@mastra/code-sdk 1.19.0-alpha.1 → 1.19.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp/runtime.d.ts.map +1 -1
- package/dist/acp/runtime.js +1 -0
- package/dist/acp/runtime.js.map +1 -1
- package/dist/agent-connections/tools.d.ts.map +1 -1
- package/dist/agent-connections/tools.js +67 -2
- package/dist/agent-connections/tools.js.map +1 -1
- package/dist/agents/fastembed-subprocess.d.ts +31 -0
- package/dist/agents/fastembed-subprocess.d.ts.map +1 -0
- package/dist/agents/fastembed-subprocess.js +202 -0
- package/dist/agents/fastembed-subprocess.js.map +1 -0
- package/dist/agents/instructions.d.ts +5 -2
- package/dist/agents/instructions.d.ts.map +1 -1
- package/dist/agents/instructions.js +6 -4
- package/dist/agents/instructions.js.map +1 -1
- package/dist/agents/mastracode-gateway.d.ts.map +1 -1
- package/dist/agents/mastracode-gateway.js +2 -2
- package/dist/agents/mastracode-gateway.js.map +1 -1
- package/dist/agents/memory.d.ts.map +1 -1
- package/dist/agents/memory.js +4 -6
- package/dist/agents/memory.js.map +1 -1
- package/dist/agents/model.d.ts.map +1 -1
- package/dist/agents/model.js +10 -5
- package/dist/agents/model.js.map +1 -1
- package/dist/agents/modes/build.js +1 -1
- package/dist/agents/modes/build.js.map +1 -1
- package/dist/agents/modes/plan.js +1 -1
- package/dist/agents/modes/plan.js.map +1 -1
- package/dist/agents/prompts/agent-instructions.d.ts +24 -1
- package/dist/agents/prompts/agent-instructions.d.ts.map +1 -1
- package/dist/agents/prompts/agent-instructions.js +386 -41
- package/dist/agents/prompts/agent-instructions.js.map +1 -1
- package/dist/agents/prompts/index.d.ts +3 -1
- package/dist/agents/prompts/index.d.ts.map +1 -1
- package/dist/agents/prompts/index.js +16 -5
- package/dist/agents/prompts/index.js.map +1 -1
- package/dist/agents/prompts/plan.d.ts +2 -0
- package/dist/agents/prompts/plan.d.ts.map +1 -1
- package/dist/agents/prompts/plan.js +10 -8
- package/dist/agents/prompts/plan.js.map +1 -1
- package/dist/agents/sandbox-filesystem.d.ts +25 -0
- package/dist/agents/sandbox-filesystem.d.ts.map +1 -1
- package/dist/agents/sandbox-filesystem.js +47 -6
- package/dist/agents/sandbox-filesystem.js.map +1 -1
- package/dist/auth/account-rotation-processor.d.ts +23 -0
- package/dist/auth/account-rotation-processor.d.ts.map +1 -1
- package/dist/auth/account-rotation-processor.js +63 -1
- package/dist/auth/account-rotation-processor.js.map +1 -1
- package/dist/auth/index.js +2 -2
- package/dist/auth/storage.d.ts +8 -0
- package/dist/auth/storage.d.ts.map +1 -1
- package/dist/auth/storage.js +37 -3
- package/dist/auth/storage.js.map +1 -1
- package/dist/experimental-agent.d.ts +8 -0
- package/dist/experimental-agent.d.ts.map +1 -1
- package/dist/experimental-agent.js +12 -1
- package/dist/experimental-agent.js.map +1 -1
- package/dist/headless/cli.d.ts.map +1 -1
- package/dist/headless/cli.js +2 -1
- package/dist/headless/cli.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +21 -9
- package/dist/index.js.map +1 -1
- package/dist/onboarding/settings.d.ts +4 -0
- package/dist/onboarding/settings.d.ts.map +1 -1
- package/dist/onboarding/settings.js +6 -2
- package/dist/onboarding/settings.js.map +1 -1
- package/dist/schedules/scheduler.d.ts.map +1 -1
- package/dist/schedules/scheduler.js +3 -2
- package/dist/schedules/scheduler.js.map +1 -1
- package/dist/utils/token-estimator.d.ts.map +1 -1
- package/dist/utils/token-estimator.js +2 -1
- package/dist/utils/token-estimator.js.map +1 -1
- package/package.json +11 -11
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox-filesystem.js","names":["posixPath"],"sources":["../../src/agents/sandbox-filesystem.ts"],"sourcesContent":["/**\n * SandboxFilesystem\n *\n * A `WorkspaceFilesystem` that stores files inside a remote `MastraSandbox`\n * (e.g. a Railway VM) rather than on the server host. File operations are\n * implemented by shelling out through the sandbox's `executeCommand`, so the\n * agent's file tools and command tools share one VM and one view of the repo.\n * When the sandbox exposes its own `filesystem`, file operations use it\n * instead, which takes one round trip rather than several commands; grep and\n * walks still run as shell commands.\n *\n * Paths are workspace-relative (`/src/foo.ts`) and resolve under the sandbox\n * working directory (`basePath`). A traversal guard rejects any path that\n * escapes the workdir, mirroring `LocalFilesystem`'s contained mode.\n *\n * Reads/writes use base64 over the wire so binary content survives the shell.\n */\n\nimport { posix as posixPath } from 'node:path';\nimport type {\n CopyOptions,\n FileContent,\n FileEntry,\n FileStat,\n FilesystemGrepMatch,\n FilesystemGrepOptions,\n FilesystemGrepResult,\n FilesystemInfo,\n ListOptions,\n ProviderStatus,\n ReadOptions,\n RemoveOptions,\n WalkEntry,\n WalkOptions,\n WorkspaceFilesystem,\n WriteOptions,\n} from '@mastra/core/workspace';\nimport {\n DirectoryNotFoundError,\n FileExistsError,\n FileNotFoundError,\n getMimeType,\n IsDirectoryError,\n NotDirectoryError,\n UnsupportedGrepPatternError,\n} from '@mastra/core/workspace';\n\n/**\n * Sentinel exit codes used by guard clauses that run before the real command,\n * so shell failures can be mapped to typed filesystem errors.\n */\nconst EXIT_NOT_FOUND = 20;\nconst EXIT_IS_DIRECTORY = 21;\nconst EXIT_EXISTS = 22;\nconst EXIT_NOT_DIRECTORY = 23;\n\n/** Minimal command result shape we depend on. */\nexport interface SandboxCommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/** Minimal sandbox surface the filesystem needs. */\nexport interface SandboxExec {\n readonly id: string;\n /**\n * The sandbox's own file API, when it has one (`WorkspaceSandbox.filesystem`).\n * File operations go through it instead of shell commands.\n */\n readonly filesystem?: WorkspaceFilesystem;\n executeCommand(\n command: string,\n args?: string[],\n options?: { timeout?: number; maxRetainedBytes?: number },\n ): Promise<SandboxCommandResult>;\n}\n\nexport interface SandboxFilesystemOptions {\n /** Live sandbox to run commands in. */\n sandbox: SandboxExec;\n /**\n * Absolute path inside the sandbox that is the workspace root — or a lazy\n * resolver for it. The resolver form exists for sandboxes whose workspace\n * root is only knowable once the VM is running (e.g. `$HOME/<repo>` under\n * a provider-chosen home dir): it is awaited on the first file operation\n * (which itself may lazily start the VM) and the result is memoized.\n */\n workdir: string | (() => Promise<string> | string);\n /** Optional stable id; defaults to a sandbox-derived id. */\n id?: string;\n /**\n * Check that symlinks don't lead outside the workdir when using the\n * sandbox's native filesystem. Off by default: native file APIs follow\n * symlinks, and inside a sandbox the agent can read anything with a command\n * anyway. Turn it on when files are served to someone other than the agent.\n *\n * Each path is checked once per instance, so keep such instances\n * short-lived. Without a native filesystem the shell path always checks.\n */\n verifySymlinks?: boolean;\n}\n\ntype ContainmentCheck = 'target' | 'dest' | 'parent';\n\n/** Default per-command deadline so a hung sandbox can't block file tools forever. */\nconst COMMAND_TIMEOUT_MS = 30_000;\n\n/**\n * Explain why a native grep command failed so callers can tell a timeout or\n * broken toolchain apart from a pattern the engine cannot express.\n */\nfunction describeGrepFailure(result: SandboxCommandResult): string {\n if (result.exitCode === 124) return `timed out after ${COMMAND_TIMEOUT_MS / 1000}s`;\n const stderrLine = result.stderr\n .split('\\n')\n .map(line => line.trim())\n .find(Boolean);\n const detail = stderrLine ? `: ${stderrLine.length > 200 ? `${stderrLine.slice(0, 200)}…` : stderrLine}` : '';\n return `exit code ${result.exitCode}${detail}`;\n}\n\n/** Single-quote a string for safe POSIX shell interpolation. */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\ninterface SearchTools {\n rg: boolean;\n gnuGrep: boolean;\n git: boolean;\n /** `grep -P` works, and so does `git grep -P` when git is present. */\n pcre: boolean;\n}\n\n/** One command that reports which search tools the sandbox has, one name per line. */\nconst SEARCH_TOOLS_PROBE =\n 'command -v rg >/dev/null 2>&1 && echo rg; ' +\n \"grep --version 2>/dev/null | head -n 1 | grep -q 'GNU grep' && echo gnu-grep; \" +\n \"printf 'a1\\\\n' | grep -qP '\\\\d(?=)' 2>/dev/null && echo grep-pcre; \" +\n 'if command -v git >/dev/null 2>&1; then echo git; ' +\n // git can be built without PCRE; check it on a throwaway repository.\n 'd=$(mktemp -d 2>/dev/null) && { ' +\n \"(cd \\\"$d\\\" && git init -q && printf 'a1\\\\n' >f && git grep -q --untracked -P -e '\\\\d(?=)') >/dev/null 2>&1 && echo git-pcre; \" +\n 'rm -rf \"$d\"; }; fi; true';\n\nfunction isInsideNodeModules(path: string): boolean {\n return path.split('/').includes('node_modules');\n}\n\n/** Lines a grep engine printed for one file: matches plus surrounding context. */\ninterface GrepFileLines {\n matches: FilesystemGrepMatch[];\n linesByNumber: Map<number, string>;\n}\n\nfunction fileLines(files: Map<string, GrepFileLines>, filePath: string): GrepFileLines {\n let state = files.get(filePath);\n if (!state) {\n state = { matches: [], linesByNumber: new Map() };\n files.set(filePath, state);\n }\n return state;\n}\n\n/** Turn per-file lines into results relative to `abs`, attaching before/after context. */\nfunction toGrepResults(files: Map<string, GrepFileLines>, abs: string, contextLines: number): FilesystemGrepResult[] {\n const results: FilesystemGrepResult[] = [];\n for (const [filePath, state] of files) {\n if (state.matches.length === 0) continue;\n const rel = posixPath.relative(abs, filePath) || posixPath.basename(filePath);\n const matches = state.matches.map(match => {\n if (contextLines <= 0) return match;\n const before: string[] = [];\n for (let n = match.line - 1; n >= Math.max(1, match.line - contextLines); n--) {\n const text = state.linesByNumber.get(n);\n if (text === undefined) break;\n before.unshift(text);\n }\n const after: string[] = [];\n for (let n = match.line + 1; n <= match.line + contextLines; n++) {\n const text = state.linesByNumber.get(n);\n if (text === undefined) break;\n after.push(text);\n }\n return { ...match, before, after };\n });\n results.push({ path: rel, matches });\n }\n return results;\n}\n\nfunction isFileContentString(content: FileContent): content is string {\n return typeof content === 'string';\n}\n\nfunction toBuffer(content: FileContent): Buffer {\n if (isFileContentString(content)) return Buffer.from(content, 'utf8');\n return Buffer.from(content);\n}\n\nexport class SandboxFilesystem implements WorkspaceFilesystem {\n readonly id: string;\n readonly name = 'SandboxFilesystem';\n readonly provider = 'sandbox';\n status: ProviderStatus = 'ready';\n\n private readonly sandbox: SandboxExec;\n private readonly workdirSource: string | (() => Promise<string> | string);\n private resolvedBase?: string;\n private resolvingBase?: Promise<string>;\n private readonly verifySymlinks: boolean;\n /** `check:absolutePath` keys that passed while the entry existed. */\n private readonly verified = new Set<string>();\n\n constructor(options: SandboxFilesystemOptions) {\n this.sandbox = options.sandbox;\n this.workdirSource = options.workdir;\n this.verifySymlinks = options.verifySymlinks ?? false;\n if (typeof options.workdir === 'string') this.resolvedBase = options.workdir;\n // Include the workdir when known: one sandbox can back several\n // filesystems rooted at different checkouts, and each needs a distinct\n // id. Lazy-workdir callers pass an explicit id.\n this.id =\n options.id ??\n (typeof options.workdir === 'string'\n ? `sandbox-fs:${options.sandbox.id}:${options.workdir}`\n : `sandbox-fs:${options.sandbox.id}`);\n }\n\n /** The resolved workspace root; empty until a lazy workdir first resolves. */\n get basePath(): string {\n return this.resolvedBase ?? '';\n }\n\n /** Await (and memoize) the workspace root, resolving a lazy workdir once. */\n private async base(): Promise<string> {\n if (this.resolvedBase) return this.resolvedBase;\n const source = this.workdirSource;\n if (typeof source === 'string') return (this.resolvedBase = source);\n this.resolvingBase ??= Promise.resolve()\n .then(source)\n .then(resolved => {\n if (!resolved) throw new Error('Sandbox workspace root resolution returned an empty path');\n return (this.resolvedBase = resolved);\n })\n .finally(() => {\n this.resolvingBase = undefined;\n });\n return this.resolvingBase;\n }\n\n // ── Path handling ──────────────────────────────────────────────────────\n\n /**\n * Resolve a workspace path to an absolute path inside the sandbox, enforcing\n * that it stays within the workdir. Awaits the workspace root first, which\n * for a lazy workdir may start the VM.\n */\n private async resolveAsync(inputPath: string): Promise<string> {\n return this.resolveAgainst(await this.base(), inputPath);\n }\n\n /**\n * Resolve a workspace path against a known base, enforcing that it stays\n * within the workdir.\n *\n * Accepts both workspace-relative paths (`src/foo.ts`, `/src/foo.ts`) and\n * absolute sandbox paths that already live under the workdir — the agent's\n * prompt advertises the workdir as its working directory, so tools are\n * routinely called with fully-qualified paths like `<workdir>/src/foo.ts`.\n */\n private resolveAgainst(basePath: string, inputPath: string): string {\n const base = posixPath.normalize(basePath);\n const normalizedInput = posixPath.normalize(inputPath);\n const rel =\n normalizedInput === base\n ? ''\n : normalizedInput.startsWith(`${base}/`)\n ? normalizedInput.slice(base.length + 1)\n : inputPath.startsWith('/')\n ? inputPath.slice(1)\n : inputPath;\n const resolved = posixPath.normalize(posixPath.join(base, rel));\n if (resolved !== base && !resolved.startsWith(`${base}/`)) {\n throw new Error(`Path escapes workspace root: ${inputPath}`);\n }\n return resolved;\n }\n\n resolveAbsolutePath(inputPath: string): string | undefined {\n // Sync interface: a lazy workdir that has not resolved yet has no\n // absolute form to offer.\n if (!this.resolvedBase) return undefined;\n return this.resolveAgainst(this.resolvedBase, inputPath);\n }\n\n // ── Command helper ─────────────────────────────────────────────────────\n\n private async exec(script: string): Promise<SandboxCommandResult> {\n // File reads come back as base64 on stdout and listings/grep are parsed\n // line by line, so dropping the oldest output would corrupt results.\n return this.sandbox.executeCommand('sh', ['-c', script], {\n timeout: COMMAND_TIMEOUT_MS,\n maxRetainedBytes: Infinity,\n });\n }\n\n /**\n * Lexical guard catches `..` traversal, but a symlink inside the workdir can\n * still point outside it. After resolving a path that refers to an existing\n * entry, verify its realpath is still contained in the workdir.\n *\n * Canonicalization tries `realpath`, then `readlink -f` (GNU/busybox), then\n * `cd && pwd -P` for directories — covering GNU hosts, macOS/BSD, and\n * busybox. If the path exists but cannot be canonicalized we fail CLOSED:\n * returning without a check would let a symlink bypass containment.\n */\n private async assertContainedRealpath(abs: string, inputPath: string): Promise<boolean> {\n const result = await this.exec(\n [\n `p=${shellQuote(abs)}`,\n `if [ ! -e \"$p\" ] && [ ! -L \"$p\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n // The workdir itself may contain symlinked components (/tmp on macOS),\n // so canonicalize it as the comparison root.\n `root=$(cd ${shellQuote(this.basePath)} 2>/dev/null && pwd -P)`,\n `[ -n \"$root\" ] || exit 1`,\n `rp=$(realpath \"$p\" 2>/dev/null) || rp=$(readlink -f \"$p\" 2>/dev/null) || { [ -d \"$p\" ] && rp=$(cd \"$p\" 2>/dev/null && pwd -P); }`,\n `[ -n \"$rp\" ] || exit 1`,\n `printf '%s\\\\n%s' \"$root\" \"$rp\"`,\n ].join('\\n'),\n );\n // Path doesn't exist yet: nothing to canonicalize (writes to a fresh leaf\n // are covered by assertContainedDest checking the parent directory).\n if (result.exitCode === EXIT_NOT_FOUND) return false;\n const [root, real] = result.stdout.split('\\n').map(s => s.trim());\n if (result.exitCode !== 0 || !root || !real) {\n throw new Error(`Unable to verify path stays within workspace root: ${inputPath}`);\n }\n if (real !== root && !real.startsWith(`${root}/`)) {\n throw new Error(`Path escapes workspace root (symlink): ${inputPath}`);\n }\n return true;\n }\n\n /**\n * Guard for write destinations. The lexical guard catches `..`, but a symlink\n * inside the workdir can redirect a write outside it. For an existing target\n * we check its realpath; for a not-yet-existing target we check the realpath\n * of its nearest existing ancestor directory, since a symlinked parent is the\n * escape vector (e.g. `link -> /etc` then writing `link/passwd`).\n */\n private async assertContainedDest(abs: string, inputPath: string): Promise<boolean> {\n // First check the target itself (covers overwriting an existing symlink).\n const exists = await this.assertContainedRealpath(abs, inputPath);\n // Then check the parent directory's realpath; readlink -f resolves the\n // nearest existing ancestor when the leaf doesn't exist yet.\n const parent = posixPath.dirname(abs);\n if (parent && parent !== abs) {\n await this.assertContainedRealpath(parent, inputPath);\n }\n return exists;\n }\n\n /**\n * Before a native filesystem call, run the containment check the shell path\n * runs for that operation, when `verifySymlinks` is on. A pass is remembered\n * only for an entry that exists: a missing path may later appear as a\n * symlink that leads outside the workdir.\n */\n private async verifyNative(check: ContainmentCheck, abs: string, inputPath: string): Promise<void> {\n if (!this.verifySymlinks) return;\n const key = `${check}:${abs}`;\n if (this.verified.has(key)) return;\n const existed =\n check === 'dest'\n ? await this.assertContainedDest(abs, inputPath)\n : await this.assertContainedRealpath(check === 'parent' ? posixPath.dirname(abs) : abs, inputPath);\n if (existed) this.verified.add(key);\n }\n\n private async execOk(script: string, context: string): Promise<SandboxCommandResult> {\n const result = await this.exec(script);\n if (result.exitCode !== 0) {\n throw new Error(`${context} failed (exit ${result.exitCode}): ${result.stderr.trim() || result.stdout.trim()}`);\n }\n return result;\n }\n\n // ── File operations ────────────────────────────────────────────────────\n\n async readFile(path: string, options?: ReadOptions): Promise<string | Buffer> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', abs, path);\n return native.readFile(abs, options);\n }\n await this.assertContainedRealpath(abs, path);\n // Guard clauses first: redirecting from a directory \"succeeds\" with empty\n // output on some shells, so classify before reading.\n const result = await this.exec(\n `if [ -d ${shellQuote(abs)} ]; then exit ${EXIT_IS_DIRECTORY}; elif [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; base64 < ${shellQuote(abs)}`,\n );\n if (result.exitCode === EXIT_IS_DIRECTORY) throw new IsDirectoryError(path);\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(path);\n if (result.exitCode !== 0) {\n throw new Error(`readFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n const buffer = Buffer.from(result.stdout.replace(/\\s/g, ''), 'base64');\n if (options?.encoding) {\n return buffer.toString(options.encoding);\n }\n return buffer;\n }\n\n async writeFile(path: string, content: FileContent, options?: WriteOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('dest', abs, path);\n return native.writeFile(abs, content, options);\n }\n await this.assertContainedDest(abs, path);\n const b64 = toBuffer(content).toString('base64');\n const dir = posixPath.dirname(abs);\n const mkdir = options?.recursive === false ? '' : `mkdir -p ${shellQuote(dir)} && `;\n if (options?.overwrite === false) {\n // `set -C` (noclobber) makes the redirect itself the exclusivity check —\n // no exists() pre-check that could race with a concurrent writer.\n const result = await this.exec(\n `${mkdir}{ (set -C; printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}) 2>/dev/null || { [ -e ${shellQuote(abs)} ] && exit ${EXIT_EXISTS} || exit 1; }; }`,\n );\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(path);\n if (result.exitCode !== 0) {\n throw new Error(`writeFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n await this.execOk(`${mkdir}printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}`, `writeFile ${path}`);\n }\n\n async appendFile(path: string, content: FileContent): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('dest', abs, path);\n return native.appendFile(abs, content);\n }\n await this.assertContainedDest(abs, path);\n const b64 = toBuffer(content).toString('base64');\n await this.execOk(\n `mkdir -p ${shellQuote(posixPath.dirname(abs))} && printf %s ${shellQuote(b64)} | base64 -d >> ${shellQuote(abs)}`,\n `appendFile ${path}`,\n );\n }\n\n async deleteFile(path: string, options?: RemoveOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('parent', abs, path);\n return native.deleteFile(abs, options);\n }\n // Contain the parent's realpath: deleting `link/file` where `link` points\n // outside the workdir must fail, while deleting a symlink entry itself\n // (which lives inside the workdir) stays allowed.\n await this.assertContainedRealpath(posixPath.dirname(abs), path);\n if (options?.force) {\n // `rm -f` already succeeds for a missing file, but still fails for\n // directories and permission errors — surface those.\n await this.execOk(`rm -f ${shellQuote(abs)}`, `deleteFile ${path}`);\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; rm ${shellQuote(abs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(path);\n if (result.exitCode !== 0) {\n throw new Error(`deleteFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n async copyFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n const srcAbs = await this.resolveAsync(src);\n const destAbs = await this.resolveAsync(dest);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', srcAbs, src);\n await this.verifyNative('dest', destAbs, dest);\n return native.copyFile(srcAbs, destAbs, options);\n }\n await this.assertContainedRealpath(srcAbs, src);\n await this.assertContainedDest(destAbs, dest);\n const recursive = options?.recursive ? '-r ' : '';\n if (options?.overwrite === false) {\n // Atomic no-clobber: directories claim the destination with an exclusive\n // mkdir; files copy to a temp name then hardlink into place (link(2)\n // fails if the destination exists). No racy exists() pre-check.\n const result = await this.exec(\n [\n `src=${shellQuote(srcAbs)}`,\n `dest=${shellQuote(destAbs)}`,\n `if [ ! -e \"$src\" ] && [ ! -L \"$src\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n `mkdir -p ${shellQuote(posixPath.dirname(destAbs))} || exit 1`,\n `if [ -d \"$src\" ]; then`,\n ` mkdir \"$dest\" 2>/dev/null || exit ${EXIT_EXISTS}`,\n ` cp -R \"$src\"/. \"$dest\"/`,\n `else`,\n ` tmp=\"$dest.__cptmp$$\"`,\n ` cp \"$src\" \"$tmp\" || exit 1`,\n ` ln \"$tmp\" \"$dest\" 2>/dev/null || { rm -f \"$tmp\"; [ -e \"$dest\" ] && exit ${EXIT_EXISTS} || exit 1; }`,\n ` rm -f \"$tmp\"`,\n `fi`,\n ].join('\\n'),\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(dest);\n if (result.exitCode !== 0) {\n throw new Error(`copyFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(srcAbs)} ]; then exit ${EXIT_NOT_FOUND}; fi; mkdir -p ${shellQuote(posixPath.dirname(destAbs))} && cp ${recursive}${shellQuote(srcAbs)} ${shellQuote(destAbs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode !== 0) {\n throw new Error(`copyFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n async moveFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n const srcAbs = await this.resolveAsync(src);\n const destAbs = await this.resolveAsync(dest);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', srcAbs, src);\n await this.verifyNative('dest', destAbs, dest);\n return native.moveFile(srcAbs, destAbs, options);\n }\n await this.assertContainedRealpath(srcAbs, src);\n await this.assertContainedDest(destAbs, dest);\n if (options?.overwrite === false) {\n // `mv -n` exits 0 even when it skips, so detect a skipped move by the\n // source surviving. The no-clobber rename itself is atomic; no racy\n // exists() pre-check.\n const result = await this.exec(\n [\n `src=${shellQuote(srcAbs)}`,\n `dest=${shellQuote(destAbs)}`,\n `if [ ! -e \"$src\" ] && [ ! -L \"$src\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n `mkdir -p ${shellQuote(posixPath.dirname(destAbs))} || exit 1`,\n `mv -n \"$src\" \"$dest\" 2>/dev/null || exit 1`,\n `if [ -e \"$src\" ] || [ -L \"$src\" ]; then exit ${EXIT_EXISTS}; fi`,\n ].join('\\n'),\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(dest);\n if (result.exitCode !== 0) {\n throw new Error(`moveFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(srcAbs)} ]; then exit ${EXIT_NOT_FOUND}; fi; mkdir -p ${shellQuote(posixPath.dirname(destAbs))} && mv ${shellQuote(srcAbs)} ${shellQuote(destAbs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode !== 0) {\n throw new Error(`moveFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n // ── Directory operations ───────────────────────────────────────────────\n\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('dest', abs, path);\n return native.mkdir(abs, options);\n }\n await this.assertContainedDest(abs, path);\n const flag = options?.recursive === false ? '' : '-p ';\n await this.execOk(`mkdir ${flag}${shellQuote(abs)}`, `mkdir ${path}`);\n }\n\n async rmdir(path: string, options?: RemoveOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('parent', abs, path);\n return native.rmdir(abs, options);\n }\n // Same parent containment as deleteFile — `rm -r` through a symlinked\n // parent would otherwise delete outside the workspace.\n await this.assertContainedRealpath(posixPath.dirname(abs), path);\n if (options?.recursive) {\n const force = options?.force ? '-f ' : '';\n await this.execOk(`rm -r ${force}${shellQuote(abs)}`, `rmdir ${path}`);\n return;\n }\n const result = await this.exec(`rmdir ${shellQuote(abs)}`);\n if (result.exitCode !== 0 && !options?.force) {\n throw new Error(`Directory not empty or not found: ${path}`);\n }\n }\n\n async readdir(path: string, options?: ListOptions): Promise<FileEntry[]> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', abs, path);\n return native.readdir(abs, options);\n }\n await this.assertContainedRealpath(abs, path);\n if (options?.recursive) {\n // Recursive listing emitting \"type\\tpath\". `find -printf` is GNU-only\n // (fails on macOS/BSD hosts backing a local sandbox), so classify each\n // entry with a portable shell loop instead.\n const result = await this.exec(\n `test -d ${shellQuote(abs)} && find ${shellQuote(abs)} -mindepth 1 ${options.maxDepth ? `-maxdepth ${Number(options.maxDepth)} ` : ''}2>/dev/null | while IFS= read -r f; do if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`,\n );\n if (result.exitCode !== 0) throw new Error(`Directory not found: ${path}`);\n return this.parseFindOutput(result.stdout, abs, options);\n }\n // Non-recursive: list with name + type via a portable loop. Use printf,\n // not echo — bash-as-/bin/sh (macOS local sandboxes) does not expand \\t\n // in echo arguments.\n const result = await this.exec(\n `cd ${shellQuote(abs)} 2>/dev/null && for f in * .[!.]*; do [ -e \"$f\" ] || continue; if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`,\n );\n if (result.exitCode !== 0) throw new Error(`Directory not found: ${path}`);\n return this.parseListOutput(result.stdout, options);\n }\n\n private parseListOutput(stdout: string, options?: ListOptions): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const type = line.slice(0, tab) === 'd' ? 'directory' : 'file';\n const name = line.slice(tab + 1);\n if (!name || name === '.' || name === '..') continue;\n if (type === 'file' && !this.matchesExtension(name, options?.extension)) continue;\n entries.push({ name, type });\n }\n return entries;\n }\n\n private parseFindOutput(stdout: string, base: string, options?: ListOptions): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const type = line.slice(0, tab) === 'd' ? 'directory' : 'file';\n const fullPath = line.slice(tab + 1);\n const name = posixPath.relative(base, fullPath);\n if (!name) continue;\n if (type === 'file' && !this.matchesExtension(name, options?.extension)) continue;\n entries.push({ name, type });\n }\n return entries;\n }\n\n private matchesExtension(name: string, extension?: string | string[]): boolean {\n if (!extension) return true;\n const exts = Array.isArray(extension) ? extension : [extension];\n return exts.some(ext => name.endsWith(ext));\n }\n\n // ── Native walk / grep capabilities ────────────────────────────────────\n\n /**\n * Walk the tree in a single sandbox command instead of one readdir round\n * trip per directory. Uses `find` with a portable classification loop\n * (`find -printf` is GNU-only and fails on macOS/BSD hosts). `find` does\n * not follow symlinked directories by default, matching the host-side\n * walker's no-recursion-into-symlinks behavior.\n */\n async walk(path: string, options?: WalkOptions): Promise<WalkEntry[]> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedRealpath(abs, path);\n const maxDepth =\n options?.maxDepth !== undefined && Number.isFinite(options.maxDepth)\n ? `-maxdepth ${Math.max(0, Math.floor(options.maxDepth))} `\n : '';\n // Prune hidden entries in-sandbox when not requested, so a huge hidden\n // tree (e.g. `.git`) doesn't inflate the response. `.gitignore` files\n // still come back when the caller applies them.\n const keepGitignore = options?.includeGitignoreFiles ? `! \\\\( -type f -name .gitignore \\\\) ` : '';\n const hiddenPrune = options?.includeHidden ? '' : `\\\\( -name '.*' ${keepGitignore}\\\\) -prune -o `;\n // Skip directories like node_modules entirely instead of listing them\n // only for the caller to filter them out.\n const skipNames = options?.skipDirectoryNames?.filter(Boolean) ?? [];\n const skipPrune = skipNames.length\n ? `\\\\( -type d \\\\( ${skipNames.map(name => `-name ${shellQuote(name)}`).join(' -o ')} \\\\) \\\\) -prune -o `\n : '';\n // Emit \"flag\\tpath[\\ttarget]\" — flag is d/f for regular entries, D/F for\n // symlinks (with the link target as a third field).\n const script =\n `root=${shellQuote(abs)}\\n` +\n `[ -e \"$root\" ] || [ -L \"$root\" ] || exit ${EXIT_NOT_FOUND}\\n` +\n `[ -d \"$root\" ] || exit ${EXIT_NOT_DIRECTORY}\\n` +\n `find \"$root\" -mindepth 1 ${maxDepth}${hiddenPrune}${skipPrune}-print 2>/dev/null | while IFS= read -r f; do ` +\n `if [ -L \"$f\" ]; then if [ -d \"$f\" ]; then t=D; else t=F; fi; printf '%s\\\\t%s\\\\t%s\\\\n' \"$t\" \"$f\" \"$(readlink \"$f\")\"; ` +\n `elif [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`;\n const result = await this.exec(script);\n if (result.exitCode === EXIT_NOT_FOUND) throw new DirectoryNotFoundError(path);\n if (result.exitCode === EXIT_NOT_DIRECTORY) throw new NotDirectoryError(path);\n if (result.exitCode !== 0) {\n throw new Error(`walk ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n const entries: WalkEntry[] = [];\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const flag = line.slice(0, tab);\n const isSymlink = flag === 'D' || flag === 'F';\n let fullPath = line.slice(tab + 1);\n let symlinkTarget: string | undefined;\n if (isSymlink) {\n const tab2 = fullPath.lastIndexOf('\\t');\n if (tab2 >= 0) {\n symlinkTarget = fullPath.slice(tab2 + 1) || undefined;\n fullPath = fullPath.slice(0, tab2);\n }\n }\n const rel = posixPath.relative(abs, fullPath);\n if (!rel || rel.startsWith('..')) continue;\n entries.push({\n name: posixPath.basename(rel),\n type: flag === 'd' || flag === 'D' ? 'directory' : 'file',\n ...(isSymlink ? { isSymlink: true, ...(symlinkTarget ? { symlinkTarget } : {}) } : {}),\n path: rel,\n });\n }\n return entries;\n }\n\n /**\n * Content search executed inside the sandbox in one command, using the best\n * engine the sandbox has: ripgrep, then GNU grep (with git choosing files\n * inside repositories), then POSIX `grep -rnE`. Patterns the grep engines\n * can't express (PCRE-style classes, word boundaries, lookarounds,\n * non-greedy quantifiers) throw {@link UnsupportedGrepPatternError} so\n * callers use their host-side walk.\n *\n * ripgrep and GNU grep apply every `.gitignore` in the tree, relative to the\n * directory that holds it, and skip `node_modules` unless the search path\n * is inside one. Callers still apply their own hidden/glob filtering.\n */\n async grep(options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const abs = await this.resolveAsync(options.path);\n await this.assertContainedRealpath(abs, options.path);\n const tools = await this.searchTools();\n if (tools.rg) return this.grepWithRipgrep(abs, options);\n if (tools.gnuGrep) return this.grepWithGnuGrep(abs, options, tools);\n return this.grepWithPosixGrep(abs, options);\n }\n\n private toolsCheck: Promise<SearchTools> | undefined;\n\n private searchTools(): Promise<SearchTools> {\n const check = (this.toolsCheck ??= this.exec(SEARCH_TOOLS_PROBE).then(result => {\n if (result.exitCode !== 0) throw new Error(`search tool probe exited with ${result.exitCode}`);\n const found = new Set(result.stdout.split('\\n').map(line => line.trim()));\n const git = found.has('git');\n return {\n rg: found.has('rg'),\n gnuGrep: found.has('gnu-grep'),\n git,\n pcre: found.has('grep-pcre') && (!git || found.has('git-pcre')),\n };\n }));\n // Only a successful probe is cached; a failed one (e.g. the sandbox wasn't\n // ready) is retried on the next search instead of pinning the slow path.\n return check.catch(() => {\n if (this.toolsCheck === check) this.toolsCheck = undefined;\n return { rg: false, gnuGrep: false, git: false, pcre: false };\n });\n }\n\n private async grepWithRipgrep(abs: string, options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const args = [\n // --no-require-git applies .gitignore files outside a git checkout too\n // (e.g. a multi-repo root). A path passed explicitly is searched even\n // when ignored, so targeting `dist/` or `node_modules/x` still works.\n 'rg --json --hidden --no-require-git',\n // .git is filtered host-side too; exclude it here so its object files\n // don't inflate the response.\n `-g ${shellQuote('!.git/**')}`,\n isInsideNodeModules(abs) ? '' : `-g ${shellQuote('!**/node_modules/**')}`,\n options.caseSensitive ? '' : '-i',\n options.maxCountPerFile !== undefined ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : '',\n options.contextLines ? `-C ${Math.max(0, Math.floor(options.contextLines))}` : '',\n `-e ${shellQuote(options.pattern)}`,\n shellQuote(abs),\n ]\n .filter(Boolean)\n .join(' ');\n const result = await this.exec(args);\n // rg exits 1 when there are no matches, 2 on any error. A bad pattern\n // produces no output at all, but a per-file error (e.g. an unreadable\n // file) also yields exit 2 while still emitting matches for every other\n // file. Keep those partial results; only treat \"error with no matches\"\n // as an unsupported pattern so the caller falls back to the host walk.\n if (result.exitCode === 1) return [];\n const results = this.parseRipgrepJson(result.stdout, abs, options);\n if (result.exitCode !== 0 && results.length === 0) {\n throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));\n }\n return results;\n }\n\n private parseRipgrepJson(stdout: string, abs: string, options: FilesystemGrepOptions): FilesystemGrepResult[] {\n const files = new Map<string, GrepFileLines>();\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n let event: any;\n try {\n event = JSON.parse(line);\n } catch {\n continue;\n }\n if (event.type !== 'match' && event.type !== 'context') continue;\n const filePath: string | undefined = event.data?.path?.text;\n const lineNumber: number | undefined = event.data?.line_number;\n if (!filePath || !lineNumber) continue;\n const state = fileLines(files, filePath);\n const text: string = (event.data?.lines?.text ?? '').replace(/\\r?\\n$/, '');\n state.linesByNumber.set(lineNumber, text);\n if (event.type === 'match') {\n // rg submatch offsets are byte offsets into the line; convert to a\n // UTF-16 (JS string) index for the capability contract.\n const byteStart: number = event.data?.submatches?.[0]?.start ?? 0;\n const column = Buffer.from(text, 'utf8').subarray(0, byteStart).toString('utf8').length;\n state.matches.push({ line: lineNumber, column, text });\n }\n }\n return this.applyTotalCap(toGrepResults(files, abs, options.contextLines ?? 0), options.maxTotalMatches);\n }\n\n /**\n * Patterns whose meaning differs between POSIX ERE and JS RegExp. The grep\n * runs with ERE but match columns are recomputed with JS, so anything that\n * only one side understands (PCRE classes, lookarounds, lazy quantifiers,\n * POSIX bracket classes, GNU word anchors) must fall back to the host walk.\n */\n private static readonly ERE_UNSUPPORTED = /\\\\[dDwWsSbB<>]|\\(\\?|[*+?}]\\?|\\[:[a-z]+:\\]/;\n\n /**\n * Escapes that `grep -P` (PCRE) and JS RegExp (without the `u` flag) both\n * accept but read differently, e.g. `\\A` is \"start of subject\" in PCRE and\n * a literal `A` in JS, plus POSIX bracket classes. PCRE-only syntax that JS\n * rejects (inline flags, possessive quantifiers, atomic groups) already\n * fails the JS compile below.\n */\n private static readonly PCRE_UNSUPPORTED = /\\\\[AzZGKQEhHvVRXNCpPe]|\\[:[a-z]+:\\]/;\n\n /** Reject patterns grep can't run with the same meaning as JS; return the JS regex used for columns. */\n private static grepRegex(options: FilesystemGrepOptions, pcre = false): RegExp {\n if (\n pcre\n ? SandboxFilesystem.PCRE_UNSUPPORTED.test(options.pattern)\n : SandboxFilesystem.ERE_UNSUPPORTED.test(options.pattern)\n ) {\n throw new UnsupportedGrepPatternError(\n options.pattern,\n pcre ? 'grep -P reads this syntax differently from JavaScript' : 'POSIX ERE cannot express this syntax',\n );\n }\n try {\n return new RegExp(options.pattern, options.caseSensitive ? '' : 'i');\n } catch {\n throw new UnsupportedGrepPatternError(options.pattern, 'invalid regular expression');\n }\n }\n\n /**\n * GNU grep without ripgrep. Inside a git checkout, `git grep` picks the\n * files (tracked plus untracked, every `.gitignore` applied) and GNU grep\n * prints them with context. Outside a checkout (e.g. a multi-repo root),\n * each child repository is searched the same way and plain grep covers the\n * remaining files, skipping `node_modules`. `--null` ends each file name\n * with NUL, so match (`N:`) and context (`N-`) lines parse unambiguously.\n * When grep and git support it, patterns run as PCRE (`-P`), so `\\d`,\n * `\\w`, `\\s`, `\\b`, and lookarounds don't need the host walk.\n */\n private async grepWithGnuGrep(\n abs: string,\n options: FilesystemGrepOptions,\n tools: SearchTools,\n ): Promise<FilesystemGrepResult[]> {\n const hasGit = tools.git;\n const mode = tools.pcre ? '-P' : '-E';\n const jsRegex = SandboxFilesystem.grepRegex(options, tools.pcre);\n const contextLines = Math.max(0, Math.floor(options.contextLines ?? 0));\n const grepFlags = [\n `-HnI${mode.slice(1)} --null`,\n options.caseSensitive ? '' : '-i',\n options.maxCountPerFile !== undefined ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : '',\n contextLines > 0 ? `-C ${contextLines}` : '',\n ]\n .filter(Boolean)\n .join(' ');\n const skipNodeModules = !isInsideNodeModules(abs);\n const nodeModulesPathspec = skipNodeModules ? ` ${shellQuote(':(exclude,glob)**/node_modules/**')}` : '';\n const pruneNames = skipNodeModules ? '-name .git -o -name node_modules' : '-name .git';\n const script = [\n `pat=${shellQuote(options.pattern)}`,\n `root=${shellQuote(abs)}`,\n // xargs exit codes can't tell \"no match\" from \"bad pattern\"; check first.\n `grep ${mode} -e \"$pat\" </dev/null >/dev/null 2>&1`,\n 'if [ $? -eq 2 ]; then echo \"grep: invalid regular expression\" >&2; exit 2; fi',\n 'tmp=$(mktemp -d) || exit 1',\n `trap 'rm -rf \"$tmp\"' EXIT`,\n `search_files() { xargs -0 -r grep ${grepFlags} -e \"$pat\" -- 2>/dev/null; }`,\n // A line starting with NUL names the directory later paths are relative to.\n 'search_repo() {',\n ` git -C \"$1\" grep -l -z -I --untracked ${options.caseSensitive ? '' : '-i '}${mode} -e \"$pat\" -- .${nodeModulesPathspec} >\"$tmp/files\" 2>/dev/null`,\n ' [ $? -gt 1 ] && return 1',\n ` printf '\\\\0%s\\\\n' \"$1\"`,\n ' (cd \"$1\" && search_files) <\"$tmp/files\"',\n '}',\n ...(hasGit\n ? [\n 'if git -C \"$root\" rev-parse --is-inside-work-tree >/dev/null 2>&1 && ! git -C \"$root\" check-ignore -q . 2>/dev/null; then',\n ' search_repo \"$root\" && exit 0',\n 'fi',\n `find \"$root\" -mindepth 1 -maxdepth 3 \\\\( ${skipNodeModules ? '-name node_modules -prune' : '-false'} \\\\) -o \\\\( -name .git -prune -print \\\\) >\"$tmp/repos\" 2>/dev/null`,\n ': >\"$tmp/done\"',\n 'while IFS= read -r g; do',\n ' d=${g%/.git}',\n ' search_repo \"$d\" && printf \\'%s\\\\n\\' \"$d\" >>\"$tmp/done\"',\n 'done <\"$tmp/repos\"',\n 'set --',\n 'while IFS= read -r d; do set -- \"$@\" -o -path \"$d\"; done <\"$tmp/done\"',\n ]\n : ['set --']),\n `printf '\\\\0%s\\\\n' \"$root\"`,\n `find \"$root\" -mindepth 1 \\\\( ${pruneNames} \"$@\" \\\\) -prune -o -type f -print0 2>/dev/null | search_files`,\n 'exit 0',\n ].join('\\n');\n const result = await this.exec(script);\n if (result.exitCode !== 0) {\n throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));\n }\n const files = new Map<string, GrepFileLines>();\n let base = abs;\n for (const line of result.stdout.split('\\n')) {\n if (!line || line === '--') continue;\n if (line.startsWith('\\0')) {\n base = line.slice(1);\n continue;\n }\n const nul = line.indexOf('\\0');\n if (nul <= 0) continue;\n const parsed = /^(\\d+)([:-])(.*)$/s.exec(line.slice(nul + 1));\n if (!parsed) continue;\n const lineNumber = Number(parsed[1]);\n const text = parsed[3]!;\n const state = fileLines(files, posixPath.resolve(base, line.slice(0, nul)));\n state.linesByNumber.set(lineNumber, text);\n if (parsed[2] !== ':') continue;\n const column = jsRegex.exec(text)?.index;\n if (column === undefined) {\n throw new UnsupportedGrepPatternError(options.pattern, 'POSIX ERE and JS RegExp disagree on this pattern');\n }\n state.matches.push({ line: lineNumber, column, text });\n }\n return this.applyTotalCap(toGrepResults(files, abs, contextLines), options.maxTotalMatches);\n }\n\n private async grepWithPosixGrep(abs: string, options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const jsRegex = SandboxFilesystem.grepRegex(options);\n // Reconstructing per-match context from `grep -C` text output is not\n // reliable (separator lines are ambiguous); let the host walk handle it.\n if (options.contextLines) {\n throw new UnsupportedGrepPatternError(options.pattern, 'context lines are not supported by POSIX grep');\n }\n const args = [\n 'grep -rnIE',\n // .git is filtered host-side too; skip it so object files are not scanned.\n '--exclude-dir=.git',\n options.caseSensitive ? '' : '-i',\n options.maxCountPerFile !== undefined ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : '',\n '--',\n shellQuote(options.pattern),\n shellQuote(abs),\n ]\n .filter(Boolean)\n .join(' ');\n const result = await this.exec(args);\n if (result.exitCode === 1) return [];\n // Like rg, grep exits 2 on per-file errors (e.g. an unreadable file) while\n // still printing matches for the rest; keep those partial results.\n if (result.exitCode !== 0 && !(result.exitCode === 2 && result.stdout.trim())) {\n throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));\n }\n // grep -n has no column output; recompute with the JS regex host-side so\n // columns are UTF-16 indices, consistent with the fallback implementation.\n const byFile = new Map<string, FilesystemGrepMatch[]>();\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const parsed = /^(.*?):(\\d+):(.*)$/.exec(line);\n if (!parsed) continue;\n const rel = posixPath.relative(abs, parsed[1]!) || posixPath.basename(parsed[1]!);\n const text = parsed[3]!;\n const column = jsRegex.exec(text)?.index;\n // grep matched this line but the JS regex did not: the two dialects\n // disagree on this pattern, so the columns would be wrong. Fall back.\n if (column === undefined) {\n throw new UnsupportedGrepPatternError(options.pattern, 'POSIX ERE and JS RegExp disagree on this pattern');\n }\n let matches = byFile.get(rel);\n if (!matches) {\n matches = [];\n byFile.set(rel, matches);\n }\n matches.push({ line: Number(parsed[2]), column, text });\n }\n const results = [...byFile.entries()].map(([path, matches]) => ({ path, matches }));\n return this.applyTotalCap(results, options.maxTotalMatches);\n }\n\n private applyTotalCap(results: FilesystemGrepResult[], maxTotal?: number): FilesystemGrepResult[] {\n if (maxTotal === undefined) return results;\n const capped: FilesystemGrepResult[] = [];\n let total = 0;\n for (const file of results) {\n if (total >= maxTotal) break;\n const remaining = maxTotal - total;\n const matches = file.matches.slice(0, remaining);\n total += matches.length;\n capped.push({ path: file.path, matches });\n }\n return capped;\n }\n\n // ── Path / metadata ────────────────────────────────────────────────────\n\n async exists(path: string): Promise<boolean> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) return native.exists(abs);\n const result = await this.exec(`test -e ${shellQuote(abs)}`);\n return result.exitCode === 0;\n }\n\n async stat(path: string): Promise<FileStat> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', abs, path);\n const info = await native.stat(abs);\n return {\n ...info,\n name: posixPath.basename(abs),\n path: `/${posixPath.relative(this.basePath, abs)}`,\n mimeType: info.type === 'file' ? (info.mimeType ?? getMimeType(abs)) : info.mimeType,\n };\n }\n await this.assertContainedRealpath(abs, path);\n // GNU stat: %F=type, %s=size, %Y=mtime (epoch seconds), %W=birth (or -1).\n // BSD/macOS stat (local sandbox hosts) rejects `-c`; fall back to its\n // `-f` format with the same field order (%HT=type, %z=size, %m=mtime,\n // %B=birth). Delimit with `|` — neither stat interprets `\\t` escapes in\n // its format string. `-L` reports the symlink target, like LocalFilesystem.\n const result = await this.exec(\n `stat -L -c '%F|%s|%Y|%W' ${shellQuote(abs)} 2>/dev/null || stat -L -f '%HT|%z|%m|%B' ${shellQuote(abs)}`,\n );\n if (result.exitCode !== 0) {\n throw new FileNotFoundError(path);\n }\n const [kind, sizeStr, mtimeStr, ctimeStr] = result.stdout.trim().split('|');\n const type = kind && kind.toLowerCase().includes('directory') ? 'directory' : 'file';\n const size = Number(sizeStr) || 0;\n const mtime = Number(mtimeStr) || 0;\n const ctime = Number(ctimeStr);\n return {\n name: posixPath.basename(abs),\n path: `/${posixPath.relative(this.basePath, abs)}`,\n type,\n size: type === 'directory' ? 0 : size,\n modifiedAt: new Date(mtime * 1000),\n createdAt: new Date((ctime > 0 ? ctime : mtime) * 1000),\n mimeType: type === 'file' ? getMimeType(abs) : undefined,\n };\n }\n\n // ── Lifecycle ──────────────────────────────────────────────────────────\n\n async init(): Promise<void> {\n await this.execOk(`mkdir -p ${shellQuote(await this.base())}`, 'init workdir');\n }\n\n async destroy(): Promise<void> {\n // The sandbox lifecycle is owned by the caller; nothing to tear down here.\n }\n\n async isReady(): Promise<boolean> {\n const result = await this.exec(`test -d ${shellQuote(await this.base())}`);\n return result.exitCode === 0;\n }\n\n getInfo(): FilesystemInfo {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n metadata: { basePath: this.basePath, sandboxId: this.sandbox.id },\n };\n }\n\n getInstructions(): string {\n return `Files are stored in a remote sandbox at ${this.basePath}. Use absolute workspace paths like /src/index.ts. All reads, writes and commands run inside the same sandbox.`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAM,iBAAiB;AACvB,MAAM,oBAAoB;AAC1B,MAAM,cAAc;AACpB,MAAM,qBAAqB;;AAoD3B,MAAM,qBAAqB;;;;;AAM3B,SAAS,oBA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AAc;EAC9E,MAAM,OAAO,OAAO,OAAO,KAAK;EAChC,MAAM,QAAQ,OAAO,QAAQ,KAAK;EAClC,MAAM,QAAQ,OAAO,QAAQ;EAC7B,OAAO;GACL,MAAMA,MAAU,SAAS,GAAG;GAC5B,MAAM,IAAIA,MAAU,SAAS,KAAK,UAAU,GAAG;GAC/C;GACA,MAAM,SAAS,cAAc,IAAI;GACjC,4BAAY,IAAI,KAAK,QAAQ,GAAI;GACjC,2BAAW,IAAI,MAAM,QAAQ,IAAI,QAAQ,SAAS,GAAI;GACtD,UAAU,SAAS,SAAS,YAAY,GAAG,IAAI,KAAA;EACjD;CACF;CAIA,MAAM,OAAsB;EAC1B,MAAM,KAAK,OAAO,YAAY,WAAW,MAAM,KAAK,KAAK,CAAC,KAAK,cAAc;CAC/E;CAEA,MAAM,UAAyB,CAE/B;CAEA,MAAM,UAA4B;EAEhC,QAAO,MADc,KAAK,KAAK,WAAW,WAAW,MAAM,KAAK,KAAK,CAAC,GAAG,EAAA,CAC3D,aAAa;CAC7B;CAEA,UAA0B;EACxB,OAAO;GACL,IAAI,KAAK;GACT,MAAM,KAAK;GACX,UAAU,KAAK;GACf,QAAQ,KAAK;GACb,UAAU;IAAE,UAAU,KAAK;IAAU,WAAW,KAAK,QAAQ;GAAG;EAClE;CACF;CAEA,kBAA0B;EACxB,OAAO,2CAA2C,KAAK,SAAS;CAClE;AACF"}
|
|
1
|
+
{"version":3,"file":"sandbox-filesystem.js","names":["posixPath"],"sources":["../../src/agents/sandbox-filesystem.ts"],"sourcesContent":["/**\n * SandboxFilesystem\n *\n * A `WorkspaceFilesystem` that stores files inside a remote `MastraSandbox`\n * (e.g. a Railway VM) rather than on the server host. File operations are\n * implemented by shelling out through the sandbox's `executeCommand`, so the\n * agent's file tools and command tools share one VM and one view of the repo.\n * When the sandbox exposes its own `filesystem`, file operations use it\n * instead, which takes one round trip rather than several commands; grep and\n * walks still run as shell commands.\n *\n * Paths are workspace-relative (`/src/foo.ts`) and resolve under the sandbox\n * working directory (`basePath`). A traversal guard rejects any path that\n * escapes the workdir, mirroring `LocalFilesystem`'s contained mode.\n *\n * Reads/writes use base64 over the wire so binary content survives the shell.\n */\n\nimport { posix as posixPath } from 'node:path';\nimport type {\n CopyOptions,\n FileContent,\n FileEntry,\n FileStat,\n FilesystemGrepMatch,\n FilesystemGrepOptions,\n FilesystemGrepResult,\n FilesystemInfo,\n ListOptions,\n ProviderStatus,\n ReadOptions,\n RemoveOptions,\n WalkEntry,\n WalkOptions,\n WorkspaceFilesystem,\n WriteOptions,\n} from '@mastra/core/workspace';\nimport {\n DirectoryNotFoundError,\n FileExistsError,\n FileNotFoundError,\n getMimeType,\n IsDirectoryError,\n LocalFilesystem,\n NotDirectoryError,\n UnsupportedGrepPatternError,\n} from '@mastra/core/workspace';\n\n/**\n * Sentinel exit codes used by guard clauses that run before the real command,\n * so shell failures can be mapped to typed filesystem errors.\n */\nconst EXIT_NOT_FOUND = 20;\nconst EXIT_IS_DIRECTORY = 21;\nconst EXIT_EXISTS = 22;\nconst EXIT_NOT_DIRECTORY = 23;\n\n/** Minimal command result shape we depend on. */\nexport interface SandboxCommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/** Minimal sandbox surface the filesystem needs. */\nexport interface SandboxExec {\n readonly id: string;\n /**\n * The sandbox's own file API, when it has one (`WorkspaceSandbox.filesystem`).\n * File operations go through it instead of shell commands.\n */\n readonly filesystem?: WorkspaceFilesystem;\n executeCommand(\n command: string,\n args?: string[],\n options?: { timeout?: number; maxRetainedBytes?: number },\n ): Promise<SandboxCommandResult>;\n}\n\nexport interface SandboxFilesystemOptions {\n /** Live sandbox to run commands in. */\n sandbox: SandboxExec;\n /**\n * Absolute path inside the sandbox that is the workspace root — or a lazy\n * resolver for it. The resolver form exists for sandboxes whose workspace\n * root is only knowable once the VM is running (e.g. `$HOME/<repo>` under\n * a provider-chosen home dir): it is awaited on the first file operation\n * (which itself may lazily start the VM) and the result is memoized.\n */\n workdir: string | (() => Promise<string> | string);\n /** Optional stable id; defaults to a sandbox-derived id. */\n id?: string;\n /**\n * Check that symlinks don't lead outside the workdir when using the\n * sandbox's native filesystem. Off by default: native file APIs follow\n * symlinks, and inside a sandbox the agent can read anything with a command\n * anyway. Turn it on when files are served to someone other than the agent.\n *\n * Each path is checked once per instance, so keep such instances\n * short-lived. Without a native filesystem the shell path always checks.\n */\n verifySymlinks?: boolean;\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. Values are\n * normalized like `LocalFilesystem`'s option, so `'sas'`, `'.sas'` and\n * `'.SAS'` are equivalent.\n */\n textExtensions?: string[];\n}\n\ntype ContainmentCheck = 'target' | 'dest' | 'parent';\n\n/** Default per-command deadline so a hung sandbox can't block file tools forever. */\nconst COMMAND_TIMEOUT_MS = 30_000;\n\n/**\n * Explain why a native grep command failed so callers can tell a timeout or\n * broken toolchain apart from a pattern the engine cannot express.\n */\nfunction describeGrepFailure(result: SandboxCommandResult): string {\n if (result.exitCode === 124) return `timed out after ${COMMAND_TIMEOUT_MS / 1000}s`;\n const stderrLine = result.stderr\n .split('\\n')\n .map(line => line.trim())\n .find(Boolean);\n const detail = stderrLine ? `: ${stderrLine.length > 200 ? `${stderrLine.slice(0, 200)}…` : stderrLine}` : '';\n return `exit code ${result.exitCode}${detail}`;\n}\n\n/** Single-quote a string for safe POSIX shell interpolation. */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\ninterface SearchTools {\n rg: boolean;\n gnuGrep: boolean;\n git: boolean;\n /** `grep -P` works, and so does `git grep -P` when git is present. */\n pcre: boolean;\n}\n\n/** One command that reports which search tools the sandbox has, one name per line. */\nconst SEARCH_TOOLS_PROBE =\n 'command -v rg >/dev/null 2>&1 && echo rg; ' +\n \"grep --version 2>/dev/null | head -n 1 | grep -q 'GNU grep' && echo gnu-grep; \" +\n \"printf 'a1\\\\n' | grep -qP '\\\\d(?=)' 2>/dev/null && echo grep-pcre; \" +\n 'if command -v git >/dev/null 2>&1; then echo git; ' +\n // git can be built without PCRE; check it on a throwaway repository.\n 'd=$(mktemp -d 2>/dev/null) && { ' +\n \"(cd \\\"$d\\\" && git init -q && printf 'a1\\\\n' >f && git grep -q --untracked -P -e '\\\\d(?=)') >/dev/null 2>&1 && echo git-pcre; \" +\n 'rm -rf \"$d\"; }; fi; true';\n\nfunction isInsideNodeModules(path: string): boolean {\n return path.split('/').includes('node_modules');\n}\n\n/** Lines a grep engine printed for one file: matches plus surrounding context. */\ninterface GrepFileLines {\n matches: FilesystemGrepMatch[];\n linesByNumber: Map<number, string>;\n}\n\nfunction fileLines(files: Map<string, GrepFileLines>, filePath: string): GrepFileLines {\n let state = files.get(filePath);\n if (!state) {\n state = { matches: [], linesByNumber: new Map() };\n files.set(filePath, state);\n }\n return state;\n}\n\n/** Turn per-file lines into results relative to `abs`, attaching before/after context. */\nfunction toGrepResults(files: Map<string, GrepFileLines>, abs: string, contextLines: number): FilesystemGrepResult[] {\n const results: FilesystemGrepResult[] = [];\n for (const [filePath, state] of files) {\n if (state.matches.length === 0) continue;\n const rel = posixPath.relative(abs, filePath) || posixPath.basename(filePath);\n const matches = state.matches.map(match => {\n if (contextLines <= 0) return match;\n const before: string[] = [];\n for (let n = match.line - 1; n >= Math.max(1, match.line - contextLines); n--) {\n const text = state.linesByNumber.get(n);\n if (text === undefined) break;\n before.unshift(text);\n }\n const after: string[] = [];\n for (let n = match.line + 1; n <= match.line + contextLines; n++) {\n const text = state.linesByNumber.get(n);\n if (text === undefined) break;\n after.push(text);\n }\n return { ...match, before, after };\n });\n results.push({ path: rel, matches });\n }\n return results;\n}\n\nfunction isFileContentString(content: FileContent): content is string {\n return typeof content === 'string';\n}\n\nfunction toBuffer(content: FileContent): Buffer {\n if (isFileContentString(content)) return Buffer.from(content, 'utf8');\n return Buffer.from(content);\n}\n\nexport class SandboxFilesystem implements WorkspaceFilesystem {\n readonly id: string;\n readonly name = 'SandboxFilesystem';\n readonly provider = 'sandbox';\n status: ProviderStatus = 'ready';\n\n private readonly sandbox: SandboxExec;\n private readonly workdirSource: string | (() => Promise<string> | string);\n private resolvedBase?: string;\n private resolvingBase?: Promise<string>;\n private readonly verifySymlinks: boolean;\n /**\n * Classifies file names as text: the built-in extensions plus\n * `textExtensions`, normalized exactly as `LocalFilesystem` does. Only its\n * `isTextFile` is ever called; it never touches a file.\n */\n private readonly textClassifier: LocalFilesystem;\n /** `check:absolutePath` keys that passed while the entry existed. */\n private readonly verified = new Set<string>();\n\n constructor(options: SandboxFilesystemOptions) {\n this.sandbox = options.sandbox;\n this.workdirSource = options.workdir;\n this.verifySymlinks = options.verifySymlinks ?? false;\n this.textClassifier = new LocalFilesystem({ basePath: '/', textExtensions: options.textExtensions });\n if (typeof options.workdir === 'string') this.resolvedBase = options.workdir;\n // Include the workdir when known: one sandbox can back several\n // filesystems rooted at different checkouts, and each needs a distinct\n // id. Lazy-workdir callers pass an explicit id.\n this.id =\n options.id ??\n (typeof options.workdir === 'string'\n ? `sandbox-fs:${options.sandbox.id}:${options.workdir}`\n : `sandbox-fs:${options.sandbox.id}`);\n }\n\n /** The resolved workspace root; empty until a lazy workdir first resolves. */\n get basePath(): string {\n return this.resolvedBase ?? '';\n }\n\n /**\n * Whether tools like `grep` should treat a file as text: the built-in text\n * extensions plus any `textExtensions` passed to the constructor.\n */\n isTextFile(filename: string): boolean {\n return this.textClassifier.isTextFile(filename);\n }\n\n /** Await (and memoize) the workspace root, resolving a lazy workdir once. */\n private async base(): Promise<string> {\n if (this.resolvedBase) return this.resolvedBase;\n const source = this.workdirSource;\n if (typeof source === 'string') return (this.resolvedBase = source);\n this.resolvingBase ??= Promise.resolve()\n .then(source)\n .then(resolved => {\n if (!resolved) throw new Error('Sandbox workspace root resolution returned an empty path');\n return (this.resolvedBase = resolved);\n })\n .finally(() => {\n this.resolvingBase = undefined;\n });\n return this.resolvingBase;\n }\n\n // ── Path handling ──────────────────────────────────────────────────────\n\n /**\n * Resolve a workspace path to an absolute path inside the sandbox, enforcing\n * that it stays within the workdir. Awaits the workspace root first, which\n * for a lazy workdir may start the VM.\n */\n private async resolveAsync(inputPath: string): Promise<string> {\n return this.resolveAgainst(await this.base(), inputPath);\n }\n\n /**\n * Resolve a workspace path against a known base, enforcing that it stays\n * within the workdir.\n *\n * Accepts both workspace-relative paths (`src/foo.ts`, `/src/foo.ts`) and\n * absolute sandbox paths that already live under the workdir — the agent's\n * prompt advertises the workdir as its working directory, so tools are\n * routinely called with fully-qualified paths like `<workdir>/src/foo.ts`.\n */\n private resolveAgainst(basePath: string, inputPath: string): string {\n const base = posixPath.normalize(basePath);\n const normalizedInput = posixPath.normalize(inputPath);\n const rel =\n normalizedInput === base\n ? ''\n : normalizedInput.startsWith(`${base}/`)\n ? normalizedInput.slice(base.length + 1)\n : inputPath.startsWith('/')\n ? inputPath.slice(1)\n : inputPath;\n const resolved = posixPath.normalize(posixPath.join(base, rel));\n if (resolved !== base && !resolved.startsWith(`${base}/`)) {\n throw new Error(`Path escapes workspace root: ${inputPath}`);\n }\n return resolved;\n }\n\n /**\n * A miss on an absolute path outside the workdir (e.g. `/tmp/x/a.ts`) that\n * does exist at that real sandbox path: the agent meant the sandbox path,\n * but it was remapped under the workdir. Explain that instead of a bare\n * not-found. Undefined when the path is inside the workdir or doesn't exist.\n */\n private async outsideWorkdirNotFound(inputPath: string, abs: string): Promise<FileNotFoundError | undefined> {\n const base = posixPath.normalize(this.basePath);\n const normalized = posixPath.normalize(inputPath);\n if (!inputPath.startsWith('/') || normalized === base || normalized.startsWith(`${base}/`)) return undefined;\n const probe = await this.exec(`test -e ${shellQuote(normalized)}`).catch(() => undefined);\n if (probe?.exitCode !== 0) return undefined;\n const error = new FileNotFoundError(inputPath);\n error.message = `File not found: ${inputPath} (resolved to ${abs}). File tools only reach files under ${base}; absolute paths are workspace-relative. Put scratch worktrees under ${base}/.worktrees/.`;\n return error;\n }\n\n resolveAbsolutePath(inputPath: string): string | undefined {\n // Sync interface: a lazy workdir that has not resolved yet has no\n // absolute form to offer.\n if (!this.resolvedBase) return undefined;\n return this.resolveAgainst(this.resolvedBase, inputPath);\n }\n\n // ── Command helper ─────────────────────────────────────────────────────\n\n private async exec(script: string): Promise<SandboxCommandResult> {\n // File reads come back as base64 on stdout and listings/grep are parsed\n // line by line, so dropping the oldest output would corrupt results.\n return this.sandbox.executeCommand('sh', ['-c', script], {\n timeout: COMMAND_TIMEOUT_MS,\n maxRetainedBytes: Infinity,\n });\n }\n\n /**\n * Lexical guard catches `..` traversal, but a symlink inside the workdir can\n * still point outside it. After resolving a path that refers to an existing\n * entry, verify its realpath is still contained in the workdir.\n *\n * Canonicalization tries `realpath`, then `readlink -f` (GNU/busybox), then\n * `cd && pwd -P` for directories — covering GNU hosts, macOS/BSD, and\n * busybox. If the path exists but cannot be canonicalized we fail CLOSED:\n * returning without a check would let a symlink bypass containment.\n */\n private async assertContainedRealpath(abs: string, inputPath: string): Promise<boolean> {\n const result = await this.exec(\n [\n `p=${shellQuote(abs)}`,\n `if [ ! -e \"$p\" ] && [ ! -L \"$p\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n // The workdir itself may contain symlinked components (/tmp on macOS),\n // so canonicalize it as the comparison root.\n `root=$(cd ${shellQuote(this.basePath)} 2>/dev/null && pwd -P)`,\n `[ -n \"$root\" ] || exit 1`,\n `rp=$(realpath \"$p\" 2>/dev/null) || rp=$(readlink -f \"$p\" 2>/dev/null) || { [ -d \"$p\" ] && rp=$(cd \"$p\" 2>/dev/null && pwd -P); }`,\n `[ -n \"$rp\" ] || exit 1`,\n `printf '%s\\\\n%s' \"$root\" \"$rp\"`,\n ].join('\\n'),\n );\n // Path doesn't exist yet: nothing to canonicalize (writes to a fresh leaf\n // are covered by assertContainedDest checking the parent directory).\n if (result.exitCode === EXIT_NOT_FOUND) return false;\n const [root, real] = result.stdout.split('\\n').map(s => s.trim());\n if (result.exitCode !== 0 || !root || !real) {\n throw new Error(`Unable to verify path stays within workspace root: ${inputPath}`);\n }\n if (real !== root && !real.startsWith(`${root}/`)) {\n throw new Error(`Path escapes workspace root (symlink): ${inputPath}`);\n }\n return true;\n }\n\n /**\n * Guard for write destinations. The lexical guard catches `..`, but a symlink\n * inside the workdir can redirect a write outside it. For an existing target\n * we check its realpath; for a not-yet-existing target we check the realpath\n * of its nearest existing ancestor directory, since a symlinked parent is the\n * escape vector (e.g. `link -> /etc` then writing `link/passwd`).\n */\n private async assertContainedDest(abs: string, inputPath: string): Promise<boolean> {\n // First check the target itself (covers overwriting an existing symlink).\n const exists = await this.assertContainedRealpath(abs, inputPath);\n // Then check the parent directory's realpath; readlink -f resolves the\n // nearest existing ancestor when the leaf doesn't exist yet.\n const parent = posixPath.dirname(abs);\n if (parent && parent !== abs) {\n await this.assertContainedRealpath(parent, inputPath);\n }\n return exists;\n }\n\n /**\n * Before a native filesystem call, run the containment check the shell path\n * runs for that operation, when `verifySymlinks` is on. A pass is remembered\n * only for an entry that exists: a missing path may later appear as a\n * symlink that leads outside the workdir.\n */\n private async verifyNative(check: ContainmentCheck, abs: string, inputPath: string): Promise<void> {\n if (!this.verifySymlinks) return;\n const key = `${check}:${abs}`;\n if (this.verified.has(key)) return;\n const existed =\n check === 'dest'\n ? await this.assertContainedDest(abs, inputPath)\n : await this.assertContainedRealpath(check === 'parent' ? posixPath.dirname(abs) : abs, inputPath);\n if (existed) this.verified.add(key);\n }\n\n private async execOk(script: string, context: string): Promise<SandboxCommandResult> {\n const result = await this.exec(script);\n if (result.exitCode !== 0) {\n throw new Error(`${context} failed (exit ${result.exitCode}): ${result.stderr.trim() || result.stdout.trim()}`);\n }\n return result;\n }\n\n // ── File operations ────────────────────────────────────────────────────\n\n async readFile(path: string, options?: ReadOptions): Promise<string | Buffer> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', abs, path);\n try {\n return await native.readFile(abs, options);\n } catch (error) {\n const isNotFound = error instanceof FileNotFoundError || (error as { code?: unknown })?.code === 'ENOENT';\n throw (isNotFound && (await this.outsideWorkdirNotFound(path, abs))) || error;\n }\n }\n await this.assertContainedRealpath(abs, path);\n // Guard clauses first: redirecting from a directory \"succeeds\" with empty\n // output on some shells, so classify before reading.\n const result = await this.exec(\n `if [ -d ${shellQuote(abs)} ]; then exit ${EXIT_IS_DIRECTORY}; elif [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; base64 < ${shellQuote(abs)}`,\n );\n if (result.exitCode === EXIT_IS_DIRECTORY) throw new IsDirectoryError(path);\n if (result.exitCode === EXIT_NOT_FOUND) {\n throw (await this.outsideWorkdirNotFound(path, abs)) ?? new FileNotFoundError(path);\n }\n if (result.exitCode !== 0) {\n throw new Error(`readFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n const buffer = Buffer.from(result.stdout.replace(/\\s/g, ''), 'base64');\n if (options?.encoding) {\n return buffer.toString(options.encoding);\n }\n return buffer;\n }\n\n async writeFile(path: string, content: FileContent, options?: WriteOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('dest', abs, path);\n return native.writeFile(abs, content, options);\n }\n await this.assertContainedDest(abs, path);\n const b64 = toBuffer(content).toString('base64');\n const dir = posixPath.dirname(abs);\n const mkdir = options?.recursive === false ? '' : `mkdir -p ${shellQuote(dir)} && `;\n if (options?.overwrite === false) {\n // `set -C` (noclobber) makes the redirect itself the exclusivity check —\n // no exists() pre-check that could race with a concurrent writer.\n const result = await this.exec(\n `${mkdir}{ (set -C; printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}) 2>/dev/null || { [ -e ${shellQuote(abs)} ] && exit ${EXIT_EXISTS} || exit 1; }; }`,\n );\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(path);\n if (result.exitCode !== 0) {\n throw new Error(`writeFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n await this.execOk(`${mkdir}printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}`, `writeFile ${path}`);\n }\n\n async appendFile(path: string, content: FileContent): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('dest', abs, path);\n return native.appendFile(abs, content);\n }\n await this.assertContainedDest(abs, path);\n const b64 = toBuffer(content).toString('base64');\n await this.execOk(\n `mkdir -p ${shellQuote(posixPath.dirname(abs))} && printf %s ${shellQuote(b64)} | base64 -d >> ${shellQuote(abs)}`,\n `appendFile ${path}`,\n );\n }\n\n async deleteFile(path: string, options?: RemoveOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('parent', abs, path);\n return native.deleteFile(abs, options);\n }\n // Contain the parent's realpath: deleting `link/file` where `link` points\n // outside the workdir must fail, while deleting a symlink entry itself\n // (which lives inside the workdir) stays allowed.\n await this.assertContainedRealpath(posixPath.dirname(abs), path);\n if (options?.force) {\n // `rm -f` already succeeds for a missing file, but still fails for\n // directories and permission errors — surface those.\n await this.execOk(`rm -f ${shellQuote(abs)}`, `deleteFile ${path}`);\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; rm ${shellQuote(abs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(path);\n if (result.exitCode !== 0) {\n throw new Error(`deleteFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n async copyFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n const srcAbs = await this.resolveAsync(src);\n const destAbs = await this.resolveAsync(dest);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', srcAbs, src);\n await this.verifyNative('dest', destAbs, dest);\n return native.copyFile(srcAbs, destAbs, options);\n }\n await this.assertContainedRealpath(srcAbs, src);\n await this.assertContainedDest(destAbs, dest);\n const recursive = options?.recursive ? '-r ' : '';\n if (options?.overwrite === false) {\n // Atomic no-clobber: directories claim the destination with an exclusive\n // mkdir; files copy to a temp name then hardlink into place (link(2)\n // fails if the destination exists). No racy exists() pre-check.\n const result = await this.exec(\n [\n `src=${shellQuote(srcAbs)}`,\n `dest=${shellQuote(destAbs)}`,\n `if [ ! -e \"$src\" ] && [ ! -L \"$src\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n `mkdir -p ${shellQuote(posixPath.dirname(destAbs))} || exit 1`,\n `if [ -d \"$src\" ]; then`,\n ` mkdir \"$dest\" 2>/dev/null || exit ${EXIT_EXISTS}`,\n ` cp -R \"$src\"/. \"$dest\"/`,\n `else`,\n ` tmp=\"$dest.__cptmp$$\"`,\n ` cp \"$src\" \"$tmp\" || exit 1`,\n ` ln \"$tmp\" \"$dest\" 2>/dev/null || { rm -f \"$tmp\"; [ -e \"$dest\" ] && exit ${EXIT_EXISTS} || exit 1; }`,\n ` rm -f \"$tmp\"`,\n `fi`,\n ].join('\\n'),\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(dest);\n if (result.exitCode !== 0) {\n throw new Error(`copyFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(srcAbs)} ]; then exit ${EXIT_NOT_FOUND}; fi; mkdir -p ${shellQuote(posixPath.dirname(destAbs))} && cp ${recursive}${shellQuote(srcAbs)} ${shellQuote(destAbs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode !== 0) {\n throw new Error(`copyFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n async moveFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n const srcAbs = await this.resolveAsync(src);\n const destAbs = await this.resolveAsync(dest);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', srcAbs, src);\n await this.verifyNative('dest', destAbs, dest);\n return native.moveFile(srcAbs, destAbs, options);\n }\n await this.assertContainedRealpath(srcAbs, src);\n await this.assertContainedDest(destAbs, dest);\n if (options?.overwrite === false) {\n // `mv -n` exits 0 even when it skips, so detect a skipped move by the\n // source surviving. The no-clobber rename itself is atomic; no racy\n // exists() pre-check.\n const result = await this.exec(\n [\n `src=${shellQuote(srcAbs)}`,\n `dest=${shellQuote(destAbs)}`,\n `if [ ! -e \"$src\" ] && [ ! -L \"$src\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n `mkdir -p ${shellQuote(posixPath.dirname(destAbs))} || exit 1`,\n `mv -n \"$src\" \"$dest\" 2>/dev/null || exit 1`,\n `if [ -e \"$src\" ] || [ -L \"$src\" ]; then exit ${EXIT_EXISTS}; fi`,\n ].join('\\n'),\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(dest);\n if (result.exitCode !== 0) {\n throw new Error(`moveFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(srcAbs)} ]; then exit ${EXIT_NOT_FOUND}; fi; mkdir -p ${shellQuote(posixPath.dirname(destAbs))} && mv ${shellQuote(srcAbs)} ${shellQuote(destAbs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode !== 0) {\n throw new Error(`moveFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n // ── Directory operations ───────────────────────────────────────────────\n\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('dest', abs, path);\n return native.mkdir(abs, options);\n }\n await this.assertContainedDest(abs, path);\n const flag = options?.recursive === false ? '' : '-p ';\n await this.execOk(`mkdir ${flag}${shellQuote(abs)}`, `mkdir ${path}`);\n }\n\n async rmdir(path: string, options?: RemoveOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('parent', abs, path);\n return native.rmdir(abs, options);\n }\n // Same parent containment as deleteFile — `rm -r` through a symlinked\n // parent would otherwise delete outside the workspace.\n await this.assertContainedRealpath(posixPath.dirname(abs), path);\n if (options?.recursive) {\n const force = options?.force ? '-f ' : '';\n await this.execOk(`rm -r ${force}${shellQuote(abs)}`, `rmdir ${path}`);\n return;\n }\n const result = await this.exec(`rmdir ${shellQuote(abs)}`);\n if (result.exitCode !== 0 && !options?.force) {\n throw new Error(`Directory not empty or not found: ${path}`);\n }\n }\n\n async readdir(path: string, options?: ListOptions): Promise<FileEntry[]> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', abs, path);\n return native.readdir(abs, options);\n }\n await this.assertContainedRealpath(abs, path);\n if (options?.recursive) {\n // Recursive listing emitting \"type\\tpath\". `find -printf` is GNU-only\n // (fails on macOS/BSD hosts backing a local sandbox), so classify each\n // entry with a portable shell loop instead.\n const result = await this.exec(\n `test -d ${shellQuote(abs)} && find ${shellQuote(abs)} -mindepth 1 ${options.maxDepth ? `-maxdepth ${Number(options.maxDepth)} ` : ''}2>/dev/null | while IFS= read -r f; do if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`,\n );\n if (result.exitCode !== 0) throw new Error(`Directory not found: ${path}`);\n return this.parseFindOutput(result.stdout, abs, options);\n }\n // Non-recursive: list with name + type via a portable loop. Use printf,\n // not echo — bash-as-/bin/sh (macOS local sandboxes) does not expand \\t\n // in echo arguments.\n const result = await this.exec(\n `cd ${shellQuote(abs)} 2>/dev/null && for f in * .[!.]*; do [ -e \"$f\" ] || continue; if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`,\n );\n if (result.exitCode !== 0) throw new Error(`Directory not found: ${path}`);\n return this.parseListOutput(result.stdout, options);\n }\n\n private parseListOutput(stdout: string, options?: ListOptions): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const type = line.slice(0, tab) === 'd' ? 'directory' : 'file';\n const name = line.slice(tab + 1);\n if (!name || name === '.' || name === '..') continue;\n if (type === 'file' && !this.matchesExtension(name, options?.extension)) continue;\n entries.push({ name, type });\n }\n return entries;\n }\n\n private parseFindOutput(stdout: string, base: string, options?: ListOptions): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const type = line.slice(0, tab) === 'd' ? 'directory' : 'file';\n const fullPath = line.slice(tab + 1);\n const name = posixPath.relative(base, fullPath);\n if (!name) continue;\n if (type === 'file' && !this.matchesExtension(name, options?.extension)) continue;\n entries.push({ name, type });\n }\n return entries;\n }\n\n private matchesExtension(name: string, extension?: string | string[]): boolean {\n if (!extension) return true;\n const exts = Array.isArray(extension) ? extension : [extension];\n return exts.some(ext => name.endsWith(ext));\n }\n\n // ── Native walk / grep capabilities ────────────────────────────────────\n\n /**\n * Walk the tree in a single sandbox command instead of one readdir round\n * trip per directory. Uses `find` with a portable classification loop\n * (`find -printf` is GNU-only and fails on macOS/BSD hosts). `find` does\n * not follow symlinked directories by default, matching the host-side\n * walker's no-recursion-into-symlinks behavior.\n */\n async walk(path: string, options?: WalkOptions): Promise<WalkEntry[]> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedRealpath(abs, path);\n const maxDepth =\n options?.maxDepth !== undefined && Number.isFinite(options.maxDepth)\n ? `-maxdepth ${Math.max(0, Math.floor(options.maxDepth))} `\n : '';\n // Prune hidden entries in-sandbox when not requested, so a huge hidden\n // tree (e.g. `.git`) doesn't inflate the response. `.gitignore` files\n // still come back when the caller applies them.\n const keepGitignore = options?.includeGitignoreFiles ? `! \\\\( -type f -name .gitignore \\\\) ` : '';\n const hiddenPrune = options?.includeHidden ? '' : `\\\\( -name '.*' ${keepGitignore}\\\\) -prune -o `;\n // Skip directories like node_modules entirely instead of listing them\n // only for the caller to filter them out.\n const skipNames = options?.skipDirectoryNames?.filter(Boolean) ?? [];\n const skipPrune = skipNames.length\n ? `\\\\( -type d \\\\( ${skipNames.map(name => `-name ${shellQuote(name)}`).join(' -o ')} \\\\) \\\\) -prune -o `\n : '';\n // Emit \"flag\\tpath[\\ttarget]\" — flag is d/f for regular entries, D/F for\n // symlinks (with the link target as a third field).\n const script =\n `root=${shellQuote(abs)}\\n` +\n `[ -e \"$root\" ] || [ -L \"$root\" ] || exit ${EXIT_NOT_FOUND}\\n` +\n `[ -d \"$root\" ] || exit ${EXIT_NOT_DIRECTORY}\\n` +\n `find \"$root\" -mindepth 1 ${maxDepth}${hiddenPrune}${skipPrune}-print 2>/dev/null | while IFS= read -r f; do ` +\n `if [ -L \"$f\" ]; then if [ -d \"$f\" ]; then t=D; else t=F; fi; printf '%s\\\\t%s\\\\t%s\\\\n' \"$t\" \"$f\" \"$(readlink \"$f\")\"; ` +\n `elif [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`;\n const result = await this.exec(script);\n if (result.exitCode === EXIT_NOT_FOUND) throw new DirectoryNotFoundError(path);\n if (result.exitCode === EXIT_NOT_DIRECTORY) throw new NotDirectoryError(path);\n if (result.exitCode !== 0) {\n throw new Error(`walk ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n const entries: WalkEntry[] = [];\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const flag = line.slice(0, tab);\n const isSymlink = flag === 'D' || flag === 'F';\n let fullPath = line.slice(tab + 1);\n let symlinkTarget: string | undefined;\n if (isSymlink) {\n const tab2 = fullPath.lastIndexOf('\\t');\n if (tab2 >= 0) {\n symlinkTarget = fullPath.slice(tab2 + 1) || undefined;\n fullPath = fullPath.slice(0, tab2);\n }\n }\n const rel = posixPath.relative(abs, fullPath);\n if (!rel || rel.startsWith('..')) continue;\n entries.push({\n name: posixPath.basename(rel),\n type: flag === 'd' || flag === 'D' ? 'directory' : 'file',\n ...(isSymlink ? { isSymlink: true, ...(symlinkTarget ? { symlinkTarget } : {}) } : {}),\n path: rel,\n });\n }\n return entries;\n }\n\n /**\n * Content search executed inside the sandbox in one command, using the best\n * engine the sandbox has: ripgrep, then GNU grep (with git choosing files\n * inside repositories), then POSIX `grep -rnE`. Patterns the grep engines\n * can't express (PCRE-style classes, word boundaries, lookarounds,\n * non-greedy quantifiers) throw {@link UnsupportedGrepPatternError} so\n * callers use their host-side walk.\n *\n * ripgrep and GNU grep apply every `.gitignore` in the tree, relative to the\n * directory that holds it, and skip `node_modules` unless the search path\n * is inside one. Callers still apply their own hidden/glob filtering.\n */\n async grep(options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const abs = await this.resolveAsync(options.path);\n await this.assertContainedRealpath(abs, options.path);\n const tools = await this.searchTools();\n if (tools.rg) return this.grepWithRipgrep(abs, options);\n if (tools.gnuGrep) return this.grepWithGnuGrep(abs, options, tools);\n return this.grepWithPosixGrep(abs, options);\n }\n\n private toolsCheck: Promise<SearchTools> | undefined;\n\n private searchTools(): Promise<SearchTools> {\n const check = (this.toolsCheck ??= this.exec(SEARCH_TOOLS_PROBE).then(result => {\n if (result.exitCode !== 0) throw new Error(`search tool probe exited with ${result.exitCode}`);\n const found = new Set(result.stdout.split('\\n').map(line => line.trim()));\n const git = found.has('git');\n return {\n rg: found.has('rg'),\n gnuGrep: found.has('gnu-grep'),\n git,\n pcre: found.has('grep-pcre') && (!git || found.has('git-pcre')),\n };\n }));\n // Only a successful probe is cached; a failed one (e.g. the sandbox wasn't\n // ready) is retried on the next search instead of pinning the slow path.\n return check.catch(() => {\n if (this.toolsCheck === check) this.toolsCheck = undefined;\n return { rg: false, gnuGrep: false, git: false, pcre: false };\n });\n }\n\n private async grepWithRipgrep(abs: string, options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const args = [\n // --no-require-git applies .gitignore files outside a git checkout too\n // (e.g. a multi-repo root). A path passed explicitly is searched even\n // when ignored, so targeting `dist/` or `node_modules/x` still works.\n 'rg --json --hidden --no-require-git',\n // .git is filtered host-side too; exclude it here so its object files\n // don't inflate the response.\n `-g ${shellQuote('!.git/**')}`,\n isInsideNodeModules(abs) ? '' : `-g ${shellQuote('!**/node_modules/**')}`,\n options.caseSensitive ? '' : '-i',\n options.maxCountPerFile !== undefined ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : '',\n options.contextLines ? `-C ${Math.max(0, Math.floor(options.contextLines))}` : '',\n `-e ${shellQuote(options.pattern)}`,\n shellQuote(abs),\n ]\n .filter(Boolean)\n .join(' ');\n const result = await this.exec(args);\n // rg exits 1 when there are no matches, 2 on any error. A bad pattern\n // produces no output at all, but a per-file error (e.g. an unreadable\n // file) also yields exit 2 while still emitting matches for every other\n // file. Keep those partial results; only treat \"error with no matches\"\n // as an unsupported pattern so the caller falls back to the host walk.\n if (result.exitCode === 1) return [];\n const results = this.parseRipgrepJson(result.stdout, abs, options);\n if (result.exitCode !== 0 && results.length === 0) {\n throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));\n }\n return results;\n }\n\n private parseRipgrepJson(stdout: string, abs: string, options: FilesystemGrepOptions): FilesystemGrepResult[] {\n const files = new Map<string, GrepFileLines>();\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n let event: any;\n try {\n event = JSON.parse(line);\n } catch {\n continue;\n }\n if (event.type !== 'match' && event.type !== 'context') continue;\n const filePath: string | undefined = event.data?.path?.text;\n const lineNumber: number | undefined = event.data?.line_number;\n if (!filePath || !lineNumber) continue;\n const state = fileLines(files, filePath);\n const text: string = (event.data?.lines?.text ?? '').replace(/\\r?\\n$/, '');\n state.linesByNumber.set(lineNumber, text);\n if (event.type === 'match') {\n // rg submatch offsets are byte offsets into the line; convert to a\n // UTF-16 (JS string) index for the capability contract.\n const byteStart: number = event.data?.submatches?.[0]?.start ?? 0;\n const column = Buffer.from(text, 'utf8').subarray(0, byteStart).toString('utf8').length;\n state.matches.push({ line: lineNumber, column, text });\n }\n }\n return this.applyTotalCap(toGrepResults(files, abs, options.contextLines ?? 0), options.maxTotalMatches);\n }\n\n /**\n * Patterns whose meaning differs between POSIX ERE and JS RegExp. The grep\n * runs with ERE but match columns are recomputed with JS, so anything that\n * only one side understands (PCRE classes, lookarounds, lazy quantifiers,\n * POSIX bracket classes, GNU word anchors) must fall back to the host walk.\n */\n private static readonly ERE_UNSUPPORTED = /\\\\[dDwWsSbB<>]|\\(\\?|[*+?}]\\?|\\[:[a-z]+:\\]/;\n\n /**\n * Escapes that `grep -P` (PCRE) and JS RegExp (without the `u` flag) both\n * accept but read differently, e.g. `\\A` is \"start of subject\" in PCRE and\n * a literal `A` in JS, plus POSIX bracket classes. PCRE-only syntax that JS\n * rejects (inline flags, possessive quantifiers, atomic groups) already\n * fails the JS compile below.\n */\n private static readonly PCRE_UNSUPPORTED = /\\\\[AzZGKQEhHvVRXNCpPe]|\\[:[a-z]+:\\]/;\n\n /** Reject patterns grep can't run with the same meaning as JS; return the JS regex used for columns. */\n private static grepRegex(options: FilesystemGrepOptions, pcre = false): RegExp {\n if (\n pcre\n ? SandboxFilesystem.PCRE_UNSUPPORTED.test(options.pattern)\n : SandboxFilesystem.ERE_UNSUPPORTED.test(options.pattern)\n ) {\n throw new UnsupportedGrepPatternError(\n options.pattern,\n pcre ? 'grep -P reads this syntax differently from JavaScript' : 'POSIX ERE cannot express this syntax',\n );\n }\n try {\n return new RegExp(options.pattern, options.caseSensitive ? '' : 'i');\n } catch {\n throw new UnsupportedGrepPatternError(options.pattern, 'invalid regular expression');\n }\n }\n\n /**\n * GNU grep without ripgrep. Inside a git checkout, `git grep` picks the\n * files (tracked plus untracked, every `.gitignore` applied) and GNU grep\n * prints them with context. Outside a checkout (e.g. a multi-repo root),\n * each child repository is searched the same way and plain grep covers the\n * remaining files, skipping `node_modules`. `--null` ends each file name\n * with NUL, so match (`N:`) and context (`N-`) lines parse unambiguously.\n * When grep and git support it, patterns run as PCRE (`-P`), so `\\d`,\n * `\\w`, `\\s`, `\\b`, and lookarounds don't need the host walk.\n */\n private async grepWithGnuGrep(\n abs: string,\n options: FilesystemGrepOptions,\n tools: SearchTools,\n ): Promise<FilesystemGrepResult[]> {\n const hasGit = tools.git;\n const mode = tools.pcre ? '-P' : '-E';\n const jsRegex = SandboxFilesystem.grepRegex(options, tools.pcre);\n const contextLines = Math.max(0, Math.floor(options.contextLines ?? 0));\n const grepFlags = [\n `-HnI${mode.slice(1)} --null`,\n options.caseSensitive ? '' : '-i',\n options.maxCountPerFile !== undefined ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : '',\n contextLines > 0 ? `-C ${contextLines}` : '',\n ]\n .filter(Boolean)\n .join(' ');\n const skipNodeModules = !isInsideNodeModules(abs);\n const nodeModulesPathspec = skipNodeModules ? ` ${shellQuote(':(exclude,glob)**/node_modules/**')}` : '';\n const pruneNames = skipNodeModules ? '-name .git -o -name node_modules' : '-name .git';\n const script = [\n `pat=${shellQuote(options.pattern)}`,\n `root=${shellQuote(abs)}`,\n // xargs exit codes can't tell \"no match\" from \"bad pattern\"; check first.\n `grep ${mode} -e \"$pat\" </dev/null >/dev/null 2>&1`,\n 'if [ $? -eq 2 ]; then echo \"grep: invalid regular expression\" >&2; exit 2; fi',\n 'tmp=$(mktemp -d) || exit 1',\n `trap 'rm -rf \"$tmp\"' EXIT`,\n `search_files() { xargs -0 -r grep ${grepFlags} -e \"$pat\" -- 2>/dev/null; }`,\n // A line starting with NUL names the directory later paths are relative to.\n 'search_repo() {',\n ` git -C \"$1\" grep -l -z -I --untracked ${options.caseSensitive ? '' : '-i '}${mode} -e \"$pat\" -- .${nodeModulesPathspec} >\"$tmp/files\" 2>/dev/null`,\n ' [ $? -gt 1 ] && return 1',\n ` printf '\\\\0%s\\\\n' \"$1\"`,\n ' (cd \"$1\" && search_files) <\"$tmp/files\"',\n '}',\n ...(hasGit\n ? [\n 'if git -C \"$root\" rev-parse --is-inside-work-tree >/dev/null 2>&1 && ! git -C \"$root\" check-ignore -q . 2>/dev/null; then',\n ' search_repo \"$root\" && exit 0',\n 'fi',\n `find \"$root\" -mindepth 1 -maxdepth 3 \\\\( ${skipNodeModules ? '-name node_modules -prune' : '-false'} \\\\) -o \\\\( -name .git -prune -print \\\\) >\"$tmp/repos\" 2>/dev/null`,\n ': >\"$tmp/done\"',\n 'while IFS= read -r g; do',\n ' d=${g%/.git}',\n ' search_repo \"$d\" && printf \\'%s\\\\n\\' \"$d\" >>\"$tmp/done\"',\n 'done <\"$tmp/repos\"',\n 'set --',\n 'while IFS= read -r d; do set -- \"$@\" -o -path \"$d\"; done <\"$tmp/done\"',\n ]\n : ['set --']),\n `printf '\\\\0%s\\\\n' \"$root\"`,\n `find \"$root\" -mindepth 1 \\\\( ${pruneNames} \"$@\" \\\\) -prune -o -type f -print0 2>/dev/null | search_files`,\n 'exit 0',\n ].join('\\n');\n const result = await this.exec(script);\n if (result.exitCode !== 0) {\n throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));\n }\n const files = new Map<string, GrepFileLines>();\n let base = abs;\n for (const line of result.stdout.split('\\n')) {\n if (!line || line === '--') continue;\n if (line.startsWith('\\0')) {\n base = line.slice(1);\n continue;\n }\n const nul = line.indexOf('\\0');\n if (nul <= 0) continue;\n const parsed = /^(\\d+)([:-])(.*)$/s.exec(line.slice(nul + 1));\n if (!parsed) continue;\n const lineNumber = Number(parsed[1]);\n const text = parsed[3]!;\n const state = fileLines(files, posixPath.resolve(base, line.slice(0, nul)));\n state.linesByNumber.set(lineNumber, text);\n if (parsed[2] !== ':') continue;\n const column = jsRegex.exec(text)?.index;\n if (column === undefined) {\n throw new UnsupportedGrepPatternError(options.pattern, 'POSIX ERE and JS RegExp disagree on this pattern');\n }\n state.matches.push({ line: lineNumber, column, text });\n }\n return this.applyTotalCap(toGrepResults(files, abs, contextLines), options.maxTotalMatches);\n }\n\n private async grepWithPosixGrep(abs: string, options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const jsRegex = SandboxFilesystem.grepRegex(options);\n // Reconstructing per-match context from `grep -C` text output is not\n // reliable (separator lines are ambiguous); let the host walk handle it.\n if (options.contextLines) {\n throw new UnsupportedGrepPatternError(options.pattern, 'context lines are not supported by POSIX grep');\n }\n const args = [\n 'grep -rnIE',\n // .git is filtered host-side too; skip it so object files are not scanned.\n '--exclude-dir=.git',\n options.caseSensitive ? '' : '-i',\n options.maxCountPerFile !== undefined ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : '',\n '--',\n shellQuote(options.pattern),\n shellQuote(abs),\n ]\n .filter(Boolean)\n .join(' ');\n const result = await this.exec(args);\n if (result.exitCode === 1) return [];\n // Like rg, grep exits 2 on per-file errors (e.g. an unreadable file) while\n // still printing matches for the rest; keep those partial results.\n if (result.exitCode !== 0 && !(result.exitCode === 2 && result.stdout.trim())) {\n throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));\n }\n // grep -n has no column output; recompute with the JS regex host-side so\n // columns are UTF-16 indices, consistent with the fallback implementation.\n const byFile = new Map<string, FilesystemGrepMatch[]>();\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const parsed = /^(.*?):(\\d+):(.*)$/.exec(line);\n if (!parsed) continue;\n const rel = posixPath.relative(abs, parsed[1]!) || posixPath.basename(parsed[1]!);\n const text = parsed[3]!;\n const column = jsRegex.exec(text)?.index;\n // grep matched this line but the JS regex did not: the two dialects\n // disagree on this pattern, so the columns would be wrong. Fall back.\n if (column === undefined) {\n throw new UnsupportedGrepPatternError(options.pattern, 'POSIX ERE and JS RegExp disagree on this pattern');\n }\n let matches = byFile.get(rel);\n if (!matches) {\n matches = [];\n byFile.set(rel, matches);\n }\n matches.push({ line: Number(parsed[2]), column, text });\n }\n const results = [...byFile.entries()].map(([path, matches]) => ({ path, matches }));\n return this.applyTotalCap(results, options.maxTotalMatches);\n }\n\n private applyTotalCap(results: FilesystemGrepResult[], maxTotal?: number): FilesystemGrepResult[] {\n if (maxTotal === undefined) return results;\n const capped: FilesystemGrepResult[] = [];\n let total = 0;\n for (const file of results) {\n if (total >= maxTotal) break;\n const remaining = maxTotal - total;\n const matches = file.matches.slice(0, remaining);\n total += matches.length;\n capped.push({ path: file.path, matches });\n }\n return capped;\n }\n\n // ── Path / metadata ────────────────────────────────────────────────────\n\n async exists(path: string): Promise<boolean> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) return native.exists(abs);\n const result = await this.exec(`test -e ${shellQuote(abs)}`);\n return result.exitCode === 0;\n }\n\n async stat(path: string): Promise<FileStat> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', abs, path);\n let info: Awaited<ReturnType<typeof native.stat>>;\n try {\n info = await native.stat(abs);\n } catch (error) {\n const isNotFound = error instanceof FileNotFoundError || (error as { code?: unknown })?.code === 'ENOENT';\n throw (isNotFound && (await this.outsideWorkdirNotFound(path, abs))) || error;\n }\n return {\n ...info,\n name: posixPath.basename(abs),\n path: `/${posixPath.relative(this.basePath, abs)}`,\n mimeType: info.type === 'file' ? (info.mimeType ?? getMimeType(abs)) : info.mimeType,\n };\n }\n await this.assertContainedRealpath(abs, path);\n // GNU stat: %F=type, %s=size, %Y=mtime (epoch seconds), %W=birth (or -1).\n // BSD/macOS stat (local sandbox hosts) rejects `-c`; fall back to its\n // `-f` format with the same field order (%HT=type, %z=size, %m=mtime,\n // %B=birth). Delimit with `|` — neither stat interprets `\\t` escapes in\n // its format string. `-L` reports the symlink target, like LocalFilesystem.\n const result = await this.exec(\n `stat -L -c '%F|%s|%Y|%W' ${shellQuote(abs)} 2>/dev/null || stat -L -f '%HT|%z|%m|%B' ${shellQuote(abs)}`,\n );\n if (result.exitCode !== 0) {\n throw (await this.outsideWorkdirNotFound(path, abs)) ?? new FileNotFoundError(path);\n }\n const [kind, sizeStr, mtimeStr, ctimeStr] = result.stdout.trim().split('|');\n const type = kind && kind.toLowerCase().includes('directory') ? 'directory' : 'file';\n const size = Number(sizeStr) || 0;\n const mtime = Number(mtimeStr) || 0;\n const ctime = Number(ctimeStr);\n return {\n name: posixPath.basename(abs),\n path: `/${posixPath.relative(this.basePath, abs)}`,\n type,\n size: type === 'directory' ? 0 : size,\n modifiedAt: new Date(mtime * 1000),\n createdAt: new Date((ctime > 0 ? ctime : mtime) * 1000),\n mimeType: type === 'file' ? getMimeType(abs) : undefined,\n };\n }\n\n // ── Lifecycle ──────────────────────────────────────────────────────────\n\n async init(): Promise<void> {\n await this.execOk(`mkdir -p ${shellQuote(await this.base())}`, 'init workdir');\n }\n\n async destroy(): Promise<void> {\n // The sandbox lifecycle is owned by the caller; nothing to tear down here.\n }\n\n async isReady(): Promise<boolean> {\n const result = await this.exec(`test -d ${shellQuote(await this.base())}`);\n return result.exitCode === 0;\n }\n\n getInfo(): FilesystemInfo {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n metadata: { basePath: this.basePath, sandboxId: this.sandbox.id },\n };\n }\n\n getInstructions(): string {\n return `Files are stored in a remote sandbox at ${this.basePath}. Use absolute workspace paths like /src/index.ts. All reads, writes and commands run inside the same sandbox. Absolute paths are workspace-relative (/tmp/x resolves to ${this.basePath}/tmp/x), so file tools cannot reach files outside ${this.basePath}. Create scratch git worktrees under ${this.basePath}/.worktrees/, then, in a pnpm monorepo, run \\`pnpm install --prefer-offline --frozen-lockfile\\` in the worktree and build the workspace packages you test against (with Turborepo: \\`pnpm turbo build --filter=\"<package>^...\"\\`, which reuses the build cache).`;\n }\n}\n"],"mappings":";;;;;;;;;;;;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QAAQ;EAC7B,OAAO;GACL,MAAMA,MAAU,SAAS,GAAG;GAC5B,MAAM,IAAIA,MAAU,SAAS,KAAK,UAAU,GAAG;GAC/C;GACA,MAAM,SAAS,cAAc,IAAI;GACjC,4BAAY,IAAI,KAAK,QAAQ,GAAI;GACjC,2BAAW,IAAI,MAAM,QAAQ,IAAI,QAAQ,SAAS,GAAI;GACtD,UAAU,SAAS,SAAS,YAAY,GAAG,IAAI,KAAA;EACjD;CACF;CAIA,MAAM,OAAsB;EAC1B,MAAM,KAAK,OAAO,YAAY,WAAW,MAAM,KAAK,KAAK,CAAC,KAAK,cAAc;CAC/E;CAEA,MAAM,UAAyB,CAE/B;CAEA,MAAM,UAA4B;EAEhC,QAAO,MADc,KAAK,KAAK,WAAW,WAAW,MAAM,KAAK,KAAK,CAAC,GAAG,EAAA,CAC3D,aAAa;CAC7B;CAEA,UAA0B;EACxB,OAAO;GACL,IAAI,KAAK;GACT,MAAM,KAAK;GACX,UAAU,KAAK;GACf,QAAQ,KAAK;GACb,UAAU;IAAE,UAAU,KAAK;IAAU,WAAW,KAAK,QAAQ;GAAG;EAClE;CACF;CAEA,kBAA0B;EACxB,OAAO,2CAA2C,KAAK,SAAS,2KAA2K,KAAK,SAAS,oDAAoD,KAAK,SAAS,uCAAuC,KAAK,SAAS;CAClX;AACF"}
|
|
@@ -65,9 +65,32 @@ export type RotationClassification = {
|
|
|
65
65
|
reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed';
|
|
66
66
|
} | {
|
|
67
67
|
kind: 'hop';
|
|
68
|
+
} | {
|
|
69
|
+
kind: 'stream-cut';
|
|
68
70
|
} | {
|
|
69
71
|
kind: 'never';
|
|
70
72
|
};
|
|
73
|
+
/**
|
|
74
|
+
* Same-account retries for a stream the provider cut after accepting the
|
|
75
|
+
* request. Each one can cost a full stream (900 s on the ChatGPT Codex route),
|
|
76
|
+
* so the budget is small. This is the whole budget: Mastra Code's
|
|
77
|
+
* `StreamErrorRetryProcessor` leaves these errors to this processor.
|
|
78
|
+
*/
|
|
79
|
+
export declare const MAX_STREAM_CUT_RETRIES = 2;
|
|
80
|
+
/**
|
|
81
|
+
* Whether the provider accepted the request and then the response stream died:
|
|
82
|
+
* the AI SDK reports a body that fails after a 2xx response as
|
|
83
|
+
* "Failed to process successful response" with the 2xx status, and the ChatGPT
|
|
84
|
+
* Codex backend ends streams at 900 s, sometimes with a `request_timeout` error
|
|
85
|
+
* frame first. Either way the account and the provider answered, so this is
|
|
86
|
+
* not an outage, and another account would be cut the same way.
|
|
87
|
+
*
|
|
88
|
+
* `@ai-sdk/openai` raises that frame with `code: 'request_timeout'` and a
|
|
89
|
+
* derived `statusCode: 504`, so callers must check this before any 5xx rule.
|
|
90
|
+
* Mastra Code's transient retry matchers call it first so that account
|
|
91
|
+
* rotation is the only processor that retries these errors.
|
|
92
|
+
*/
|
|
93
|
+
export declare function isStreamCutAfterResponse(error: unknown): boolean;
|
|
71
94
|
/**
|
|
72
95
|
* The locked Q7 taxonomy. Rate limits and exhausted quotas rotate immediately
|
|
73
96
|
* (429 is not covered by any transient matcher, so it arrives here on first
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account-rotation-processor.d.ts","sourceRoot":"","sources":["../../src/auth/account-rotation-processor.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACpH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAMnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAS3D,OAAO,KAAK,EAAE,eAAe,EAAsB,MAAM,YAAY,CAAC;AAEtE,eAAO,MAAM,wBAAwB,mCAAmC,CAAC;AAEzE,yEAAyE;AACzE,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE;QAAE,EAAE,EAAE,MAAM,C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/** Session-state key set when account rotation advances the model route. */
|
|
60
60
|
const MODEL_FALLBACK_STATE_KEY = "mastracodePendingModelFallback";
|
|
61
|
+
/**
|
|
62
|
+
* Same-account retries for a stream the provider cut after accepting the
|
|
63
|
+
* request. Each one can cost a full stream (900 s on the ChatGPT Codex route),
|
|
64
|
+
* so the budget is small. This is the whole budget: Mastra Code's
|
|
65
|
+
* `StreamErrorRetryProcessor` leaves these errors to this processor.
|
|
66
|
+
*/
|
|
67
|
+
const MAX_STREAM_CUT_RETRIES = 2;
|
|
61
68
|
const ROTATION_BY_PROVIDER_KIND = {
|
|
62
69
|
auth: {
|
|
63
70
|
kind: "rotate",
|
|
@@ -122,6 +129,42 @@ function isNetworkErrorLike(error) {
|
|
|
122
129
|
}
|
|
123
130
|
return false;
|
|
124
131
|
}
|
|
132
|
+
/** The code the ChatGPT Codex backend puts on the error frame it sends when it ends a stream at 900 s. */
|
|
133
|
+
const STREAM_DURATION_LIMIT_CODE = "request_timeout";
|
|
134
|
+
function asRecord(value) {
|
|
135
|
+
return typeof value === "object" && value !== null ? value : void 0;
|
|
136
|
+
}
|
|
137
|
+
/** The `error.code` of a stream error frame: the raw frame, or the frame `@ai-sdk/openai` keeps as `data`. */
|
|
138
|
+
function streamErrorFrameCode(value) {
|
|
139
|
+
const data = asRecord(value.data);
|
|
140
|
+
return asRecord((value.type === "error" ? value : data?.type === "error" ? data : void 0)?.error)?.code;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Whether the provider accepted the request and then the response stream died:
|
|
144
|
+
* the AI SDK reports a body that fails after a 2xx response as
|
|
145
|
+
* "Failed to process successful response" with the 2xx status, and the ChatGPT
|
|
146
|
+
* Codex backend ends streams at 900 s, sometimes with a `request_timeout` error
|
|
147
|
+
* frame first. Either way the account and the provider answered, so this is
|
|
148
|
+
* not an outage, and another account would be cut the same way.
|
|
149
|
+
*
|
|
150
|
+
* `@ai-sdk/openai` raises that frame with `code: 'request_timeout'` and a
|
|
151
|
+
* derived `statusCode: 504`, so callers must check this before any 5xx rule.
|
|
152
|
+
* Mastra Code's transient retry matchers call it first so that account
|
|
153
|
+
* rotation is the only processor that retries these errors.
|
|
154
|
+
*/
|
|
155
|
+
function isStreamCutAfterResponse(error) {
|
|
156
|
+
let current = error;
|
|
157
|
+
for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {
|
|
158
|
+
const record = asRecord(current);
|
|
159
|
+
if (!record) break;
|
|
160
|
+
const { statusCode, status, code } = record;
|
|
161
|
+
const httpStatus = typeof statusCode === "number" ? statusCode : status;
|
|
162
|
+
if (typeof httpStatus === "number" && httpStatus >= 200 && httpStatus < 300) return true;
|
|
163
|
+
if (code === STREAM_DURATION_LIMIT_CODE || streamErrorFrameCode(record) === STREAM_DURATION_LIMIT_CODE) return true;
|
|
164
|
+
current = record.cause;
|
|
165
|
+
}
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
125
168
|
/**
|
|
126
169
|
* The locked Q7 taxonomy. Rate limits and exhausted quotas rotate immediately
|
|
127
170
|
* (429 is not covered by any transient matcher, so it arrives here on first
|
|
@@ -135,6 +178,7 @@ function classifyRotationError(error) {
|
|
|
135
178
|
kind: "rotate",
|
|
136
179
|
reason: "auth-failed"
|
|
137
180
|
};
|
|
181
|
+
if (isStreamCutAfterResponse(error)) return { kind: "stream-cut" };
|
|
138
182
|
const status = readErrorStatus(error);
|
|
139
183
|
const byStatus = rotationFromStatus(status);
|
|
140
184
|
if (byStatus) return byStatus;
|
|
@@ -366,6 +410,24 @@ var AccountRotationProcessor = class {
|
|
|
366
410
|
await this.gateChainHop(args, error);
|
|
367
411
|
return { retry: false };
|
|
368
412
|
}
|
|
413
|
+
if (classification.kind === "stream-cut") {
|
|
414
|
+
const budget = state.streamCutRetries;
|
|
415
|
+
const cuts = budget?.step === args.stepNumber ? budget.count : 0;
|
|
416
|
+
if (cuts >= 2) {
|
|
417
|
+
await this.gateChainHop(args, error);
|
|
418
|
+
return { retry: false };
|
|
419
|
+
}
|
|
420
|
+
state.streamCutRetries = {
|
|
421
|
+
step: args.stepNumber,
|
|
422
|
+
count: cuts + 1
|
|
423
|
+
};
|
|
424
|
+
args.rotateResponseMessageId?.();
|
|
425
|
+
(args.requestContext?.get("controller"))?.emitEvent?.({
|
|
426
|
+
type: "info",
|
|
427
|
+
message: `The provider ended the response stream early (it may have hit a stream duration limit). Retrying (${cuts + 1}/2).`
|
|
428
|
+
});
|
|
429
|
+
return { retry: true };
|
|
430
|
+
}
|
|
369
431
|
const cascade = await this.getModelRouteCascade(args);
|
|
370
432
|
const currentEntry = cascade?.entries[cascade.position];
|
|
371
433
|
const providerId = providerFromError(error) ?? (currentEntry ? providerFromModelId(currentEntry.modelId) : void 0) ?? (cascade ? void 0 : providerFromSession(args));
|
|
@@ -597,6 +659,6 @@ var AccountStartNoticeProcessor = class {
|
|
|
597
659
|
return args.messageList;
|
|
598
660
|
}
|
|
599
661
|
};
|
|
600
|
-
export { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_DISPLAY_NAMES, accountSwitchNoticeText, classifyRotationError, isAccountSwitchReason, isModelFallbackReason, modelFallbackNoticeText, providerFromError, providerFromModelId };
|
|
662
|
+
export { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, MAX_STREAM_CUT_RETRIES, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_DISPLAY_NAMES, accountSwitchNoticeText, classifyRotationError, isAccountSwitchReason, isModelFallbackReason, isStreamCutAfterResponse, modelFallbackNoticeText, providerFromError, providerFromModelId };
|
|
601
663
|
|
|
602
664
|
//# sourceMappingURL=account-rotation-processor.js.map
|