@librechat/agents 3.2.41 → 3.2.43

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.
Files changed (75) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +4 -3
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/graphs/Graph.cjs +5 -2
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +1 -1
  6. package/dist/cjs/llm/bedrock/index.cjs +9 -1
  7. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  8. package/dist/cjs/main.cjs +6 -0
  9. package/dist/cjs/messages/cache.cjs +43 -0
  10. package/dist/cjs/messages/cache.cjs.map +1 -1
  11. package/dist/cjs/session/JsonlSessionStore.cjs +1 -1
  12. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs +2 -2
  13. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs.map +1 -1
  14. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs +118 -22
  15. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs.map +1 -1
  16. package/dist/cjs/tools/local/CompileCheckTool.cjs +11 -3
  17. package/dist/cjs/tools/local/CompileCheckTool.cjs.map +1 -1
  18. package/dist/cjs/tools/local/FileCheckpointer.cjs +8 -3
  19. package/dist/cjs/tools/local/FileCheckpointer.cjs.map +1 -1
  20. package/dist/cjs/tools/local/LocalCodingTools.cjs +26 -7
  21. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  22. package/dist/cjs/tools/local/LocalExecutionEngine.cjs +2 -2
  23. package/dist/cjs/tools/local/syntaxCheck.cjs +6 -2
  24. package/dist/cjs/tools/local/syntaxCheck.cjs.map +1 -1
  25. package/dist/cjs/tools/local/workspaceFS.cjs +20 -0
  26. package/dist/cjs/tools/local/workspaceFS.cjs.map +1 -1
  27. package/dist/esm/agents/AgentContext.mjs +5 -4
  28. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  29. package/dist/esm/graphs/Graph.mjs +6 -3
  30. package/dist/esm/graphs/Graph.mjs.map +1 -1
  31. package/dist/esm/hooks/createWorkspacePolicyHook.mjs +1 -1
  32. package/dist/esm/llm/bedrock/index.mjs +10 -2
  33. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  34. package/dist/esm/main.mjs +3 -3
  35. package/dist/esm/messages/cache.mjs +42 -1
  36. package/dist/esm/messages/cache.mjs.map +1 -1
  37. package/dist/esm/session/JsonlSessionStore.mjs +1 -1
  38. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs +3 -3
  39. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs.map +1 -1
  40. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs +115 -23
  41. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs.map +1 -1
  42. package/dist/esm/tools/local/CompileCheckTool.mjs +11 -3
  43. package/dist/esm/tools/local/CompileCheckTool.mjs.map +1 -1
  44. package/dist/esm/tools/local/FileCheckpointer.mjs +9 -4
  45. package/dist/esm/tools/local/FileCheckpointer.mjs.map +1 -1
  46. package/dist/esm/tools/local/LocalCodingTools.mjs +26 -7
  47. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  48. package/dist/esm/tools/local/LocalExecutionEngine.mjs +2 -2
  49. package/dist/esm/tools/local/syntaxCheck.mjs +6 -2
  50. package/dist/esm/tools/local/syntaxCheck.mjs.map +1 -1
  51. package/dist/esm/tools/local/workspaceFS.mjs +19 -1
  52. package/dist/esm/tools/local/workspaceFS.mjs.map +1 -1
  53. package/dist/types/agents/AgentContext.d.ts +3 -2
  54. package/dist/types/llm/bedrock/index.d.ts +7 -0
  55. package/dist/types/messages/cache.d.ts +27 -0
  56. package/dist/types/tools/cloudflare/CloudflareSandboxExecutionEngine.d.ts +53 -0
  57. package/dist/types/tools/local/workspaceFS.d.ts +13 -0
  58. package/package.json +1 -1
  59. package/src/agents/AgentContext.ts +10 -3
  60. package/src/graphs/Graph.ts +24 -6
  61. package/src/llm/bedrock/index.ts +19 -3
  62. package/src/llm/bedrock/llm.spec.ts +97 -0
  63. package/src/messages/cache.test.ts +63 -0
  64. package/src/messages/cache.ts +51 -0
  65. package/src/specs/vllm-reasoning-toolcalls.test.ts +340 -0
  66. package/src/tools/__tests__/CloudflareSandboxExecution.test.ts +323 -0
  67. package/src/tools/__tests__/LocalExecutionTools.test.ts +54 -0
  68. package/src/tools/cloudflare/CloudflareProgrammaticToolCalling.ts +7 -2
  69. package/src/tools/cloudflare/CloudflareSandboxExecutionEngine.ts +269 -37
  70. package/src/tools/local/CompileCheckTool.ts +19 -3
  71. package/src/tools/local/FileCheckpointer.ts +20 -4
  72. package/src/tools/local/LocalCodingTools.ts +61 -8
  73. package/src/tools/local/__tests__/FileCheckpointer.test.ts +42 -0
  74. package/src/tools/local/syntaxCheck.ts +14 -2
  75. package/src/tools/local/workspaceFS.ts +27 -0
@@ -1 +1 @@
1
- {"version":3,"file":"LocalCodingTools.cjs","names":["truncateLocalOutput","runPostEditSyntaxCheck","path","encodeFile","getWorkspaceFS","resolveWorkspacePathSafe","classifyAttachment","imageAttachmentContent","decodeFile","diff","locateEdit","applyEdit","getSpawn","spawnLocalProcess","input","createLocalFileCheckpointer","createCompileCheckTool","createLocalBashExecutionTool","createLocalCodeExecutionTool","createLocalProgrammaticToolCallingTool","createLocalBashProgrammaticToolCallingTool","createCompileCheckToolDefinition"],"sources":["../../../../src/tools/local/LocalCodingTools.ts"],"sourcesContent":["import { basename, dirname } from 'path';\nimport { createTwoFilesPatch } from 'diff';\nimport { tool } from '@langchain/core/tools';\nimport type { DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport {\n createLocalBashProgrammaticToolCallingTool,\n createLocalProgrammaticToolCallingTool,\n} from './LocalProgrammaticToolCalling';\nimport {\n getSpawn,\n getWorkspaceFS,\n resolveWorkspacePathSafe,\n spawnLocalProcess,\n truncateLocalOutput,\n} from './LocalExecutionEngine';\nimport {\n createLocalBashExecutionTool,\n createLocalCodeExecutionTool,\n} from './LocalExecutionTools';\nimport {\n createCompileCheckTool,\n createCompileCheckToolDefinition,\n} from './CompileCheckTool';\nimport { classifyAttachment, imageAttachmentContent } from './attachments';\nimport { createLocalFileCheckpointer } from './FileCheckpointer';\nimport { applyEdit, locateEdit } from './editStrategies';\nimport { decodeFile, encodeFile } from './textEncoding';\nimport { runPostEditSyntaxCheck } from './syntaxCheck';\nimport { Constants } from '@/common';\n\nconst MAX_READ_CHARS = 256000;\nconst DEFAULT_MAX_RESULTS = 200;\nconst DEFAULT_MAX_READ_BYTES = 10 * 1024 * 1024;\nconst BINARY_DETECTION_BYTES = 8000;\n\n/**\n * Tool name aliases retained for back-compat with consumers that imported\n * the per-file `Local*ToolName` constants. The canonical names live on\n * `Constants.*` (see `src/common/enum.ts`); these aliases just point at\n * them so a typo upstream gets caught at the type level.\n */\nexport const LocalWriteFileToolName = Constants.WRITE_FILE;\nexport const LocalEditFileToolName = Constants.EDIT_FILE;\nexport const LocalGrepSearchToolName = Constants.GREP_SEARCH;\nexport const LocalGlobSearchToolName = Constants.GLOB_SEARCH;\nexport const LocalListDirectoryToolName = Constants.LIST_DIRECTORY;\n\nexport const LocalReadFileToolSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description:\n 'Path to a local file, relative to the configured cwd unless absolute paths are allowed.',\n },\n offset: {\n type: 'integer',\n description: 'Optional 1-indexed line offset for large files.',\n },\n limit: {\n type: 'integer',\n description: 'Optional maximum number of lines to return.',\n },\n },\n required: ['path'],\n};\n\nexport const LocalWriteFileToolSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description:\n 'Path to write, relative to the configured cwd unless absolute paths are allowed.',\n },\n content: {\n type: 'string',\n description: 'Complete file contents to write.',\n },\n },\n required: ['path', 'content'],\n};\n\nexport const LocalEditFileToolSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description:\n 'Path to edit, relative to the configured cwd unless absolute paths are allowed.',\n },\n old_text: {\n type: 'string',\n description: 'Exact text to replace. Must appear exactly once.',\n },\n new_text: {\n type: 'string',\n description: 'Replacement text.',\n },\n edits: {\n type: 'array',\n description:\n 'Optional batch of exact replacements. Each old_text must appear exactly once in the original file.',\n items: {\n type: 'object',\n properties: {\n old_text: { type: 'string' },\n new_text: { type: 'string' },\n },\n required: ['old_text', 'new_text'],\n },\n },\n },\n required: ['path'],\n};\n\nexport const LocalGrepSearchToolSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Regex pattern to search for.',\n },\n path: {\n type: 'string',\n description: 'Directory or file to search. Defaults to cwd.',\n },\n glob: {\n type: 'string',\n description: 'Optional file glob passed to rg -g.',\n },\n max_results: {\n type: 'integer',\n description: 'Maximum matching lines to return.',\n },\n },\n required: ['pattern'],\n};\n\nexport const LocalGlobSearchToolSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'File glob pattern, for example \"src/**/*.ts\".',\n },\n path: {\n type: 'string',\n description: 'Directory to search. Defaults to cwd.',\n },\n max_results: {\n type: 'integer',\n description: 'Maximum file paths to return.',\n },\n },\n required: ['pattern'],\n};\n\nexport const LocalListDirectoryToolSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Directory to list. Defaults to cwd.',\n },\n },\n};\n\nfunction lineWindow(\n content: string,\n offset?: number,\n limit?: number\n): { text: string; truncated: boolean } {\n const start = Math.max((offset ?? 1) - 1, 0);\n // Avoid splitting the whole file when the caller asked for a small\n // window. For a 10 MB file with `offset: 1, limit: 10`, the prior\n // `content.split('\\n')` allocated millions of strings to throw all\n // but 10 away. We walk newline indices directly: O(start + limit)\n // instead of O(file). When `limit` is omitted, fall back to the\n // simple split — it's the same amount of work either way.\n if (limit == null || limit <= 0) {\n const lines = content.split('\\n');\n const selected = lines.slice(start);\n const numbered = selected\n .map(\n (line, index) =>\n `${String(start + index + 1).padStart(6, ' ')}\\t${line}`\n )\n .join('\\n');\n return {\n text: truncateLocalOutput(numbered, MAX_READ_CHARS),\n truncated: numbered.length > MAX_READ_CHARS,\n };\n }\n // Walk to the start line by counting newlines.\n let cursor = 0;\n for (let i = 0; i < start; i++) {\n const next = content.indexOf('\\n', cursor);\n if (next === -1) {\n // File has fewer lines than `offset` — return empty window.\n return { text: '', truncated: false };\n }\n cursor = next + 1;\n }\n // Collect up to `limit` lines from `cursor`.\n const out: string[] = [];\n let pos = cursor;\n let exhausted = true;\n for (let k = 0; k < limit; k++) {\n const next = content.indexOf('\\n', pos);\n if (next === -1) {\n out.push(content.slice(pos));\n break;\n }\n out.push(content.slice(pos, next));\n pos = next + 1;\n if (k === limit - 1 && pos < content.length) {\n exhausted = false;\n }\n }\n const numbered = out\n .map(\n (text, index) => `${String(start + index + 1).padStart(6, ' ')}\\t${text}`\n )\n .join('\\n');\n return {\n text: truncateLocalOutput(numbered, MAX_READ_CHARS),\n truncated: !exhausted || numbered.length > MAX_READ_CHARS,\n };\n}\n\nconst MAX_DIFF_CHARS = 4000;\n\ntype SyntaxRun =\n | {\n mode: 'auto' | 'strict';\n outcome: import('./syntaxCheck').SyntaxCheckOutcome;\n }\n | undefined;\n\nasync function maybeRunSyntaxCheck(\n path: string,\n config: t.LocalExecutionConfig\n): Promise<SyntaxRun> {\n const mode = config.postEditSyntaxCheck ?? 'off';\n if (mode === 'off') return undefined;\n const outcome = await runPostEditSyntaxCheck(path, config);\n if (outcome == null) return undefined;\n return { mode, outcome };\n}\n\nfunction appendSyntaxCheckSummary(base: string, run: SyntaxRun): string {\n if (run == null) return base;\n if (run.outcome.ok) return base;\n const banner =\n run.mode === 'strict'\n ? `\\n\\n[syntax-check FAILED via ${run.outcome.checker}]\\n`\n : `\\n\\n[syntax-check warning via ${run.outcome.checker}]\\n`;\n return `${base}${banner}${run.outcome.output}`;\n}\n\n/**\n * Revert a write_file/edit_file mutation in `postEditSyntaxCheck:\n * 'strict'` mode after the post-write syntax check failed. Strict\n * mode advertises a safety gate, so leaving the corrupted file on\n * disk + throwing is a half-broken contract — the model \"reacts\" to\n * the error but the next call sees broken on-disk state. Codex P2\n * [49]. Best-effort: a swallowed error here means the workspace is\n * still in the bad post-write state, but we still throw the\n * original syntax-check error so the caller knows.\n *\n * - If the file existed pre-write: restore the previous bytes with\n * the original encoding.\n * - If the file is brand-new: unlink it.\n */\nasync function revertStrictWrite(\n fs: import('./workspaceFS').WorkspaceFS,\n path: string,\n existed: boolean,\n before: string,\n encoding: { text: string; hasBom: boolean; newline: '\\n' | '\\r\\n' }\n): Promise<void> {\n try {\n if (existed) {\n // encodeFile uses encoding.{hasBom,newline} to restore the\n // on-disk shape; the `text` field is overridden by the\n // explicit `before` arg we pass in.\n await fs.writeFile(\n path,\n encodeFile(before, { ...encoding, text: before }),\n 'utf8'\n );\n } else {\n await fs.unlink(path);\n }\n } catch {\n /* best-effort: caller still sees the original syntax error */\n }\n}\n\nfunction summariseDiff(\n filePath: string,\n before: string,\n after: string\n): string {\n if (before === after) {\n return '(no textual changes)';\n }\n const name = basename(filePath);\n const patch = createTwoFilesPatch(name, name, before, after, '', '', {\n context: 3,\n });\n if (patch.length <= MAX_DIFF_CHARS) {\n return patch;\n }\n return (\n patch.slice(0, MAX_DIFF_CHARS) +\n `\\n[... diff truncated, ${patch.length - MAX_DIFF_CHARS} more chars ...]`\n );\n}\n\nfunction normalizeEdits(input: {\n old_text?: string;\n new_text?: string;\n edits?: Array<{ old_text?: string; new_text?: string }>;\n}): Array<{ oldText: string; newText: string }> {\n const edits = Array.isArray(input.edits)\n ? input.edits.map((edit) => ({\n oldText: edit.old_text ?? '',\n newText: edit.new_text ?? '',\n }))\n : [];\n\n if (input.old_text != null || input.new_text != null) {\n edits.push({\n oldText: input.old_text ?? '',\n newText: input.new_text ?? '',\n });\n }\n\n return edits;\n}\n\nfunction toolDefinition(\n name: string,\n description: string,\n parameters: t.JsonSchemaType\n): t.LCTool {\n return {\n name,\n description,\n parameters,\n allowed_callers: ['direct', 'code_execution'],\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n toolType: 'builtin',\n };\n}\n\nasync function looksBinary(\n path: string,\n fs: import('./workspaceFS').WorkspaceFS\n): Promise<boolean> {\n let handle;\n try {\n handle = await fs.open(path, 'r');\n const sample = Buffer.alloc(BINARY_DETECTION_BYTES);\n const { bytesRead } = await handle.read(\n sample,\n 0,\n BINARY_DETECTION_BYTES,\n 0\n );\n for (let i = 0; i < bytesRead; i++) {\n if (sample[i] === 0) {\n return true;\n }\n }\n return false;\n } finally {\n await handle?.close();\n }\n}\n\nconst DEFAULT_MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024;\n\nexport function createLocalReadFileTool(\n config: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n const fs = getWorkspaceFS(config);\n return tool(\n async (rawInput) => {\n const input = rawInput as {\n path: string;\n offset?: number;\n limit?: number;\n };\n const path = await resolveWorkspacePathSafe(\n input.path,\n config,\n 'read'\n );\n const fileStat = await fs.stat(path);\n if (!fileStat.isFile()) {\n throw new Error(`Path is not a file: ${input.path}`);\n }\n const maxBytes = Math.max(\n config.maxReadBytes ?? DEFAULT_MAX_READ_BYTES,\n 1\n );\n if (fileStat.size > maxBytes) {\n const stub = `File is ${fileStat.size} bytes, exceeds the ${maxBytes}-byte read cap. Read a slice via bash (e.g. head/sed) or raise local.maxReadBytes.`;\n return [stub, { path, bytes: fileStat.size, truncated: true }];\n }\n\n if (await looksBinary(path, fs)) {\n const attachmentMode = config.attachReadAttachments ?? 'off';\n if (attachmentMode !== 'off') {\n const attachment = await classifyAttachment({\n path,\n bytes: fileStat.size,\n mode: attachmentMode,\n maxBytes: config.maxAttachmentBytes ?? DEFAULT_MAX_ATTACHMENT_BYTES,\n // Route through the configured WorkspaceFS so a custom\n // engine sees the same path semantics as `read_file`\n // itself (manual review finding F).\n fs,\n });\n if (attachment.kind === 'image') {\n return [\n imageAttachmentContent(path, attachment),\n {\n path,\n bytes: fileStat.size,\n mime: attachment.mime,\n attachment: 'image',\n },\n ];\n }\n if (attachment.kind === 'pdf') {\n return [\n [\n {\n type: 'text',\n text: `Read ${path} (application/pdf, ${fileStat.size} bytes). PDF attached as base64 data URL; vision-capable models that accept PDF will render it.`,\n },\n {\n type: 'image_url',\n image_url: { url: attachment.dataUrl },\n },\n ],\n {\n path,\n bytes: fileStat.size,\n mime: attachment.mime,\n attachment: 'pdf',\n },\n ];\n }\n if (attachment.kind === 'oversize') {\n return [\n `Refusing to embed ${attachment.mime} attachment (${attachment.bytes} bytes exceeds ${attachment.maxBytes}-byte cap).`,\n {\n path,\n bytes: fileStat.size,\n mime: attachment.mime,\n attachment: 'oversize',\n },\n ];\n }\n if (attachment.kind === 'binary') {\n return [\n `Refusing to read binary file (${fileStat.size} bytes, ${attachment.mime}): ${path}`,\n {\n path,\n bytes: fileStat.size,\n mime: attachment.mime,\n binary: true,\n },\n ];\n }\n // text-or-unknown falls through to the text-read path below.\n } else {\n return [\n `Refusing to read binary file (${fileStat.size} bytes): ${path}`,\n { path, bytes: fileStat.size, binary: true },\n ];\n }\n }\n\n const content = await fs.readFile(path, 'utf8');\n const result = lineWindow(content, input.offset, input.limit);\n return [\n result.truncated ? `${result.text}\\n[truncated]` : result.text,\n { path, bytes: fileStat.size },\n ];\n },\n {\n name: Constants.READ_FILE,\n description:\n 'Read a local text file from the configured working directory with line numbers. ' +\n 'When `attachReadAttachments` is enabled (e.g. images-only), reading an image returns an ' +\n '`image_url` content block so vision-capable models can see the file directly.',\n schema: LocalReadFileToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createLocalWriteFileTool(\n config: t.LocalExecutionConfig = {},\n checkpointer?: t.LocalFileCheckpointer\n): DynamicStructuredTool {\n const fs = getWorkspaceFS(config);\n return tool(\n async (rawInput) => {\n const input = rawInput as { path: string; content: string };\n if (config.readOnly === true) {\n throw new Error('write_file is blocked in read-only local mode.');\n }\n const path = await resolveWorkspacePathSafe(\n input.path,\n config,\n 'write'\n );\n if (checkpointer != null) {\n await checkpointer.captureBeforeWrite(path);\n }\n\n let before = '';\n let encoding = { text: '', hasBom: false, newline: '\\n' as const } as\n | ReturnType<typeof decodeFile>\n | { text: string; hasBom: false; newline: '\\n' };\n let existed = false;\n try {\n const raw = await fs.readFile(path, 'utf8');\n const decoded = decodeFile(raw);\n before = decoded.text;\n encoding = decoded;\n existed = true;\n } catch {\n existed = false;\n }\n\n await fs.mkdir(dirname(path), { recursive: true });\n const finalText = encodeFile(input.content, encoding);\n await fs.writeFile(path, finalText, 'utf8');\n\n const syntax = await maybeRunSyntaxCheck(path, config);\n\n const diff = existed\n ? summariseDiff(path, before, input.content)\n : `(new file, ${input.content.length} chars)`;\n const baseSummary = existed\n ? `Overwrote ${path} (${input.content.length} chars). Diff:\\n${diff}`\n : `Created ${path} (${input.content.length} chars).`;\n const summary = appendSyntaxCheckSummary(baseSummary, syntax);\n if (syntax?.outcome.ok === false && syntax.mode === 'strict') {\n // Roll back the write so strict mode is an actual gate, not\n // \"fail the call AND leave the corrupted file on disk\".\n // Codex P2 [49].\n await revertStrictWrite(fs, path, existed, before, encoding);\n throw new Error(\n `write_file syntax check failed (${syntax.outcome.checker}); reverted to pre-write state.\\n${syntax.outcome.output}`\n );\n }\n return [\n summary,\n {\n path,\n bytes: finalText.length,\n new_file: !existed,\n newline: encoding.newline === '\\r\\n' ? 'CRLF' : 'LF',\n had_bom: encoding.hasBom,\n ...(syntax != null && syntax.outcome.ok === false\n ? { syntax_error: syntax.outcome.checker }\n : {}),\n },\n ];\n },\n {\n name: LocalWriteFileToolName,\n description:\n 'Create or overwrite a local text file in the configured working directory. ' +\n 'Preserves the existing BOM and line endings when overwriting; defaults to LF without BOM for new files. ' +\n 'Returns a unified diff of the changes when overwriting.',\n schema: LocalWriteFileToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createLocalEditFileTool(\n config: t.LocalExecutionConfig = {},\n checkpointer?: t.LocalFileCheckpointer\n): DynamicStructuredTool {\n const fs = getWorkspaceFS(config);\n return tool(\n async (rawInput) => {\n const input = rawInput as {\n path: string;\n old_text?: string;\n new_text?: string;\n edits?: Array<{ old_text?: string; new_text?: string }>;\n };\n if (config.readOnly === true) {\n throw new Error('edit_file is blocked in read-only local mode.');\n }\n const edits = normalizeEdits(input);\n if (edits.length === 0) {\n throw new Error('edit_file requires old_text/new_text or edits[].');\n }\n\n const path = await resolveWorkspacePathSafe(\n input.path,\n config,\n 'write'\n );\n const raw = await fs.readFile(path, 'utf8');\n const encoding = decodeFile(raw);\n const original = encoding.text;\n\n let next = original;\n const strategiesUsed: string[] = [];\n for (let i = 0; i < edits.length; i++) {\n const edit = edits[i];\n const match = locateEdit(next, edit.oldText);\n if (match == null) {\n throw new Error(\n `Edit ${i + 1}/${edits.length}: could not locate old_text in ${input.path}. ` +\n 'Tried exact, line-trimmed, whitespace-normalized, and indentation-flexible matching. ' +\n 'Re-read the file and copy the literal lines.'\n );\n }\n strategiesUsed.push(match.strategy);\n next = applyEdit(next, match, edit.newText);\n }\n\n if (checkpointer != null) {\n await checkpointer.captureBeforeWrite(path);\n }\n const finalText = encodeFile(next, encoding);\n await fs.writeFile(path, finalText, 'utf8');\n\n const syntax = await maybeRunSyntaxCheck(path, config);\n\n const diff = summariseDiff(path, original, next);\n const fuzzy = strategiesUsed.some((s) => s !== 'exact');\n const baseSummary =\n `Applied ${edits.length} edit(s) to ${path}` +\n (fuzzy ? ` (strategies: ${strategiesUsed.join(', ')})` : '') +\n `. Diff:\\n${diff}`;\n const summary = appendSyntaxCheckSummary(baseSummary, syntax);\n if (syntax?.outcome.ok === false && syntax.mode === 'strict') {\n // Restore the pre-edit bytes so strict mode is an actual\n // gate (Codex P2 [49]). edit_file always operates on an\n // existing file, so `existed = true` here.\n await revertStrictWrite(fs, path, true, original, encoding);\n throw new Error(\n `edit_file syntax check failed (${syntax.outcome.checker}); reverted to pre-edit state.\\n${syntax.outcome.output}`\n );\n }\n return [\n summary,\n {\n path,\n edits: edits.length,\n strategies: strategiesUsed,\n newline: encoding.newline === '\\r\\n' ? 'CRLF' : 'LF',\n had_bom: encoding.hasBom,\n ...(syntax != null && syntax.outcome.ok === false\n ? { syntax_error: syntax.outcome.checker }\n : {}),\n },\n ];\n },\n {\n name: LocalEditFileToolName,\n description:\n 'Apply exact text replacements to a local file. The matcher tries exact, line-trimmed, whitespace-normalized, and indentation-flexible strategies in order so common LLM whitespace mistakes are recoverable. Each old_text must still match exactly one location. Returns a unified diff of the changes.',\n schema: LocalEditFileToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\n/**\n * Ripgrep availability cache, keyed on the *effective execution\n * backend* — whatever function `getSpawn(config)` returns. Without\n * the backend key, a Run that probes `rg` over Node's\n * `child_process.spawn` would poison subsequent Runs whose\n * `local.exec.spawn` routes to a remote sandbox or container that\n * doesn't have rg installed: the cached `true` would skip the probe,\n * the rg invocation would throw, and the Node fallback wouldn't be\n * reached. Per-backend caching avoids that without paying for a\n * spawn-per-search.\n */\n// Per-backend × per-env cache. Codex P1 #34 — keying by spawn\n// backend alone misses the case where two Runs share a backend but\n// vary `local.env` (especially PATH). Stale cache then claims `rg`\n// is available, the rg path runs, and the spawn fails with ENOENT\n// instead of falling back to the Node walker. The inner Map is\n// keyed by a stable JSON hash of the effective env so each unique\n// env gets its own probe.\nlet ripgrepAvailabilityByBackend = new WeakMap<\n t.LocalSpawn,\n Map<string, Promise<boolean>>\n>();\n\nfunction envCacheKey(env: NodeJS.ProcessEnv | undefined): string {\n // PATH is the only env entry that affects command lookup, but\n // hashing the whole env keeps the key correct for hosts that\n // vary anything else relevant. Stable JSON via sorted keys so\n // {A:1,B:2} and {B:2,A:1} produce the same hash.\n if (env == null) return '';\n const sorted: Record<string, string | undefined> = {};\n for (const k of Object.keys(env).sort()) {\n sorted[k] = env[k];\n }\n return JSON.stringify(sorted);\n}\n\nasync function isRipgrepAvailable(\n config: t.LocalExecutionConfig\n): Promise<boolean> {\n const backend = getSpawn(config);\n let envMap = ripgrepAvailabilityByBackend.get(backend);\n if (envMap == null) {\n envMap = new Map();\n ripgrepAvailabilityByBackend.set(backend, envMap);\n }\n const envKey = envCacheKey(config.env);\n let probePromise = envMap.get(envKey);\n if (probePromise == null) {\n probePromise = spawnLocalProcess(\n 'rg',\n ['--version'],\n { ...config, timeoutMs: 5000, sandbox: { enabled: false } },\n { internal: true }\n )\n .then((probe) => probe.exitCode === 0)\n .catch(() => false);\n envMap.set(envKey, probePromise);\n }\n return probePromise;\n}\n\n/**\n * Test-only reset hook. Clears the ripgrep-availability cache so\n * tests can swap in mocked spawn backends and reprobe deterministically.\n *\n * @internal Not part of the public SDK surface; the leading underscore\n * and `@internal` tag together signal that consumers should not call\n * this. Tests import it via the module path directly.\n */\nexport function _resetRipgrepCacheForTests(): void {\n ripgrepAvailabilityByBackend = new WeakMap();\n}\n\n// Skipped by the Node-fallback walker (used when ripgrep is\n// unavailable). Covers common build outputs, virtualenvs, and\n// caches so a `grep_search`/`glob_search` on a large monorepo or a\n// Python project with `.venv/` doesn't read every file under those\n// trees. ripgrep itself respects .gitignore so it doesn't need this\n// list. Audit follow-up from the comprehensive review (finding #3).\nconst SKIP_DIRS = new Set([\n '.git',\n '.svn',\n '.hg',\n 'node_modules',\n '.next',\n '.nuxt',\n '.cache',\n '.parcel-cache',\n '.turbo',\n 'dist',\n 'build',\n 'out',\n 'target',\n 'vendor',\n 'coverage',\n '.nyc_output',\n '__pycache__',\n '.venv',\n 'venv',\n 'env',\n '.tox',\n '.mypy_cache',\n '.pytest_cache',\n '.ruff_cache',\n]);\n\nfunction globToRegExp(pattern: string): RegExp {\n let result = '^';\n for (let i = 0; i < pattern.length; i++) {\n const c = pattern[i];\n if (c === '*') {\n if (pattern[i + 1] === '*') {\n result += '.*';\n i += 1;\n if (pattern[i + 1] === '/') {\n i += 1;\n }\n } else {\n result += '[^/]*';\n }\n } else if (c === '?') {\n result += '[^/]';\n } else if ('.+^$|(){}[]\\\\'.includes(c)) {\n result += '\\\\' + c;\n } else {\n result += c;\n }\n }\n result += '$';\n return new RegExp(result);\n}\n\nasync function* walkFiles(\n root: string,\n fs: import('./workspaceFS').WorkspaceFS\n): AsyncGenerator<string> {\n const stack: string[] = [root];\n while (stack.length > 0) {\n const dir = stack.pop() as string;\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of entries) {\n if (entry.name.startsWith('.git') || SKIP_DIRS.has(entry.name)) {\n continue;\n }\n const full = `${dir}/${entry.name}`;\n if (entry.isDirectory()) {\n stack.push(full);\n } else if (entry.isFile()) {\n yield full;\n }\n }\n }\n}\n\n/**\n * Catastrophic-backtracking guardrails for the fallback grep path.\n *\n * Without ripgrep we run the model-supplied pattern through Node's\n * `RegExp` engine, which uses a backtracking implementation. Patterns\n * with nested unbounded quantifiers (`(a+)+`, `(.*)*`, etc.) can\n * monopolise the event loop for arbitrary wall-clock time on\n * pathological input, and `setTimeout` cannot interrupt a synchronous\n * `RegExp.exec`. Manual review (finding D) flagged this as a real DoS.\n *\n * Mitigations applied here, in order of severity:\n * 1. Cap pattern length so an obviously oversize regex is rejected\n * before compile.\n * 2. Reject patterns that contain a nested unbounded quantifier of\n * the form `(...+|*)([+*]|{n,})` — the standard pathological\n * shape. Still a heuristic (not a full safety proof), but blocks\n * every common DoS construction we've seen in coding-agent logs.\n * 3. Wall-clock budget for the overall search: each file's regex\n * pass is checked against a deadline; once exceeded the search\n * bails with a partial result. Doesn't interrupt a stuck\n * `exec()` call, but stops a slow pattern from making the whole\n * Run hang once the first hung file finishes.\n *\n * Hosts that need bulletproof regex safety should install `rg` —\n * ripgrep uses RE2 internally and has no backtracking.\n */\nconst MAX_FALLBACK_PATTERN_LENGTH = 1024;\nconst FALLBACK_GREP_BUDGET_MS = 5000;\n// Per-file byte cap. Codex P2 #41 — without it, the whole-file\n// `readFile` + `split('\\n')` for a multi-GB log is an unbounded\n// allocation that the wall-clock budget (checked between files)\n// can't interrupt. Hosts that need to grep large files should\n// install ripgrep.\nconst FALLBACK_GREP_MAX_FILE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Heuristic: walks `pattern` to find any `(<contents>)<quant>` where\n * `<contents>` itself has an unbounded quantifier. Catches the\n * classic `(a+)+` form AND the double-nested `((a+)+)` form (which a\n * single-pass regex misses because `[^)]*` stops at the first inner\n * close-paren). Misses sufficiently obfuscated cases — bulletproof\n * ReDoS detection requires a real parser. The 5 s wall-clock budget\n * is the hard backstop for anything this slip past.\n */\nfunction hasNestedUnboundedQuantifier(pattern: string): boolean {\n for (let i = 1; i < pattern.length - 1; i++) {\n if (pattern[i] !== ')') continue;\n if (pattern[i - 1] === '\\\\') continue;\n const next = pattern[i + 1];\n if (next !== '+' && next !== '*' && next !== '{') continue;\n // Walk back to find the matching opening paren (respecting depth\n // and `\\(` escapes).\n let depth = 1;\n let j = i - 1;\n while (j >= 0) {\n const c = pattern[j];\n const escaped = j > 0 && pattern[j - 1] === '\\\\';\n if (!escaped) {\n if (c === ')') depth++;\n else if (c === '(') {\n depth--;\n if (depth === 0) break;\n }\n }\n j--;\n }\n if (j < 0) continue;\n const inner = pattern.slice(j + 1, i);\n if (/(?<!\\\\)[+*]/.test(inner)) return true;\n }\n return false;\n}\n\nclass FallbackGrepError extends Error {\n readonly kind: 'pattern-too-long' | 'unsafe-pattern' | 'invalid-pattern';\n constructor(\n kind: 'pattern-too-long' | 'unsafe-pattern' | 'invalid-pattern',\n message: string\n ) {\n super(message);\n this.kind = kind;\n }\n}\n\nfunction compileFallbackRegex(pattern: string): RegExp {\n if (pattern.length > MAX_FALLBACK_PATTERN_LENGTH) {\n throw new FallbackGrepError(\n 'pattern-too-long',\n `Pattern exceeds ${MAX_FALLBACK_PATTERN_LENGTH}-char fallback cap (install ripgrep for unbounded patterns).`\n );\n }\n if (hasNestedUnboundedQuantifier(pattern)) {\n throw new FallbackGrepError(\n 'unsafe-pattern',\n 'Pattern contains a nested unbounded quantifier (e.g. `(a+)+` or `((a+)+)`) which can cause catastrophic backtracking in the Node fallback. Install ripgrep for RE2-safe matching.'\n );\n }\n try {\n return new RegExp(pattern);\n } catch (e) {\n throw new FallbackGrepError(\n 'invalid-pattern',\n `Invalid regex: ${(e as Error).message}`\n );\n }\n}\n\n/** Structured return so callers can count matches separately from\n * diagnostic skip-sentinels (Codex P2 [43]). */\ntype FallbackGrepResult = { matches: string[]; skipped: string[] };\n\n/** Renders fallback-grep output: real matches first, skip diagnostics appended. */\nfunction formatFallbackGrepDisplay(result: FallbackGrepResult): string {\n if (result.matches.length > 0) {\n return [...result.matches, ...result.skipped].join('\\n');\n }\n if (result.skipped.length > 0) {\n return result.skipped.join('\\n');\n }\n return 'No matches found.';\n}\n\nasync function fallbackGrep(\n root: string,\n pattern: string,\n globFilter: string | undefined,\n maxResults: number,\n fs: import('./workspaceFS').WorkspaceFS\n): Promise<FallbackGrepResult> {\n const rx = compileFallbackRegex(pattern);\n const deadline = Date.now() + FALLBACK_GREP_BUDGET_MS;\n const globRx =\n globFilter != null && globFilter !== ''\n ? globToRegExp(globFilter)\n : undefined;\n const matches: string[] = [];\n // Track skipped (oversize) files separately so they don't consume\n // the maxResults budget. Codex P2 [43]: round 14's fix pushed skip\n // sentinels into `matches`, so a directory of one oversize non-\n // matching file falsely reported `matches: 1`, and enough\n // oversize files could fill the budget before any real match was\n // scanned. Now diagnostics are appended after real matches and\n // independent of the budget.\n const skippedDiagnostics: string[] = [];\n for await (const file of walkFiles(root, fs)) {\n if (Date.now() > deadline) {\n // Wall-clock budget exceeded — return partial results rather\n // than letting a slow pattern hang the Run.\n return { matches, skipped: skippedDiagnostics };\n }\n if (globRx != null) {\n const rel = file.startsWith(root + '/')\n ? file.slice(root.length + 1)\n : file;\n if (!globRx.test(rel)) {\n continue;\n }\n }\n // Skip files larger than the per-file cap and remember them as\n // diagnostics (NOT as matches). Codex P2 [41]: pre-fix\n // `fs.readFile` then `.split('\\n')` allocated the whole file +\n // an array of every line, which a single multi-GB log could\n // turn into an OOM even after the regex DoS guards.\n let stat;\n try {\n stat = await fs.stat(file);\n } catch {\n continue;\n }\n if (stat.size > FALLBACK_GREP_MAX_FILE_BYTES) {\n skippedDiagnostics.push(\n `${file}:0:[skipped: file > ${FALLBACK_GREP_MAX_FILE_BYTES} bytes; install ripgrep for unbounded grep]`\n );\n continue;\n }\n let content;\n try {\n content = await fs.readFile(file, 'utf8');\n } catch {\n continue;\n }\n if (content.includes('\\0')) {\n continue;\n }\n // Re-check the deadline AFTER the read — a slow disk on one\n // file can blow the budget without us noticing.\n if (Date.now() > deadline) {\n return { matches, skipped: skippedDiagnostics };\n }\n const lines = content.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n if (rx.test(lines[i])) {\n matches.push(`${file}:${i + 1}:${lines[i]}`);\n if (matches.length >= maxResults) {\n return { matches, skipped: skippedDiagnostics };\n }\n }\n }\n }\n return { matches, skipped: skippedDiagnostics };\n}\n\nasync function fallbackGlob(\n root: string,\n pattern: string,\n maxResults: number,\n fs: import('./workspaceFS').WorkspaceFS\n): Promise<string[]> {\n const rx = globToRegExp(pattern);\n const out: string[] = [];\n for await (const file of walkFiles(root, fs)) {\n const rel = file.startsWith(root + '/')\n ? file.slice(root.length + 1)\n : file;\n if (rx.test(rel)) {\n out.push(file);\n if (out.length >= maxResults) {\n break;\n }\n }\n }\n return out;\n}\n\nexport function createLocalGrepSearchTool(\n config: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n const fs = getWorkspaceFS(config);\n return tool(\n async (rawInput) => {\n const input = rawInput as {\n pattern: string;\n path?: string;\n glob?: string;\n max_results?: number;\n };\n const target = await resolveWorkspacePathSafe(\n input.path ?? '.',\n config,\n 'read'\n );\n const maxResults = Math.max(input.max_results ?? DEFAULT_MAX_RESULTS, 1);\n\n if (await isRipgrepAvailable(config)) {\n // Pass the pattern through `-e` so dash-prefixed patterns\n // like `-foo` are treated as the search regex, not as a\n // (probably-unknown) flag. `rg --help` explicitly requires\n // `-e/--regexp` (or `--`) for that case. Same trick avoids\n // any future flag-conflict if a user query happens to look\n // like an rg long option.\n const args = [\n '--line-number',\n '--column',\n '--hidden',\n '--glob',\n '!.git/**',\n ...(input.glob != null && input.glob !== ''\n ? ['--glob', input.glob]\n : []),\n '-e',\n input.pattern,\n target,\n ];\n const result = await spawnLocalProcess('rg', args, {\n ...config,\n timeoutMs: config.timeoutMs ?? 30000,\n });\n // ripgrep exit codes:\n // 0 → at least one match\n // 1 → no matches (clean — \"No matches found.\")\n // 2 → real error (bad regex, unreadable target, etc.)\n // Without this branch (Codex P2 #23 — same fix shape glob_search\n // got from P2 #13), exit-2 errors silently mapped to\n // `matches: 0`, so the agent treated tooling failures as a\n // genuine absence of matches.\n if (\n result.timedOut ||\n (result.exitCode != null && result.exitCode > 1)\n ) {\n const detail = result.stderr.trim() || `rg exited ${result.exitCode}`;\n return [\n `grep_search failed: ${detail}`,\n {\n matches: 0,\n engine: 'ripgrep',\n error: detail,\n exitCode: result.exitCode,\n },\n ];\n }\n const lines = result.stdout\n .split('\\n')\n .filter(Boolean)\n .slice(0, maxResults);\n const output =\n lines.length > 0\n ? lines.join('\\n')\n : result.stderr.trim() || 'No matches found.';\n return [output, { matches: lines.length, engine: 'ripgrep' }];\n }\n\n try {\n const { matches, skipped } = await fallbackGrep(\n target,\n input.pattern,\n input.glob,\n maxResults,\n fs\n );\n // Artifact count: ONLY real matches (Codex P2 [43] —\n // skip sentinels used to inflate the count and the budget).\n const display = formatFallbackGrepDisplay({ matches, skipped });\n return [\n display,\n {\n matches: matches.length,\n skipped: skipped.length,\n engine: 'node-fallback',\n },\n ];\n } catch (e) {\n if (e instanceof FallbackGrepError) {\n return [\n `grep_search refused the pattern: ${e.message}`,\n {\n matches: 0,\n engine: 'node-fallback',\n error: e.message,\n kind: e.kind,\n },\n ];\n }\n throw e;\n }\n },\n {\n name: LocalGrepSearchToolName,\n description:\n 'Search local files for a regex pattern (ripgrep when available, Node fallback otherwise).',\n schema: LocalGrepSearchToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createLocalGlobSearchTool(\n config: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n const fs = getWorkspaceFS(config);\n return tool(\n async (rawInput) => {\n const input = rawInput as {\n pattern: string;\n path?: string;\n max_results?: number;\n };\n const target = await resolveWorkspacePathSafe(\n input.path ?? '.',\n config,\n 'read'\n );\n const maxResults = Math.max(input.max_results ?? DEFAULT_MAX_RESULTS, 1);\n\n if (await isRipgrepAvailable(config)) {\n const result = await spawnLocalProcess(\n 'rg',\n [\n '--files',\n '--hidden',\n '--glob',\n '!.git/**',\n '--glob',\n input.pattern,\n target,\n ],\n { ...config, timeoutMs: config.timeoutMs ?? 30000 }\n );\n // rg --files exit codes:\n // 0 → at least one file matched\n // 1 → no files matched (clean — \"No files found.\")\n // 2 → real error (bad glob, unreadable target, etc.)\n // Without this branch, exit-2 errors used to silently map to\n // \"No files found.\" — the agent then treats a tooling failure\n // as a real absence of matches.\n if (\n result.timedOut ||\n (result.exitCode != null && result.exitCode > 1)\n ) {\n const detail = result.stderr.trim() || `rg exited ${result.exitCode}`;\n return [\n `glob_search failed: ${detail}`,\n {\n files: [],\n engine: 'ripgrep',\n error: detail,\n exitCode: result.exitCode,\n },\n ];\n }\n const lines = result.stdout\n .split('\\n')\n .filter(Boolean)\n .slice(0, maxResults);\n return [\n lines.length > 0 ? lines.join('\\n') : 'No files found.',\n { files: lines, engine: 'ripgrep' },\n ];\n }\n\n const files = await fallbackGlob(target, input.pattern, maxResults, fs);\n return [\n files.length > 0 ? files.join('\\n') : 'No files found.',\n { files, engine: 'node-fallback' },\n ];\n },\n {\n name: LocalGlobSearchToolName,\n description:\n 'Find local files matching a glob pattern (ripgrep when available, Node fallback otherwise).',\n schema: LocalGlobSearchToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createLocalListDirectoryTool(\n config: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n const fs = getWorkspaceFS(config);\n return tool(\n async (rawInput) => {\n const input = rawInput as { path?: string };\n const path = await resolveWorkspacePathSafe(\n input.path ?? '.',\n config,\n 'read'\n );\n const entries = await fs.readdir(path, { withFileTypes: true });\n const output = entries\n .map(\n (entry) => `${entry.isDirectory() ? 'dir ' : 'file'}\\t${entry.name}`\n )\n .join('\\n');\n return [output || 'Directory is empty.', { path, count: entries.length }];\n },\n {\n name: LocalListDirectoryToolName,\n description: 'List files and directories in a local directory.',\n schema: LocalListDirectoryToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport type LocalCodingToolBundle = {\n tools: DynamicStructuredTool[];\n /**\n * Present when `config.fileCheckpointing === true` or a `checkpointer`\n * was passed in. Callers can call `rewind()` to restore captured\n * pre-write contents.\n */\n checkpointer?: t.LocalFileCheckpointer;\n};\n\nexport function createLocalCodingTools(\n config: t.LocalExecutionConfig = {},\n options: { checkpointer?: t.LocalFileCheckpointer } = {}\n): DynamicStructuredTool[] {\n const checkpointer =\n options.checkpointer ??\n (config.fileCheckpointing === true\n ? createLocalFileCheckpointer({ fs: config.exec?.fs })\n : undefined);\n return [\n createLocalReadFileTool(config),\n createLocalWriteFileTool(config, checkpointer),\n createLocalEditFileTool(config, checkpointer),\n createLocalGrepSearchTool(config),\n createLocalGlobSearchTool(config),\n createLocalListDirectoryTool(config),\n createCompileCheckTool(config),\n createLocalBashExecutionTool({ config }),\n createLocalCodeExecutionTool(config),\n createLocalProgrammaticToolCallingTool(config),\n createLocalBashProgrammaticToolCallingTool(config),\n ];\n}\n\n/**\n * Variant of `createLocalCodingTools` that returns the bundle alongside\n * the file checkpointer so callers can later call\n * `bundle.checkpointer?.rewind()`.\n */\nexport function createLocalCodingToolBundle(\n config: t.LocalExecutionConfig = {},\n options: { checkpointer?: t.LocalFileCheckpointer } = {}\n): LocalCodingToolBundle {\n const checkpointer =\n options.checkpointer ??\n (config.fileCheckpointing === true\n ? createLocalFileCheckpointer({ fs: config.exec?.fs })\n : undefined);\n return {\n tools: createLocalCodingTools(config, { checkpointer }),\n checkpointer,\n };\n}\n\nexport function createLocalCodingToolDefinitions(): t.LCTool[] {\n return [\n toolDefinition(\n Constants.READ_FILE,\n 'Read a local text file from the configured working directory with line numbers.',\n LocalReadFileToolSchema as t.JsonSchemaType\n ),\n toolDefinition(\n LocalWriteFileToolName,\n 'Create or overwrite a local text file in the configured working directory.',\n LocalWriteFileToolSchema as t.JsonSchemaType\n ),\n toolDefinition(\n LocalEditFileToolName,\n 'Apply exact text replacements to a local file.',\n LocalEditFileToolSchema as t.JsonSchemaType\n ),\n toolDefinition(\n LocalGrepSearchToolName,\n 'Search local files with ripgrep and return matching lines.',\n LocalGrepSearchToolSchema as t.JsonSchemaType\n ),\n toolDefinition(\n LocalGlobSearchToolName,\n 'Find local files matching a glob pattern.',\n LocalGlobSearchToolSchema as t.JsonSchemaType\n ),\n toolDefinition(\n LocalListDirectoryToolName,\n 'List files and directories in a local directory.',\n LocalListDirectoryToolSchema as t.JsonSchemaType\n ),\n createCompileCheckToolDefinition(),\n ];\n}\n\nexport function createLocalCodingToolRegistry(): t.LCToolRegistry {\n return new Map(\n createLocalCodingToolDefinitions().map((definition) => [\n definition.name,\n definition,\n ])\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AA+BA,MAAM,iBAAiB;AACvB,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB,KAAK,OAAO;AAC3C,MAAM,yBAAyB;;;;;;;AAQ/B,MAAa,yBAAA;AACb,MAAa,wBAAA;AACb,MAAa,0BAAA;AACb,MAAa,0BAAA;AACb,MAAa,6BAAA;AAEb,MAAa,0BAA4C;CACvD,MAAM;CACN,YAAY;EACV,MAAM;GACJ,MAAM;GACN,aACE;EACJ;EACA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,OAC1Ba,yBAAAA,4BAA4B,EAAE,IAAI,OAAO,MAAM,GAAG,CAAC,IACnD,KAAA;CACN,OAAO;EACL,wBAAwB,MAAM;EAC9B,yBAAyB,QAAQ,YAAY;EAC7C,wBAAwB,QAAQ,YAAY;EAC5C,0BAA0B,MAAM;EAChC,0BAA0B,MAAM;EAChC,6BAA6B,MAAM;EACnCC,yBAAAA,uBAAuB,MAAM;EAC7BC,4BAAAA,6BAA6B,EAAE,OAAO,CAAC;EACvCC,4BAAAA,6BAA6B,MAAM;EACnCC,qCAAAA,uCAAuC,MAAM;EAC7CC,qCAAAA,2CAA2C,MAAM;CACnD;AACF;;;;;;AAOA,SAAgB,4BACd,SAAiC,CAAC,GAClC,UAAsD,CAAC,GAChC;CACvB,MAAM,eACJ,QAAQ,iBACP,OAAO,sBAAsB,OAC1BL,yBAAAA,4BAA4B,EAAE,IAAI,OAAO,MAAM,GAAG,CAAC,IACnD,KAAA;CACN,OAAO;EACL,OAAO,uBAAuB,QAAQ,EAAE,aAAa,CAAC;EACtD;CACF;AACF;AAEA,SAAgB,mCAA+C;CAC7D,OAAO;EACL,eAAA,aAEE,mFACA,uBACF;EACA,eACE,wBACA,8EACA,wBACF;EACA,eACE,uBACA,kDACA,uBACF;EACA,eACE,yBACA,8DACA,yBACF;EACA,eACE,yBACA,6CACA,yBACF;EACA,eACE,4BACA,oDACA,4BACF;EACAM,yBAAAA,iCAAiC;CACnC;AACF;AAEA,SAAgB,gCAAkD;CAChE,OAAO,IAAI,IACT,iCAAiC,CAAC,CAAC,KAAK,eAAe,CACrD,WAAW,MACX,UACF,CAAC,CACH;AACF"}
1
+ {"version":3,"file":"LocalCodingTools.cjs","names":["truncateLocalOutput","runPostEditSyntaxCheck","path","encodeFile","isWorkspaceClientTimeoutError","getWorkspaceFS","resolveWorkspacePathSafe","classifyAttachment","imageAttachmentContent","decodeFile","diff","locateEdit","applyEdit","getSpawn","spawnLocalProcess","input","createLocalFileCheckpointer","createCompileCheckTool","createLocalBashExecutionTool","createLocalCodeExecutionTool","createLocalProgrammaticToolCallingTool","createLocalBashProgrammaticToolCallingTool","createCompileCheckToolDefinition"],"sources":["../../../../src/tools/local/LocalCodingTools.ts"],"sourcesContent":["import { basename, dirname } from 'path';\nimport { createTwoFilesPatch } from 'diff';\nimport { tool } from '@langchain/core/tools';\nimport type { DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { isWorkspaceClientTimeoutError } from './workspaceFS';\nimport {\n createLocalBashProgrammaticToolCallingTool,\n createLocalProgrammaticToolCallingTool,\n} from './LocalProgrammaticToolCalling';\nimport {\n getSpawn,\n getWorkspaceFS,\n resolveWorkspacePathSafe,\n spawnLocalProcess,\n truncateLocalOutput,\n} from './LocalExecutionEngine';\nimport {\n createLocalBashExecutionTool,\n createLocalCodeExecutionTool,\n} from './LocalExecutionTools';\nimport {\n createCompileCheckTool,\n createCompileCheckToolDefinition,\n} from './CompileCheckTool';\nimport { classifyAttachment, imageAttachmentContent } from './attachments';\nimport { createLocalFileCheckpointer } from './FileCheckpointer';\nimport { applyEdit, locateEdit } from './editStrategies';\nimport { decodeFile, encodeFile } from './textEncoding';\nimport { runPostEditSyntaxCheck } from './syntaxCheck';\nimport { Constants } from '@/common';\n\nconst MAX_READ_CHARS = 256000;\nconst DEFAULT_MAX_RESULTS = 200;\nconst DEFAULT_MAX_READ_BYTES = 10 * 1024 * 1024;\nconst BINARY_DETECTION_BYTES = 8000;\n\n/**\n * Tool name aliases retained for back-compat with consumers that imported\n * the per-file `Local*ToolName` constants. The canonical names live on\n * `Constants.*` (see `src/common/enum.ts`); these aliases just point at\n * them so a typo upstream gets caught at the type level.\n */\nexport const LocalWriteFileToolName = Constants.WRITE_FILE;\nexport const LocalEditFileToolName = Constants.EDIT_FILE;\nexport const LocalGrepSearchToolName = Constants.GREP_SEARCH;\nexport const LocalGlobSearchToolName = Constants.GLOB_SEARCH;\nexport const LocalListDirectoryToolName = Constants.LIST_DIRECTORY;\n\nexport const LocalReadFileToolSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description:\n 'Path to a local file, relative to the configured cwd unless absolute paths are allowed.',\n },\n offset: {\n type: 'integer',\n description: 'Optional 1-indexed line offset for large files.',\n },\n limit: {\n type: 'integer',\n description: 'Optional maximum number of lines to return.',\n },\n },\n required: ['path'],\n};\n\nexport const LocalWriteFileToolSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description:\n 'Path to write, relative to the configured cwd unless absolute paths are allowed.',\n },\n content: {\n type: 'string',\n description: 'Complete file contents to write.',\n },\n },\n required: ['path', 'content'],\n};\n\nexport const LocalEditFileToolSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description:\n 'Path to edit, relative to the configured cwd unless absolute paths are allowed.',\n },\n old_text: {\n type: 'string',\n description: 'Exact text to replace. Must appear exactly once.',\n },\n new_text: {\n type: 'string',\n description: 'Replacement text.',\n },\n edits: {\n type: 'array',\n description:\n 'Optional batch of exact replacements. Each old_text must appear exactly once in the original file.',\n items: {\n type: 'object',\n properties: {\n old_text: { type: 'string' },\n new_text: { type: 'string' },\n },\n required: ['old_text', 'new_text'],\n },\n },\n },\n required: ['path'],\n};\n\nexport const LocalGrepSearchToolSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Regex pattern to search for.',\n },\n path: {\n type: 'string',\n description: 'Directory or file to search. Defaults to cwd.',\n },\n glob: {\n type: 'string',\n description: 'Optional file glob passed to rg -g.',\n },\n max_results: {\n type: 'integer',\n description: 'Maximum matching lines to return.',\n },\n },\n required: ['pattern'],\n};\n\nexport const LocalGlobSearchToolSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'File glob pattern, for example \"src/**/*.ts\".',\n },\n path: {\n type: 'string',\n description: 'Directory to search. Defaults to cwd.',\n },\n max_results: {\n type: 'integer',\n description: 'Maximum file paths to return.',\n },\n },\n required: ['pattern'],\n};\n\nexport const LocalListDirectoryToolSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Directory to list. Defaults to cwd.',\n },\n },\n};\n\nfunction lineWindow(\n content: string,\n offset?: number,\n limit?: number\n): { text: string; truncated: boolean } {\n const start = Math.max((offset ?? 1) - 1, 0);\n // Avoid splitting the whole file when the caller asked for a small\n // window. For a 10 MB file with `offset: 1, limit: 10`, the prior\n // `content.split('\\n')` allocated millions of strings to throw all\n // but 10 away. We walk newline indices directly: O(start + limit)\n // instead of O(file). When `limit` is omitted, fall back to the\n // simple split — it's the same amount of work either way.\n if (limit == null || limit <= 0) {\n const lines = content.split('\\n');\n const selected = lines.slice(start);\n const numbered = selected\n .map(\n (line, index) =>\n `${String(start + index + 1).padStart(6, ' ')}\\t${line}`\n )\n .join('\\n');\n return {\n text: truncateLocalOutput(numbered, MAX_READ_CHARS),\n truncated: numbered.length > MAX_READ_CHARS,\n };\n }\n // Walk to the start line by counting newlines.\n let cursor = 0;\n for (let i = 0; i < start; i++) {\n const next = content.indexOf('\\n', cursor);\n if (next === -1) {\n // File has fewer lines than `offset` — return empty window.\n return { text: '', truncated: false };\n }\n cursor = next + 1;\n }\n // Collect up to `limit` lines from `cursor`.\n const out: string[] = [];\n let pos = cursor;\n let exhausted = true;\n for (let k = 0; k < limit; k++) {\n const next = content.indexOf('\\n', pos);\n if (next === -1) {\n out.push(content.slice(pos));\n break;\n }\n out.push(content.slice(pos, next));\n pos = next + 1;\n if (k === limit - 1 && pos < content.length) {\n exhausted = false;\n }\n }\n const numbered = out\n .map(\n (text, index) => `${String(start + index + 1).padStart(6, ' ')}\\t${text}`\n )\n .join('\\n');\n return {\n text: truncateLocalOutput(numbered, MAX_READ_CHARS),\n truncated: !exhausted || numbered.length > MAX_READ_CHARS,\n };\n}\n\nconst MAX_DIFF_CHARS = 4000;\n\ntype SyntaxRun =\n | {\n mode: 'auto' | 'strict';\n outcome: import('./syntaxCheck').SyntaxCheckOutcome;\n }\n | undefined;\n\nasync function maybeRunSyntaxCheck(\n path: string,\n config: t.LocalExecutionConfig\n): Promise<SyntaxRun> {\n const mode = config.postEditSyntaxCheck ?? 'off';\n if (mode === 'off') return undefined;\n const outcome = await runPostEditSyntaxCheck(path, config);\n if (outcome == null) return undefined;\n return { mode, outcome };\n}\n\nfunction appendSyntaxCheckSummary(base: string, run: SyntaxRun): string {\n if (run == null) return base;\n if (run.outcome.ok) return base;\n const banner =\n run.mode === 'strict'\n ? `\\n\\n[syntax-check FAILED via ${run.outcome.checker}]\\n`\n : `\\n\\n[syntax-check warning via ${run.outcome.checker}]\\n`;\n return `${base}${banner}${run.outcome.output}`;\n}\n\n/**\n * Revert a write_file/edit_file mutation in `postEditSyntaxCheck:\n * 'strict'` mode after the post-write syntax check failed. Strict\n * mode advertises a safety gate, so leaving the corrupted file on\n * disk + throwing is a half-broken contract — the model \"reacts\" to\n * the error but the next call sees broken on-disk state. Codex P2\n * [49]. Best-effort: a swallowed error here means the workspace is\n * still in the bad post-write state, but we still throw the\n * original syntax-check error so the caller knows.\n *\n * - If the file existed pre-write: restore the previous bytes with\n * the original encoding.\n * - If the file is brand-new: unlink it.\n */\nasync function revertStrictWrite(\n fs: import('./workspaceFS').WorkspaceFS,\n path: string,\n existed: boolean,\n before: string,\n encoding: { text: string; hasBom: boolean; newline: '\\n' | '\\r\\n' }\n): Promise<void> {\n try {\n if (existed) {\n // encodeFile uses encoding.{hasBom,newline} to restore the\n // on-disk shape; the `text` field is overridden by the\n // explicit `before` arg we pass in.\n await fs.writeFile(\n path,\n encodeFile(before, { ...encoding, text: before }),\n 'utf8'\n );\n } else {\n await fs.unlink(path);\n }\n } catch (error) {\n // A timed-out revert leaves the rejected write on disk — the caller would\n // otherwise claim \"reverted to pre-write state\" while the bad bytes remain.\n // Surface it; for other failures stay best-effort (caller sees the original\n // syntax error).\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n }\n}\n\nfunction summariseDiff(\n filePath: string,\n before: string,\n after: string\n): string {\n if (before === after) {\n return '(no textual changes)';\n }\n const name = basename(filePath);\n const patch = createTwoFilesPatch(name, name, before, after, '', '', {\n context: 3,\n });\n if (patch.length <= MAX_DIFF_CHARS) {\n return patch;\n }\n return (\n patch.slice(0, MAX_DIFF_CHARS) +\n `\\n[... diff truncated, ${patch.length - MAX_DIFF_CHARS} more chars ...]`\n );\n}\n\nfunction normalizeEdits(input: {\n old_text?: string;\n new_text?: string;\n edits?: Array<{ old_text?: string; new_text?: string }>;\n}): Array<{ oldText: string; newText: string }> {\n const edits = Array.isArray(input.edits)\n ? input.edits.map((edit) => ({\n oldText: edit.old_text ?? '',\n newText: edit.new_text ?? '',\n }))\n : [];\n\n if (input.old_text != null || input.new_text != null) {\n edits.push({\n oldText: input.old_text ?? '',\n newText: input.new_text ?? '',\n });\n }\n\n return edits;\n}\n\nfunction toolDefinition(\n name: string,\n description: string,\n parameters: t.JsonSchemaType\n): t.LCTool {\n return {\n name,\n description,\n parameters,\n allowed_callers: ['direct', 'code_execution'],\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n toolType: 'builtin',\n };\n}\n\nasync function looksBinary(\n path: string,\n fs: import('./workspaceFS').WorkspaceFS\n): Promise<boolean> {\n let handle;\n try {\n handle = await fs.open(path, 'r');\n const sample = Buffer.alloc(BINARY_DETECTION_BYTES);\n const { bytesRead } = await handle.read(\n sample,\n 0,\n BINARY_DETECTION_BYTES,\n 0\n );\n for (let i = 0; i < bytesRead; i++) {\n if (sample[i] === 0) {\n return true;\n }\n }\n return false;\n } finally {\n await handle?.close();\n }\n}\n\nconst DEFAULT_MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024;\n\nexport function createLocalReadFileTool(\n config: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n const fs = getWorkspaceFS(config);\n return tool(\n async (rawInput) => {\n const input = rawInput as {\n path: string;\n offset?: number;\n limit?: number;\n };\n const path = await resolveWorkspacePathSafe(\n input.path,\n config,\n 'read'\n );\n const fileStat = await fs.stat(path);\n if (!fileStat.isFile()) {\n throw new Error(`Path is not a file: ${input.path}`);\n }\n const maxBytes = Math.max(\n config.maxReadBytes ?? DEFAULT_MAX_READ_BYTES,\n 1\n );\n if (fileStat.size > maxBytes) {\n const stub = `File is ${fileStat.size} bytes, exceeds the ${maxBytes}-byte read cap. Read a slice via bash (e.g. head/sed) or raise local.maxReadBytes.`;\n return [stub, { path, bytes: fileStat.size, truncated: true }];\n }\n\n if (await looksBinary(path, fs)) {\n const attachmentMode = config.attachReadAttachments ?? 'off';\n if (attachmentMode !== 'off') {\n const attachment = await classifyAttachment({\n path,\n bytes: fileStat.size,\n mode: attachmentMode,\n maxBytes: config.maxAttachmentBytes ?? DEFAULT_MAX_ATTACHMENT_BYTES,\n // Route through the configured WorkspaceFS so a custom\n // engine sees the same path semantics as `read_file`\n // itself (manual review finding F).\n fs,\n });\n if (attachment.kind === 'image') {\n return [\n imageAttachmentContent(path, attachment),\n {\n path,\n bytes: fileStat.size,\n mime: attachment.mime,\n attachment: 'image',\n },\n ];\n }\n if (attachment.kind === 'pdf') {\n return [\n [\n {\n type: 'text',\n text: `Read ${path} (application/pdf, ${fileStat.size} bytes). PDF attached as base64 data URL; vision-capable models that accept PDF will render it.`,\n },\n {\n type: 'image_url',\n image_url: { url: attachment.dataUrl },\n },\n ],\n {\n path,\n bytes: fileStat.size,\n mime: attachment.mime,\n attachment: 'pdf',\n },\n ];\n }\n if (attachment.kind === 'oversize') {\n return [\n `Refusing to embed ${attachment.mime} attachment (${attachment.bytes} bytes exceeds ${attachment.maxBytes}-byte cap).`,\n {\n path,\n bytes: fileStat.size,\n mime: attachment.mime,\n attachment: 'oversize',\n },\n ];\n }\n if (attachment.kind === 'binary') {\n return [\n `Refusing to read binary file (${fileStat.size} bytes, ${attachment.mime}): ${path}`,\n {\n path,\n bytes: fileStat.size,\n mime: attachment.mime,\n binary: true,\n },\n ];\n }\n // text-or-unknown falls through to the text-read path below.\n } else {\n return [\n `Refusing to read binary file (${fileStat.size} bytes): ${path}`,\n { path, bytes: fileStat.size, binary: true },\n ];\n }\n }\n\n const content = await fs.readFile(path, 'utf8');\n const result = lineWindow(content, input.offset, input.limit);\n return [\n result.truncated ? `${result.text}\\n[truncated]` : result.text,\n { path, bytes: fileStat.size },\n ];\n },\n {\n name: Constants.READ_FILE,\n description:\n 'Read a local text file from the configured working directory with line numbers. ' +\n 'When `attachReadAttachments` is enabled (e.g. images-only), reading an image returns an ' +\n '`image_url` content block so vision-capable models can see the file directly.',\n schema: LocalReadFileToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createLocalWriteFileTool(\n config: t.LocalExecutionConfig = {},\n checkpointer?: t.LocalFileCheckpointer\n): DynamicStructuredTool {\n const fs = getWorkspaceFS(config);\n return tool(\n async (rawInput) => {\n const input = rawInput as { path: string; content: string };\n if (config.readOnly === true) {\n throw new Error('write_file is blocked in read-only local mode.');\n }\n const path = await resolveWorkspacePathSafe(\n input.path,\n config,\n 'write'\n );\n if (checkpointer != null) {\n await checkpointer.captureBeforeWrite(path);\n }\n\n let before = '';\n let encoding = { text: '', hasBom: false, newline: '\\n' as const } as\n | ReturnType<typeof decodeFile>\n | { text: string; hasBom: false; newline: '\\n' };\n let existed = false;\n try {\n const raw = await fs.readFile(path, 'utf8');\n const decoded = decodeFile(raw);\n before = decoded.text;\n encoding = decoded;\n existed = true;\n } catch (error) {\n // A stalled-RPC timeout is NOT \"file absent\" — treating it as such would\n // overwrite an existing file with fresh content. Surface it instead.\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n existed = false;\n }\n\n await fs.mkdir(dirname(path), { recursive: true });\n const finalText = encodeFile(input.content, encoding);\n await fs.writeFile(path, finalText, 'utf8');\n\n let syntax;\n try {\n syntax = await maybeRunSyntaxCheck(path, config);\n } catch (error) {\n // A validation-read timeout must still honor strict mode's revert\n // contract: restore the pre-write state before surfacing (best-effort —\n // the revert may itself time out on the same stalled container).\n if (\n isWorkspaceClientTimeoutError(error) &&\n config.postEditSyntaxCheck === 'strict'\n ) {\n await revertStrictWrite(fs, path, existed, before, encoding);\n }\n throw error;\n }\n\n const diff = existed\n ? summariseDiff(path, before, input.content)\n : `(new file, ${input.content.length} chars)`;\n const baseSummary = existed\n ? `Overwrote ${path} (${input.content.length} chars). Diff:\\n${diff}`\n : `Created ${path} (${input.content.length} chars).`;\n const summary = appendSyntaxCheckSummary(baseSummary, syntax);\n if (syntax?.outcome.ok === false && syntax.mode === 'strict') {\n // Roll back the write so strict mode is an actual gate, not\n // \"fail the call AND leave the corrupted file on disk\".\n // Codex P2 [49].\n await revertStrictWrite(fs, path, existed, before, encoding);\n throw new Error(\n `write_file syntax check failed (${syntax.outcome.checker}); reverted to pre-write state.\\n${syntax.outcome.output}`\n );\n }\n return [\n summary,\n {\n path,\n bytes: finalText.length,\n new_file: !existed,\n newline: encoding.newline === '\\r\\n' ? 'CRLF' : 'LF',\n had_bom: encoding.hasBom,\n ...(syntax != null && syntax.outcome.ok === false\n ? { syntax_error: syntax.outcome.checker }\n : {}),\n },\n ];\n },\n {\n name: LocalWriteFileToolName,\n description:\n 'Create or overwrite a local text file in the configured working directory. ' +\n 'Preserves the existing BOM and line endings when overwriting; defaults to LF without BOM for new files. ' +\n 'Returns a unified diff of the changes when overwriting.',\n schema: LocalWriteFileToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createLocalEditFileTool(\n config: t.LocalExecutionConfig = {},\n checkpointer?: t.LocalFileCheckpointer\n): DynamicStructuredTool {\n const fs = getWorkspaceFS(config);\n return tool(\n async (rawInput) => {\n const input = rawInput as {\n path: string;\n old_text?: string;\n new_text?: string;\n edits?: Array<{ old_text?: string; new_text?: string }>;\n };\n if (config.readOnly === true) {\n throw new Error('edit_file is blocked in read-only local mode.');\n }\n const edits = normalizeEdits(input);\n if (edits.length === 0) {\n throw new Error('edit_file requires old_text/new_text or edits[].');\n }\n\n const path = await resolveWorkspacePathSafe(\n input.path,\n config,\n 'write'\n );\n const raw = await fs.readFile(path, 'utf8');\n const encoding = decodeFile(raw);\n const original = encoding.text;\n\n let next = original;\n const strategiesUsed: string[] = [];\n for (let i = 0; i < edits.length; i++) {\n const edit = edits[i];\n const match = locateEdit(next, edit.oldText);\n if (match == null) {\n throw new Error(\n `Edit ${i + 1}/${edits.length}: could not locate old_text in ${input.path}. ` +\n 'Tried exact, line-trimmed, whitespace-normalized, and indentation-flexible matching. ' +\n 'Re-read the file and copy the literal lines.'\n );\n }\n strategiesUsed.push(match.strategy);\n next = applyEdit(next, match, edit.newText);\n }\n\n if (checkpointer != null) {\n await checkpointer.captureBeforeWrite(path);\n }\n const finalText = encodeFile(next, encoding);\n await fs.writeFile(path, finalText, 'utf8');\n\n let syntax;\n try {\n syntax = await maybeRunSyntaxCheck(path, config);\n } catch (error) {\n // As in write_file: a validation-read timeout still triggers strict\n // mode's revert (edit_file always operates on an existing file).\n if (\n isWorkspaceClientTimeoutError(error) &&\n config.postEditSyntaxCheck === 'strict'\n ) {\n await revertStrictWrite(fs, path, true, original, encoding);\n }\n throw error;\n }\n\n const diff = summariseDiff(path, original, next);\n const fuzzy = strategiesUsed.some((s) => s !== 'exact');\n const baseSummary =\n `Applied ${edits.length} edit(s) to ${path}` +\n (fuzzy ? ` (strategies: ${strategiesUsed.join(', ')})` : '') +\n `. Diff:\\n${diff}`;\n const summary = appendSyntaxCheckSummary(baseSummary, syntax);\n if (syntax?.outcome.ok === false && syntax.mode === 'strict') {\n // Restore the pre-edit bytes so strict mode is an actual\n // gate (Codex P2 [49]). edit_file always operates on an\n // existing file, so `existed = true` here.\n await revertStrictWrite(fs, path, true, original, encoding);\n throw new Error(\n `edit_file syntax check failed (${syntax.outcome.checker}); reverted to pre-edit state.\\n${syntax.outcome.output}`\n );\n }\n return [\n summary,\n {\n path,\n edits: edits.length,\n strategies: strategiesUsed,\n newline: encoding.newline === '\\r\\n' ? 'CRLF' : 'LF',\n had_bom: encoding.hasBom,\n ...(syntax != null && syntax.outcome.ok === false\n ? { syntax_error: syntax.outcome.checker }\n : {}),\n },\n ];\n },\n {\n name: LocalEditFileToolName,\n description:\n 'Apply exact text replacements to a local file. The matcher tries exact, line-trimmed, whitespace-normalized, and indentation-flexible strategies in order so common LLM whitespace mistakes are recoverable. Each old_text must still match exactly one location. Returns a unified diff of the changes.',\n schema: LocalEditFileToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\n/**\n * Ripgrep availability cache, keyed on the *effective execution\n * backend* — whatever function `getSpawn(config)` returns. Without\n * the backend key, a Run that probes `rg` over Node's\n * `child_process.spawn` would poison subsequent Runs whose\n * `local.exec.spawn` routes to a remote sandbox or container that\n * doesn't have rg installed: the cached `true` would skip the probe,\n * the rg invocation would throw, and the Node fallback wouldn't be\n * reached. Per-backend caching avoids that without paying for a\n * spawn-per-search.\n */\n// Per-backend × per-env cache. Codex P1 #34 — keying by spawn\n// backend alone misses the case where two Runs share a backend but\n// vary `local.env` (especially PATH). Stale cache then claims `rg`\n// is available, the rg path runs, and the spawn fails with ENOENT\n// instead of falling back to the Node walker. The inner Map is\n// keyed by a stable JSON hash of the effective env so each unique\n// env gets its own probe.\nlet ripgrepAvailabilityByBackend = new WeakMap<\n t.LocalSpawn,\n Map<string, Promise<boolean>>\n>();\n\nfunction envCacheKey(env: NodeJS.ProcessEnv | undefined): string {\n // PATH is the only env entry that affects command lookup, but\n // hashing the whole env keeps the key correct for hosts that\n // vary anything else relevant. Stable JSON via sorted keys so\n // {A:1,B:2} and {B:2,A:1} produce the same hash.\n if (env == null) return '';\n const sorted: Record<string, string | undefined> = {};\n for (const k of Object.keys(env).sort()) {\n sorted[k] = env[k];\n }\n return JSON.stringify(sorted);\n}\n\nasync function isRipgrepAvailable(\n config: t.LocalExecutionConfig\n): Promise<boolean> {\n const backend = getSpawn(config);\n let envMap = ripgrepAvailabilityByBackend.get(backend);\n if (envMap == null) {\n envMap = new Map();\n ripgrepAvailabilityByBackend.set(backend, envMap);\n }\n const envKey = envCacheKey(config.env);\n let probePromise = envMap.get(envKey);\n if (probePromise == null) {\n probePromise = spawnLocalProcess(\n 'rg',\n ['--version'],\n { ...config, timeoutMs: 5000, sandbox: { enabled: false } },\n { internal: true }\n )\n .then((probe) => probe.exitCode === 0)\n .catch(() => false);\n envMap.set(envKey, probePromise);\n }\n return probePromise;\n}\n\n/**\n * Test-only reset hook. Clears the ripgrep-availability cache so\n * tests can swap in mocked spawn backends and reprobe deterministically.\n *\n * @internal Not part of the public SDK surface; the leading underscore\n * and `@internal` tag together signal that consumers should not call\n * this. Tests import it via the module path directly.\n */\nexport function _resetRipgrepCacheForTests(): void {\n ripgrepAvailabilityByBackend = new WeakMap();\n}\n\n// Skipped by the Node-fallback walker (used when ripgrep is\n// unavailable). Covers common build outputs, virtualenvs, and\n// caches so a `grep_search`/`glob_search` on a large monorepo or a\n// Python project with `.venv/` doesn't read every file under those\n// trees. ripgrep itself respects .gitignore so it doesn't need this\n// list. Audit follow-up from the comprehensive review (finding #3).\nconst SKIP_DIRS = new Set([\n '.git',\n '.svn',\n '.hg',\n 'node_modules',\n '.next',\n '.nuxt',\n '.cache',\n '.parcel-cache',\n '.turbo',\n 'dist',\n 'build',\n 'out',\n 'target',\n 'vendor',\n 'coverage',\n '.nyc_output',\n '__pycache__',\n '.venv',\n 'venv',\n 'env',\n '.tox',\n '.mypy_cache',\n '.pytest_cache',\n '.ruff_cache',\n]);\n\nfunction globToRegExp(pattern: string): RegExp {\n let result = '^';\n for (let i = 0; i < pattern.length; i++) {\n const c = pattern[i];\n if (c === '*') {\n if (pattern[i + 1] === '*') {\n result += '.*';\n i += 1;\n if (pattern[i + 1] === '/') {\n i += 1;\n }\n } else {\n result += '[^/]*';\n }\n } else if (c === '?') {\n result += '[^/]';\n } else if ('.+^$|(){}[]\\\\'.includes(c)) {\n result += '\\\\' + c;\n } else {\n result += c;\n }\n }\n result += '$';\n return new RegExp(result);\n}\n\nasync function* walkFiles(\n root: string,\n fs: import('./workspaceFS').WorkspaceFS\n): AsyncGenerator<string> {\n const stack: string[] = [root];\n while (stack.length > 0) {\n const dir = stack.pop() as string;\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch (error) {\n // A stalled-RPC timeout must surface, not be silently skipped as an\n // unreadable directory — that would corrupt search results (\"no matches\").\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n continue;\n }\n for (const entry of entries) {\n if (entry.name.startsWith('.git') || SKIP_DIRS.has(entry.name)) {\n continue;\n }\n const full = `${dir}/${entry.name}`;\n if (entry.isDirectory()) {\n stack.push(full);\n } else if (entry.isFile()) {\n yield full;\n }\n }\n }\n}\n\n/**\n * Catastrophic-backtracking guardrails for the fallback grep path.\n *\n * Without ripgrep we run the model-supplied pattern through Node's\n * `RegExp` engine, which uses a backtracking implementation. Patterns\n * with nested unbounded quantifiers (`(a+)+`, `(.*)*`, etc.) can\n * monopolise the event loop for arbitrary wall-clock time on\n * pathological input, and `setTimeout` cannot interrupt a synchronous\n * `RegExp.exec`. Manual review (finding D) flagged this as a real DoS.\n *\n * Mitigations applied here, in order of severity:\n * 1. Cap pattern length so an obviously oversize regex is rejected\n * before compile.\n * 2. Reject patterns that contain a nested unbounded quantifier of\n * the form `(...+|*)([+*]|{n,})` — the standard pathological\n * shape. Still a heuristic (not a full safety proof), but blocks\n * every common DoS construction we've seen in coding-agent logs.\n * 3. Wall-clock budget for the overall search: each file's regex\n * pass is checked against a deadline; once exceeded the search\n * bails with a partial result. Doesn't interrupt a stuck\n * `exec()` call, but stops a slow pattern from making the whole\n * Run hang once the first hung file finishes.\n *\n * Hosts that need bulletproof regex safety should install `rg` —\n * ripgrep uses RE2 internally and has no backtracking.\n */\nconst MAX_FALLBACK_PATTERN_LENGTH = 1024;\nconst FALLBACK_GREP_BUDGET_MS = 5000;\n// Per-file byte cap. Codex P2 #41 — without it, the whole-file\n// `readFile` + `split('\\n')` for a multi-GB log is an unbounded\n// allocation that the wall-clock budget (checked between files)\n// can't interrupt. Hosts that need to grep large files should\n// install ripgrep.\nconst FALLBACK_GREP_MAX_FILE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Heuristic: walks `pattern` to find any `(<contents>)<quant>` where\n * `<contents>` itself has an unbounded quantifier. Catches the\n * classic `(a+)+` form AND the double-nested `((a+)+)` form (which a\n * single-pass regex misses because `[^)]*` stops at the first inner\n * close-paren). Misses sufficiently obfuscated cases — bulletproof\n * ReDoS detection requires a real parser. The 5 s wall-clock budget\n * is the hard backstop for anything this slip past.\n */\nfunction hasNestedUnboundedQuantifier(pattern: string): boolean {\n for (let i = 1; i < pattern.length - 1; i++) {\n if (pattern[i] !== ')') continue;\n if (pattern[i - 1] === '\\\\') continue;\n const next = pattern[i + 1];\n if (next !== '+' && next !== '*' && next !== '{') continue;\n // Walk back to find the matching opening paren (respecting depth\n // and `\\(` escapes).\n let depth = 1;\n let j = i - 1;\n while (j >= 0) {\n const c = pattern[j];\n const escaped = j > 0 && pattern[j - 1] === '\\\\';\n if (!escaped) {\n if (c === ')') depth++;\n else if (c === '(') {\n depth--;\n if (depth === 0) break;\n }\n }\n j--;\n }\n if (j < 0) continue;\n const inner = pattern.slice(j + 1, i);\n if (/(?<!\\\\)[+*]/.test(inner)) return true;\n }\n return false;\n}\n\nclass FallbackGrepError extends Error {\n readonly kind: 'pattern-too-long' | 'unsafe-pattern' | 'invalid-pattern';\n constructor(\n kind: 'pattern-too-long' | 'unsafe-pattern' | 'invalid-pattern',\n message: string\n ) {\n super(message);\n this.kind = kind;\n }\n}\n\nfunction compileFallbackRegex(pattern: string): RegExp {\n if (pattern.length > MAX_FALLBACK_PATTERN_LENGTH) {\n throw new FallbackGrepError(\n 'pattern-too-long',\n `Pattern exceeds ${MAX_FALLBACK_PATTERN_LENGTH}-char fallback cap (install ripgrep for unbounded patterns).`\n );\n }\n if (hasNestedUnboundedQuantifier(pattern)) {\n throw new FallbackGrepError(\n 'unsafe-pattern',\n 'Pattern contains a nested unbounded quantifier (e.g. `(a+)+` or `((a+)+)`) which can cause catastrophic backtracking in the Node fallback. Install ripgrep for RE2-safe matching.'\n );\n }\n try {\n return new RegExp(pattern);\n } catch (e) {\n throw new FallbackGrepError(\n 'invalid-pattern',\n `Invalid regex: ${(e as Error).message}`\n );\n }\n}\n\n/** Structured return so callers can count matches separately from\n * diagnostic skip-sentinels (Codex P2 [43]). */\ntype FallbackGrepResult = { matches: string[]; skipped: string[] };\n\n/** Renders fallback-grep output: real matches first, skip diagnostics appended. */\nfunction formatFallbackGrepDisplay(result: FallbackGrepResult): string {\n if (result.matches.length > 0) {\n return [...result.matches, ...result.skipped].join('\\n');\n }\n if (result.skipped.length > 0) {\n return result.skipped.join('\\n');\n }\n return 'No matches found.';\n}\n\nasync function fallbackGrep(\n root: string,\n pattern: string,\n globFilter: string | undefined,\n maxResults: number,\n fs: import('./workspaceFS').WorkspaceFS\n): Promise<FallbackGrepResult> {\n const rx = compileFallbackRegex(pattern);\n const deadline = Date.now() + FALLBACK_GREP_BUDGET_MS;\n const globRx =\n globFilter != null && globFilter !== ''\n ? globToRegExp(globFilter)\n : undefined;\n const matches: string[] = [];\n // Track skipped (oversize) files separately so they don't consume\n // the maxResults budget. Codex P2 [43]: round 14's fix pushed skip\n // sentinels into `matches`, so a directory of one oversize non-\n // matching file falsely reported `matches: 1`, and enough\n // oversize files could fill the budget before any real match was\n // scanned. Now diagnostics are appended after real matches and\n // independent of the budget.\n const skippedDiagnostics: string[] = [];\n for await (const file of walkFiles(root, fs)) {\n if (Date.now() > deadline) {\n // Wall-clock budget exceeded — return partial results rather\n // than letting a slow pattern hang the Run.\n return { matches, skipped: skippedDiagnostics };\n }\n if (globRx != null) {\n const rel = file.startsWith(root + '/')\n ? file.slice(root.length + 1)\n : file;\n if (!globRx.test(rel)) {\n continue;\n }\n }\n // Skip files larger than the per-file cap and remember them as\n // diagnostics (NOT as matches). Codex P2 [41]: pre-fix\n // `fs.readFile` then `.split('\\n')` allocated the whole file +\n // an array of every line, which a single multi-GB log could\n // turn into an OOM even after the regex DoS guards.\n let stat;\n try {\n stat = await fs.stat(file);\n } catch (error) {\n // A stalled-RPC timeout must surface, not be skipped — skipping a file can\n // report \"no matches\" even when the (unreadable-due-to-stall) file matched.\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n continue;\n }\n if (stat.size > FALLBACK_GREP_MAX_FILE_BYTES) {\n skippedDiagnostics.push(\n `${file}:0:[skipped: file > ${FALLBACK_GREP_MAX_FILE_BYTES} bytes; install ripgrep for unbounded grep]`\n );\n continue;\n }\n let content;\n try {\n content = await fs.readFile(file, 'utf8');\n } catch (error) {\n // As above: a client-timeout means a stalled read, not an unreadable file.\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n continue;\n }\n if (content.includes('\\0')) {\n continue;\n }\n // Re-check the deadline AFTER the read — a slow disk on one\n // file can blow the budget without us noticing.\n if (Date.now() > deadline) {\n return { matches, skipped: skippedDiagnostics };\n }\n const lines = content.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n if (rx.test(lines[i])) {\n matches.push(`${file}:${i + 1}:${lines[i]}`);\n if (matches.length >= maxResults) {\n return { matches, skipped: skippedDiagnostics };\n }\n }\n }\n }\n return { matches, skipped: skippedDiagnostics };\n}\n\nasync function fallbackGlob(\n root: string,\n pattern: string,\n maxResults: number,\n fs: import('./workspaceFS').WorkspaceFS\n): Promise<string[]> {\n const rx = globToRegExp(pattern);\n const out: string[] = [];\n for await (const file of walkFiles(root, fs)) {\n const rel = file.startsWith(root + '/')\n ? file.slice(root.length + 1)\n : file;\n if (rx.test(rel)) {\n out.push(file);\n if (out.length >= maxResults) {\n break;\n }\n }\n }\n return out;\n}\n\nexport function createLocalGrepSearchTool(\n config: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n const fs = getWorkspaceFS(config);\n return tool(\n async (rawInput) => {\n const input = rawInput as {\n pattern: string;\n path?: string;\n glob?: string;\n max_results?: number;\n };\n const target = await resolveWorkspacePathSafe(\n input.path ?? '.',\n config,\n 'read'\n );\n const maxResults = Math.max(input.max_results ?? DEFAULT_MAX_RESULTS, 1);\n\n if (await isRipgrepAvailable(config)) {\n // Pass the pattern through `-e` so dash-prefixed patterns\n // like `-foo` are treated as the search regex, not as a\n // (probably-unknown) flag. `rg --help` explicitly requires\n // `-e/--regexp` (or `--`) for that case. Same trick avoids\n // any future flag-conflict if a user query happens to look\n // like an rg long option.\n const args = [\n '--line-number',\n '--column',\n '--hidden',\n '--glob',\n '!.git/**',\n ...(input.glob != null && input.glob !== ''\n ? ['--glob', input.glob]\n : []),\n '-e',\n input.pattern,\n target,\n ];\n const result = await spawnLocalProcess('rg', args, {\n ...config,\n timeoutMs: config.timeoutMs ?? 30000,\n });\n // ripgrep exit codes:\n // 0 → at least one match\n // 1 → no matches (clean — \"No matches found.\")\n // 2 → real error (bad regex, unreadable target, etc.)\n // Without this branch (Codex P2 #23 — same fix shape glob_search\n // got from P2 #13), exit-2 errors silently mapped to\n // `matches: 0`, so the agent treated tooling failures as a\n // genuine absence of matches.\n if (\n result.timedOut ||\n (result.exitCode != null && result.exitCode > 1)\n ) {\n const detail = result.stderr.trim() || `rg exited ${result.exitCode}`;\n return [\n `grep_search failed: ${detail}`,\n {\n matches: 0,\n engine: 'ripgrep',\n error: detail,\n exitCode: result.exitCode,\n },\n ];\n }\n const lines = result.stdout\n .split('\\n')\n .filter(Boolean)\n .slice(0, maxResults);\n const output =\n lines.length > 0\n ? lines.join('\\n')\n : result.stderr.trim() || 'No matches found.';\n return [output, { matches: lines.length, engine: 'ripgrep' }];\n }\n\n try {\n const { matches, skipped } = await fallbackGrep(\n target,\n input.pattern,\n input.glob,\n maxResults,\n fs\n );\n // Artifact count: ONLY real matches (Codex P2 [43] —\n // skip sentinels used to inflate the count and the budget).\n const display = formatFallbackGrepDisplay({ matches, skipped });\n return [\n display,\n {\n matches: matches.length,\n skipped: skipped.length,\n engine: 'node-fallback',\n },\n ];\n } catch (e) {\n if (e instanceof FallbackGrepError) {\n return [\n `grep_search refused the pattern: ${e.message}`,\n {\n matches: 0,\n engine: 'node-fallback',\n error: e.message,\n kind: e.kind,\n },\n ];\n }\n throw e;\n }\n },\n {\n name: LocalGrepSearchToolName,\n description:\n 'Search local files for a regex pattern (ripgrep when available, Node fallback otherwise).',\n schema: LocalGrepSearchToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createLocalGlobSearchTool(\n config: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n const fs = getWorkspaceFS(config);\n return tool(\n async (rawInput) => {\n const input = rawInput as {\n pattern: string;\n path?: string;\n max_results?: number;\n };\n const target = await resolveWorkspacePathSafe(\n input.path ?? '.',\n config,\n 'read'\n );\n const maxResults = Math.max(input.max_results ?? DEFAULT_MAX_RESULTS, 1);\n\n if (await isRipgrepAvailable(config)) {\n const result = await spawnLocalProcess(\n 'rg',\n [\n '--files',\n '--hidden',\n '--glob',\n '!.git/**',\n '--glob',\n input.pattern,\n target,\n ],\n { ...config, timeoutMs: config.timeoutMs ?? 30000 }\n );\n // rg --files exit codes:\n // 0 → at least one file matched\n // 1 → no files matched (clean — \"No files found.\")\n // 2 → real error (bad glob, unreadable target, etc.)\n // Without this branch, exit-2 errors used to silently map to\n // \"No files found.\" — the agent then treats a tooling failure\n // as a real absence of matches.\n if (\n result.timedOut ||\n (result.exitCode != null && result.exitCode > 1)\n ) {\n const detail = result.stderr.trim() || `rg exited ${result.exitCode}`;\n return [\n `glob_search failed: ${detail}`,\n {\n files: [],\n engine: 'ripgrep',\n error: detail,\n exitCode: result.exitCode,\n },\n ];\n }\n const lines = result.stdout\n .split('\\n')\n .filter(Boolean)\n .slice(0, maxResults);\n return [\n lines.length > 0 ? lines.join('\\n') : 'No files found.',\n { files: lines, engine: 'ripgrep' },\n ];\n }\n\n const files = await fallbackGlob(target, input.pattern, maxResults, fs);\n return [\n files.length > 0 ? files.join('\\n') : 'No files found.',\n { files, engine: 'node-fallback' },\n ];\n },\n {\n name: LocalGlobSearchToolName,\n description:\n 'Find local files matching a glob pattern (ripgrep when available, Node fallback otherwise).',\n schema: LocalGlobSearchToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createLocalListDirectoryTool(\n config: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n const fs = getWorkspaceFS(config);\n return tool(\n async (rawInput) => {\n const input = rawInput as { path?: string };\n const path = await resolveWorkspacePathSafe(\n input.path ?? '.',\n config,\n 'read'\n );\n const entries = await fs.readdir(path, { withFileTypes: true });\n const output = entries\n .map(\n (entry) => `${entry.isDirectory() ? 'dir ' : 'file'}\\t${entry.name}`\n )\n .join('\\n');\n return [output || 'Directory is empty.', { path, count: entries.length }];\n },\n {\n name: LocalListDirectoryToolName,\n description: 'List files and directories in a local directory.',\n schema: LocalListDirectoryToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport type LocalCodingToolBundle = {\n tools: DynamicStructuredTool[];\n /**\n * Present when `config.fileCheckpointing === true` or a `checkpointer`\n * was passed in. Callers can call `rewind()` to restore captured\n * pre-write contents.\n */\n checkpointer?: t.LocalFileCheckpointer;\n};\n\nexport function createLocalCodingTools(\n config: t.LocalExecutionConfig = {},\n options: { checkpointer?: t.LocalFileCheckpointer } = {}\n): DynamicStructuredTool[] {\n const checkpointer =\n options.checkpointer ??\n (config.fileCheckpointing === true\n ? createLocalFileCheckpointer({ fs: config.exec?.fs })\n : undefined);\n return [\n createLocalReadFileTool(config),\n createLocalWriteFileTool(config, checkpointer),\n createLocalEditFileTool(config, checkpointer),\n createLocalGrepSearchTool(config),\n createLocalGlobSearchTool(config),\n createLocalListDirectoryTool(config),\n createCompileCheckTool(config),\n createLocalBashExecutionTool({ config }),\n createLocalCodeExecutionTool(config),\n createLocalProgrammaticToolCallingTool(config),\n createLocalBashProgrammaticToolCallingTool(config),\n ];\n}\n\n/**\n * Variant of `createLocalCodingTools` that returns the bundle alongside\n * the file checkpointer so callers can later call\n * `bundle.checkpointer?.rewind()`.\n */\nexport function createLocalCodingToolBundle(\n config: t.LocalExecutionConfig = {},\n options: { checkpointer?: t.LocalFileCheckpointer } = {}\n): LocalCodingToolBundle {\n const checkpointer =\n options.checkpointer ??\n (config.fileCheckpointing === true\n ? createLocalFileCheckpointer({ fs: config.exec?.fs })\n : undefined);\n return {\n tools: createLocalCodingTools(config, { checkpointer }),\n checkpointer,\n };\n}\n\nexport function createLocalCodingToolDefinitions(): t.LCTool[] {\n return [\n toolDefinition(\n Constants.READ_FILE,\n 'Read a local text file from the configured working directory with line numbers.',\n LocalReadFileToolSchema as t.JsonSchemaType\n ),\n toolDefinition(\n LocalWriteFileToolName,\n 'Create or overwrite a local text file in the configured working directory.',\n LocalWriteFileToolSchema as t.JsonSchemaType\n ),\n toolDefinition(\n LocalEditFileToolName,\n 'Apply exact text replacements to a local file.',\n LocalEditFileToolSchema as t.JsonSchemaType\n ),\n toolDefinition(\n LocalGrepSearchToolName,\n 'Search local files with ripgrep and return matching lines.',\n LocalGrepSearchToolSchema as t.JsonSchemaType\n ),\n toolDefinition(\n LocalGlobSearchToolName,\n 'Find local files matching a glob pattern.',\n LocalGlobSearchToolSchema as t.JsonSchemaType\n ),\n toolDefinition(\n LocalListDirectoryToolName,\n 'List files and directories in a local directory.',\n LocalListDirectoryToolSchema as t.JsonSchemaType\n ),\n createCompileCheckToolDefinition(),\n ];\n}\n\nexport function createLocalCodingToolRegistry(): t.LCToolRegistry {\n return new Map(\n createLocalCodingToolDefinitions().map((definition) => [\n definition.name,\n definition,\n ])\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,MAAM,iBAAiB;AACvB,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB,KAAK,OAAO;AAC3C,MAAM,yBAAyB;;;;;;;AAQ/B,MAAa,yBAAA;AACb,MAAa,wBAAA;AACb,MAAa,0BAAA;AACb,MAAa,0BAAA;AACb,MAAa,6BAAA;AA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,MAAM,GAAG,CAAC,IACnD,KAAA;CACN,OAAO;EACL,OAAO,uBAAuB,QAAQ,EAAE,aAAa,CAAC;EACtD;CACF;AACF;AAEA,SAAgB,mCAA+C;CAC7D,OAAO;EACL,eAAA,aAEE,mFACA,uBACF;EACA,eACE,wBACA,8EACA,wBACF;EACA,eACE,uBACA,kDACA,uBACF;EACA,eACE,yBACA,8DACA,yBACF;EACA,eACE,yBACA,6CACA,yBACF;EACA,eACE,4BACA,oDACA,4BACF;EACAM,yBAAAA,iCAAiC;CACnC;AACF;AAEA,SAAgB,gCAAkD;CAChE,OAAO,IAAI,IACT,iCAAiC,CAAC,CAAC,KAAK,eAAe,CACrD,WAAW,MACX,UACF,CAAC,CACH;AACF"}
@@ -1,11 +1,11 @@
1
- const require_bashAst = require("./bashAst.cjs");
2
1
  const require_workspaceFS = require("./workspaceFS.cjs");
2
+ const require_bashAst = require("./bashAst.cjs");
3
3
  let path = require("path");
4
+ let fs_promises = require("fs/promises");
4
5
  let os = require("os");
5
6
  let child_process = require("child_process");
6
7
  let fs = require("fs");
7
8
  let crypto = require("crypto");
8
- let fs_promises = require("fs/promises");
9
9
  //#region src/tools/local/LocalExecutionEngine.ts
10
10
  const DEFAULT_TIMEOUT_MS = 6e4;
11
11
  const DEFAULT_MAX_OUTPUT_CHARS = 2e5;
@@ -1,3 +1,4 @@
1
+ const require_workspaceFS = require("./workspaceFS.cjs");
1
2
  const require_LocalExecutionEngine = require("./LocalExecutionEngine.cjs");
2
3
  let path = require("path");
3
4
  //#region src/tools/local/syntaxCheck.ts
@@ -95,7 +96,9 @@ const pythonCheck = async (path$2, config) => {
95
96
  };
96
97
  };
97
98
  const jsonCheck = async (path$3, config) => {
98
- const raw = await require_LocalExecutionEngine.getWorkspaceFS(config).readFile(path$3, "utf8").catch(() => void 0);
99
+ const raw = await require_LocalExecutionEngine.getWorkspaceFS(config).readFile(path$3, "utf8").catch((error) => {
100
+ if (require_workspaceFS.isWorkspaceClientTimeoutError(error)) throw error;
101
+ });
99
102
  if (raw == null) return { ok: true };
100
103
  try {
101
104
  JSON.parse(raw);
@@ -152,7 +155,8 @@ async function runPostEditSyntaxCheck(absolutePath, config) {
152
155
  output: result.output.slice(0, 4096)
153
156
  };
154
157
  return result;
155
- } catch {
158
+ } catch (error) {
159
+ if (require_workspaceFS.isWorkspaceClientTimeoutError(error)) throw error;
156
160
  return null;
157
161
  }
158
162
  }
@@ -1 +1 @@
1
- {"version":3,"file":"syntaxCheck.cjs","names":["getSpawn","spawnLocalProcess","path","getWorkspaceFS"],"sources":["../../../../src/tools/local/syntaxCheck.ts"],"sourcesContent":["/**\n * Per-file syntax check used by `edit_file` / `write_file` to surface\n * obvious errors immediately after the write — strictly cheaper than\n * full LSP integration and catches the bulk of \"you broke the file\"\n * regressions a vision-less agent loop would otherwise miss until\n * the next call.\n *\n * Each checker is a tiny shell-out (or in-process function) keyed on\n * file extension. Failures are returned as a single short message;\n * the wiring layer decides whether to append it to the tool result\n * advisorily (`auto`) or to throw and force the model to react\n * (`strict`).\n *\n * We deliberately do NOT cover TypeScript here because per-file `tsc`\n * is slow and per-file syntax (without type info) misses most TS\n * errors anyway. Use the project-level `compile_check` tool for that.\n */\n\nimport { extname } from 'path';\nimport type * as t from '@/types';\nimport {\n getSpawn,\n getWorkspaceFS,\n spawnLocalProcess,\n} from './LocalExecutionEngine';\n\nexport type SyntaxCheckOutcome =\n | { ok: true }\n | { ok: false; checker: string; output: string };\n\nexport type SyntaxChecker = (\n path: string,\n config: t.LocalExecutionConfig\n) => Promise<SyntaxCheckOutcome>;\n\n/**\n * Per-backend availability cache for the post-edit syntax-check probe\n * tools (node, python3, bash). Keyed on the *effective spawn backend*\n * — see `getSpawn(config)` in LocalExecutionEngine — so a Run that\n * probes node over Node's child_process can't poison a subsequent Run\n * whose `local.exec.spawn` routes elsewhere (a remote sandbox might\n * have python but not node, etc.).\n *\n * Mirrors the same fix that landed for the ripgrep cache in\n * `LocalCodingTools.ts` after the first round of Codex review.\n * WeakMap keying lets disposed backends GC their entry; the test\n * reset hook re-creates the map.\n */\ntype ProbeKind = 'hasNode' | 'hasPython' | 'hasBash';\ntype ProbeCache = Partial<Record<ProbeKind, Promise<boolean>>>;\n\n// Per-backend × per-env cache. Codex P2 #40 — keying by spawn\n// backend alone misses env-driven availability changes (e.g. PATH\n// loses node between Runs that share the same backend). Same fix\n// shape as the ripgrep cache (Codex P1 #34).\nlet probeCacheByBackend = new WeakMap<\n t.LocalSpawn,\n Map<string, ProbeCache>\n>();\n\nfunction envCacheKey(env: NodeJS.ProcessEnv | undefined): string {\n if (env == null) return '';\n const sorted: Record<string, string | undefined> = {};\n for (const k of Object.keys(env).sort()) {\n sorted[k] = env[k];\n }\n return JSON.stringify(sorted);\n}\n\nfunction cacheFor(\n config: t.LocalExecutionConfig\n): ProbeCache {\n const backend = getSpawn(config);\n let envMap = probeCacheByBackend.get(backend);\n if (envMap == null) {\n envMap = new Map();\n probeCacheByBackend.set(backend, envMap);\n }\n const envKey = envCacheKey(config.env);\n let entry = envMap.get(envKey);\n if (entry == null) {\n entry = {};\n envMap.set(envKey, entry);\n }\n return entry;\n}\n\nasync function probe(\n command: string,\n args: string[],\n cached: ProbeKind,\n config: t.LocalExecutionConfig\n): Promise<boolean> {\n const entry = cacheFor(config);\n let probePromise = entry[cached];\n if (probePromise == null) {\n probePromise = spawnLocalProcess(\n command,\n args,\n { ...config, timeoutMs: 5000, sandbox: { enabled: false } },\n { internal: true }\n )\n .then((result) => result != null && result.exitCode === 0)\n .catch(() => false);\n entry[cached] = probePromise;\n }\n return probePromise;\n}\n\n/**\n * Test-only reset hook. Clears the per-backend probe cache so tests\n * can swap in mocked spawn backends and reprobe deterministically.\n *\n * @internal Not part of the public SDK surface.\n */\nexport function _resetSyntaxCheckProbeCacheForTests(): void {\n probeCacheByBackend = new WeakMap();\n}\n\nconst jsCheck: SyntaxChecker = async (path, config) => {\n if (!(await probe('node', ['--version'], 'hasNode', config))) {\n return { ok: true };\n }\n const result = await spawnLocalProcess(\n 'node',\n ['--check', path],\n { ...config, timeoutMs: 5000, sandbox: { enabled: false } },\n { internal: true }\n );\n if (result.exitCode === 0) return { ok: true };\n return {\n ok: false,\n checker: 'node --check',\n output: result.stderr.trim() || result.stdout.trim() || 'syntax error',\n };\n};\n\nconst pythonCheck: SyntaxChecker = async (path, config) => {\n if (!(await probe('python3', ['--version'], 'hasPython', config))) {\n return { ok: true };\n }\n const program =\n 'import py_compile, sys\\n' +\n 'try:\\n' +\n ' py_compile.compile(sys.argv[1], doraise=True)\\n' +\n 'except py_compile.PyCompileError as e:\\n' +\n ' print(e.msg.strip(), file=sys.stderr)\\n' +\n ' sys.exit(1)\\n';\n const result = await spawnLocalProcess(\n 'python3',\n ['-c', program, path],\n { ...config, timeoutMs: 5000, sandbox: { enabled: false } },\n { internal: true }\n );\n if (result.exitCode === 0) return { ok: true };\n return {\n ok: false,\n checker: 'py_compile',\n output: result.stderr.trim() || result.stdout.trim() || 'syntax error',\n };\n};\n\nconst jsonCheck: SyntaxChecker = async (path, config) => {\n // Route through the configured WorkspaceFS so a Run with a custom\n // `local.exec.fs` (in-memory or remote engine) validates the same\n // file the write_file/edit_file path actually wrote — pre-fix this\n // read went to the host fs and either silently passed (no host\n // file → catch returns undefined → ok: true) or read a different\n // file with the same absolute path. Codex P1 #24.\n const fs = getWorkspaceFS(config);\n const raw = await fs.readFile(path, 'utf8').catch(() => undefined);\n if (raw == null) return { ok: true };\n try {\n JSON.parse(raw);\n return { ok: true };\n } catch (err) {\n return {\n ok: false,\n checker: 'JSON.parse',\n output: (err as Error).message,\n };\n }\n};\n\nconst bashCheck: SyntaxChecker = async (path, config) => {\n if (!(await probe('bash', ['--version'], 'hasBash', config))) {\n return { ok: true };\n }\n const result = await spawnLocalProcess(\n 'bash',\n ['-n', path],\n { ...config, timeoutMs: 5000, sandbox: { enabled: false } },\n { internal: true }\n );\n if (result.exitCode === 0) return { ok: true };\n return {\n ok: false,\n checker: 'bash -n',\n output: result.stderr.trim() || result.stdout.trim() || 'syntax error',\n };\n};\n\nconst CHECKERS_BY_EXT: Record<string, SyntaxChecker> = {\n '.js': jsCheck,\n '.mjs': jsCheck,\n '.cjs': jsCheck,\n '.jsx': jsCheck,\n '.py': pythonCheck,\n '.pyw': pythonCheck,\n '.json': jsonCheck,\n '.sh': bashCheck,\n '.bash': bashCheck,\n};\n\n/**\n * Run the post-edit syntax check for `absolutePath`. Returns\n * `null` when no checker matches the extension (most files), or a\n * `SyntaxCheckOutcome`.\n *\n * Truncates `output` to `maxOutputChars` (default 4096) so a\n * 10MB-of-errors transpiler dump can't blow the model context.\n */\nexport async function runPostEditSyntaxCheck(\n absolutePath: string,\n config: t.LocalExecutionConfig\n): Promise<SyntaxCheckOutcome | null> {\n const ext = extname(absolutePath).toLowerCase();\n const checker = (CHECKERS_BY_EXT as Record<string, SyntaxChecker | undefined>)[ext];\n if (checker == null) return null;\n try {\n const result = await checker(absolutePath, config);\n if (!result.ok) {\n return {\n ok: false,\n checker: result.checker,\n output: result.output.slice(0, 4096),\n };\n }\n return result;\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuDA,IAAI,sCAAsB,IAAI,QAG5B;AAEF,SAAS,YAAY,KAA4C;CAC/D,IAAI,OAAO,MAAM,OAAO;CACxB,MAAM,SAA6C,CAAC;CACpD,KAAK,MAAM,KAAK,OAAO,KAAK,GAAG,CAAC,CAAC,KAAK,GACpC,OAAO,KAAK,IAAI;CAElB,OAAO,KAAK,UAAU,MAAM;AAC9B;AAEA,SAAS,SACP,QACY;CACZ,MAAM,UAAUA,6BAAAA,SAAS,MAAM;CAC/B,IAAI,SAAS,oBAAoB,IAAI,OAAO;CAC5C,IAAI,UAAU,MAAM;EAClB,yBAAS,IAAI,IAAI;EACjB,oBAAoB,IAAI,SAAS,MAAM;CACzC;CACA,MAAM,SAAS,YAAY,OAAO,GAAG;CACrC,IAAI,QAAQ,OAAO,IAAI,MAAM;CAC7B,IAAI,SAAS,MAAM;E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YAC+C;CACjF,IAAI,WAAW,MAAM,OAAO;CAC5B,IAAI;EACF,MAAM,SAAS,MAAM,QAAQ,cAAc,MAAM;EACjD,IAAI,CAAC,OAAO,IACV,OAAO;GACL,IAAI;GACJ,SAAS,OAAO;GAChB,QAAQ,OAAO,OAAO,MAAM,GAAG,IAAI;EACrC;EAEF,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"syntaxCheck.cjs","names":["getSpawn","spawnLocalProcess","path","getWorkspaceFS","isWorkspaceClientTimeoutError"],"sources":["../../../../src/tools/local/syntaxCheck.ts"],"sourcesContent":["/**\n * Per-file syntax check used by `edit_file` / `write_file` to surface\n * obvious errors immediately after the write — strictly cheaper than\n * full LSP integration and catches the bulk of \"you broke the file\"\n * regressions a vision-less agent loop would otherwise miss until\n * the next call.\n *\n * Each checker is a tiny shell-out (or in-process function) keyed on\n * file extension. Failures are returned as a single short message;\n * the wiring layer decides whether to append it to the tool result\n * advisorily (`auto`) or to throw and force the model to react\n * (`strict`).\n *\n * We deliberately do NOT cover TypeScript here because per-file `tsc`\n * is slow and per-file syntax (without type info) misses most TS\n * errors anyway. Use the project-level `compile_check` tool for that.\n */\n\nimport { extname } from 'path';\nimport type * as t from '@/types';\nimport { isWorkspaceClientTimeoutError } from './workspaceFS';\nimport {\n getSpawn,\n getWorkspaceFS,\n spawnLocalProcess,\n} from './LocalExecutionEngine';\n\nexport type SyntaxCheckOutcome =\n | { ok: true }\n | { ok: false; checker: string; output: string };\n\nexport type SyntaxChecker = (\n path: string,\n config: t.LocalExecutionConfig\n) => Promise<SyntaxCheckOutcome>;\n\n/**\n * Per-backend availability cache for the post-edit syntax-check probe\n * tools (node, python3, bash). Keyed on the *effective spawn backend*\n * — see `getSpawn(config)` in LocalExecutionEngine — so a Run that\n * probes node over Node's child_process can't poison a subsequent Run\n * whose `local.exec.spawn` routes elsewhere (a remote sandbox might\n * have python but not node, etc.).\n *\n * Mirrors the same fix that landed for the ripgrep cache in\n * `LocalCodingTools.ts` after the first round of Codex review.\n * WeakMap keying lets disposed backends GC their entry; the test\n * reset hook re-creates the map.\n */\ntype ProbeKind = 'hasNode' | 'hasPython' | 'hasBash';\ntype ProbeCache = Partial<Record<ProbeKind, Promise<boolean>>>;\n\n// Per-backend × per-env cache. Codex P2 #40 — keying by spawn\n// backend alone misses env-driven availability changes (e.g. PATH\n// loses node between Runs that share the same backend). Same fix\n// shape as the ripgrep cache (Codex P1 #34).\nlet probeCacheByBackend = new WeakMap<\n t.LocalSpawn,\n Map<string, ProbeCache>\n>();\n\nfunction envCacheKey(env: NodeJS.ProcessEnv | undefined): string {\n if (env == null) return '';\n const sorted: Record<string, string | undefined> = {};\n for (const k of Object.keys(env).sort()) {\n sorted[k] = env[k];\n }\n return JSON.stringify(sorted);\n}\n\nfunction cacheFor(\n config: t.LocalExecutionConfig\n): ProbeCache {\n const backend = getSpawn(config);\n let envMap = probeCacheByBackend.get(backend);\n if (envMap == null) {\n envMap = new Map();\n probeCacheByBackend.set(backend, envMap);\n }\n const envKey = envCacheKey(config.env);\n let entry = envMap.get(envKey);\n if (entry == null) {\n entry = {};\n envMap.set(envKey, entry);\n }\n return entry;\n}\n\nasync function probe(\n command: string,\n args: string[],\n cached: ProbeKind,\n config: t.LocalExecutionConfig\n): Promise<boolean> {\n const entry = cacheFor(config);\n let probePromise = entry[cached];\n if (probePromise == null) {\n probePromise = spawnLocalProcess(\n command,\n args,\n { ...config, timeoutMs: 5000, sandbox: { enabled: false } },\n { internal: true }\n )\n .then((result) => result != null && result.exitCode === 0)\n .catch(() => false);\n entry[cached] = probePromise;\n }\n return probePromise;\n}\n\n/**\n * Test-only reset hook. Clears the per-backend probe cache so tests\n * can swap in mocked spawn backends and reprobe deterministically.\n *\n * @internal Not part of the public SDK surface.\n */\nexport function _resetSyntaxCheckProbeCacheForTests(): void {\n probeCacheByBackend = new WeakMap();\n}\n\nconst jsCheck: SyntaxChecker = async (path, config) => {\n if (!(await probe('node', ['--version'], 'hasNode', config))) {\n return { ok: true };\n }\n const result = await spawnLocalProcess(\n 'node',\n ['--check', path],\n { ...config, timeoutMs: 5000, sandbox: { enabled: false } },\n { internal: true }\n );\n if (result.exitCode === 0) return { ok: true };\n return {\n ok: false,\n checker: 'node --check',\n output: result.stderr.trim() || result.stdout.trim() || 'syntax error',\n };\n};\n\nconst pythonCheck: SyntaxChecker = async (path, config) => {\n if (!(await probe('python3', ['--version'], 'hasPython', config))) {\n return { ok: true };\n }\n const program =\n 'import py_compile, sys\\n' +\n 'try:\\n' +\n ' py_compile.compile(sys.argv[1], doraise=True)\\n' +\n 'except py_compile.PyCompileError as e:\\n' +\n ' print(e.msg.strip(), file=sys.stderr)\\n' +\n ' sys.exit(1)\\n';\n const result = await spawnLocalProcess(\n 'python3',\n ['-c', program, path],\n { ...config, timeoutMs: 5000, sandbox: { enabled: false } },\n { internal: true }\n );\n if (result.exitCode === 0) return { ok: true };\n return {\n ok: false,\n checker: 'py_compile',\n output: result.stderr.trim() || result.stdout.trim() || 'syntax error',\n };\n};\n\nconst jsonCheck: SyntaxChecker = async (path, config) => {\n // Route through the configured WorkspaceFS so a Run with a custom\n // `local.exec.fs` (in-memory or remote engine) validates the same\n // file the write_file/edit_file path actually wrote — pre-fix this\n // read went to the host fs and either silently passed (no host\n // file → catch returns undefined → ok: true) or read a different\n // file with the same absolute path. Codex P1 #24.\n const fs = getWorkspaceFS(config);\n const raw = await fs.readFile(path, 'utf8').catch((error) => {\n // A stalled read must not pass the syntax gate as ok:true — surface it.\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n return undefined;\n });\n if (raw == null) return { ok: true };\n try {\n JSON.parse(raw);\n return { ok: true };\n } catch (err) {\n return {\n ok: false,\n checker: 'JSON.parse',\n output: (err as Error).message,\n };\n }\n};\n\nconst bashCheck: SyntaxChecker = async (path, config) => {\n if (!(await probe('bash', ['--version'], 'hasBash', config))) {\n return { ok: true };\n }\n const result = await spawnLocalProcess(\n 'bash',\n ['-n', path],\n { ...config, timeoutMs: 5000, sandbox: { enabled: false } },\n { internal: true }\n );\n if (result.exitCode === 0) return { ok: true };\n return {\n ok: false,\n checker: 'bash -n',\n output: result.stderr.trim() || result.stdout.trim() || 'syntax error',\n };\n};\n\nconst CHECKERS_BY_EXT: Record<string, SyntaxChecker> = {\n '.js': jsCheck,\n '.mjs': jsCheck,\n '.cjs': jsCheck,\n '.jsx': jsCheck,\n '.py': pythonCheck,\n '.pyw': pythonCheck,\n '.json': jsonCheck,\n '.sh': bashCheck,\n '.bash': bashCheck,\n};\n\n/**\n * Run the post-edit syntax check for `absolutePath`. Returns\n * `null` when no checker matches the extension (most files), or a\n * `SyntaxCheckOutcome`.\n *\n * Truncates `output` to `maxOutputChars` (default 4096) so a\n * 10MB-of-errors transpiler dump can't blow the model context.\n */\nexport async function runPostEditSyntaxCheck(\n absolutePath: string,\n config: t.LocalExecutionConfig\n): Promise<SyntaxCheckOutcome | null> {\n const ext = extname(absolutePath).toLowerCase();\n const checker = (CHECKERS_BY_EXT as Record<string, SyntaxChecker | undefined>)[ext];\n if (checker == null) return null;\n try {\n const result = await checker(absolutePath, config);\n if (!result.ok) {\n return {\n ok: false,\n checker: result.checker,\n output: result.output.slice(0, 4096),\n };\n }\n return result;\n } catch (error) {\n // Don't swallow a stalled-RPC timeout as \"no checker outcome\" (which would\n // let the write through without a real syntax gate) — surface it.\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwDA,IAAI,sCAAsB,IAAI,QAG5B;AAEF,SAAS,YAAY,KAA4C;CAC/D,IAAI,OAAO,MAAM,OAAO;CACxB,MAAM,SAA6C,CAAC;CACpD,KAAK,MAAM,KAAK,OAAO,KAAK,GAAG,CAAC,CAAC,KAAK,GACpC,OAAO,KAAK,IAAI;CAElB,OAAO,KAAK,UAAU,MAAM;AAC9B;AAEA,SAAS,SACP,QACY;CACZ,MAAM,UAAUA,6BAAAA,SAAS,M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,KAAK,KAAK,OAAO,OAAO,KAAK,KAAK;CAC1D;AACF;AAEA,MAAM,kBAAiD;CACrD,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,OAAO;CACP,QAAQ;CACR,SAAS;CACT,OAAO;CACP,SAAS;AACX;;;;;;;;;AAUA,eAAsB,uBACpB,cACA,QACoC;CAEpC,MAAM,UAAW,iBAAA,GAAA,KAAA,QAAA,CADG,YAAY,CAAC,CAAC,YAC+C;CACjF,IAAI,WAAW,MAAM,OAAO;CAC5B,IAAI;EACF,MAAM,SAAS,MAAM,QAAQ,cAAc,MAAM;EACjD,IAAI,CAAC,OAAO,IACV,OAAO;GACL,IAAI;GACJ,SAAS,OAAO;GAChB,QAAQ,OAAO,OAAO,MAAM,GAAG,IAAI;EACrC;EAEF,OAAO;CACT,SAAS,OAAO;EAGd,IAAIE,oBAAAA,8BAA8B,KAAK,GACrC,MAAM;EAER,OAAO;CACT;AACF"}
@@ -21,6 +21,24 @@ let fs_promises = require("fs/promises");
21
21
  * `fs/promises`.
22
22
  */
23
23
  /**
24
+ * Thrown when a {@link WorkspaceFS} operation is abandoned by a client-side
25
+ * backstop timeout (a stalled remote/sandbox RPC that never returned). This is
26
+ * DISTINCT from "file not found": callers that catch generic FS failures as
27
+ * absence — e.g. a pre-read before an overwrite, or a `stat` before snapshotting
28
+ * — MUST rethrow this so a stalled read isn't mistaken for a missing file (which
29
+ * would otherwise overwrite an existing file or snapshot it as absent).
30
+ */
31
+ var WorkspaceClientTimeoutError = class extends Error {
32
+ code = "WORKSPACE_CLIENT_TIMEOUT";
33
+ constructor(message) {
34
+ super(message);
35
+ this.name = "WorkspaceClientTimeoutError";
36
+ }
37
+ };
38
+ function isWorkspaceClientTimeoutError(error) {
39
+ return error instanceof WorkspaceClientTimeoutError || typeof error === "object" && error !== null && error.code === "WORKSPACE_CLIENT_TIMEOUT";
40
+ }
41
+ /**
24
42
  * Default `WorkspaceFS` backed by Node's `fs/promises` module.
25
43
  * Returned by `getWorkspaceFS(config)` when the host hasn't supplied
26
44
  * an override on `local.exec.fs`.
@@ -38,6 +56,8 @@ const nodeWorkspaceFS = {
38
56
  open: (path, flags) => (0, fs_promises.open)(path, flags)
39
57
  };
40
58
  //#endregion
59
+ exports.WorkspaceClientTimeoutError = WorkspaceClientTimeoutError;
60
+ exports.isWorkspaceClientTimeoutError = isWorkspaceClientTimeoutError;
41
61
  exports.nodeWorkspaceFS = nodeWorkspaceFS;
42
62
 
43
63
  //# sourceMappingURL=workspaceFS.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"workspaceFS.cjs","names":[],"sources":["../../../../src/tools/local/workspaceFS.ts"],"sourcesContent":["/**\n * Engine-agnostic filesystem seam for the local-coding tool suite.\n *\n * The current \"local\" engine maps every operation to Node's\n * `fs/promises` against the host machine. A future engine — e.g. a\n * stateful remote sandbox (e2b / Modal / Daytona / ssh-jail) —\n * supplies its own `WorkspaceFS` implementation and reuses every\n * tool factory unchanged. Same fuzzy-match `edit_file`, same\n * checkpointer, same syntax-check, same image attachments — only\n * the underlying I/O changes.\n *\n * Path semantics belong to the implementation. The local engine\n * interprets paths as host filesystem paths; a remote engine would\n * interpret them as remote-namespace paths. Tool factories don't\n * inspect the strings beyond passing them through.\n *\n * Keep this surface minimal. Add a method only when an existing\n * tool genuinely needs it; resist the temptation to mirror all of\n * `fs/promises`.\n */\n\nimport {\n mkdir as fsMkdir,\n open as fsOpen,\n readdir as fsReaddir,\n readFile as fsReadFile,\n realpath as fsRealpath,\n stat as fsStat,\n unlink as fsUnlink,\n writeFile as fsWriteFile,\n} from 'fs/promises';\nimport type { MakeDirectoryOptions, Stats, WriteFileOptions } from 'fs';\nimport type { FileHandle } from 'fs/promises';\n\nexport type ReaddirEntry = {\n name: string;\n isFile(): boolean;\n isDirectory(): boolean;\n isSymbolicLink(): boolean;\n};\n\nexport interface WorkspaceFS {\n readFile(path: string, encoding: 'utf8'): Promise<string>;\n readFile(path: string): Promise<Buffer>;\n writeFile(\n path: string,\n content: string | Buffer,\n options?: WriteFileOptions\n ): Promise<void>;\n stat(path: string): Promise<Stats>;\n readdir(\n path: string,\n options: { withFileTypes: true }\n ): Promise<ReaddirEntry[]>;\n readdir(path: string): Promise<string[]>;\n mkdir(path: string, options?: MakeDirectoryOptions): Promise<void>;\n realpath(path: string): Promise<string>;\n unlink(path: string): Promise<void>;\n /** Open a file for low-level read access (used by binary detection). */\n open(path: string, flags: 'r'): Promise<FileHandle>;\n}\n\n/**\n * Default `WorkspaceFS` backed by Node's `fs/promises` module.\n * Returned by `getWorkspaceFS(config)` when the host hasn't supplied\n * an override on `local.exec.fs`.\n */\nexport const nodeWorkspaceFS: WorkspaceFS = {\n // The runtime impl ignores the encoding-vs-buffer distinction; the\n // overload signatures above are what callers see.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readFile: ((path: string, encoding?: 'utf8') =>\n encoding != null\n ? fsReadFile(path, encoding)\n : fsReadFile(path)) as WorkspaceFS['readFile'],\n writeFile: (path, content, options) =>\n fsWriteFile(path, content, options ?? 'utf8'),\n stat: (path) => fsStat(path),\n readdir: ((path: string, options?: { withFileTypes: true }) =>\n options?.withFileTypes === true\n ? fsReaddir(path, { withFileTypes: true })\n : fsReaddir(path)) as WorkspaceFS['readdir'],\n mkdir: async (path, options) => {\n await fsMkdir(path, options);\n },\n realpath: (path) => fsRealpath(path),\n unlink: (path) => fsUnlink(path),\n open: (path, flags) => fsOpen(path, flags),\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,MAAa,kBAA+B;CAI1C,YAAY,MAAc,aACxB,YAAY,QAAA,GAAA,YAAA,SAAA,CACG,MAAM,QAAQ,KAAA,GAAA,YAAA,SAAA,CACd,IAAI;CACrB,YAAY,MAAM,SAAS,aAAA,GAAA,YAAA,UAAA,CACb,MAAM,SAAS,WAAW,MAAM;CAC9C,OAAO,UAAA,GAAA,YAAA,KAAA,CAAgB,IAAI;CAC3B,WAAW,MAAc,YACvB,SAAS,kBAAkB,QAAA,GAAA,YAAA,QAAA,CACb,MAAM,EAAE,eAAe,KAAK,CAAC,KAAA,GAAA,YAAA,QAAA,CAC7B,IAAI;CACpB,OAAO,OAAO,MAAM,YAAY;EAC9B,OAAA,GAAA,YAAA,MAAA,CAAc,MAAM,OAAO;CAC7B;CACA,WAAW,UAAA,GAAA,YAAA,SAAA,CAAoB,IAAI;CACnC,SAAS,UAAA,GAAA,YAAA,OAAA,CAAkB,IAAI;CAC/B,OAAO,MAAM,WAAA,GAAA,YAAA,KAAA,CAAiB,MAAM,KAAK;AAC3C"}
1
+ {"version":3,"file":"workspaceFS.cjs","names":[],"sources":["../../../../src/tools/local/workspaceFS.ts"],"sourcesContent":["/**\n * Engine-agnostic filesystem seam for the local-coding tool suite.\n *\n * The current \"local\" engine maps every operation to Node's\n * `fs/promises` against the host machine. A future engine — e.g. a\n * stateful remote sandbox (e2b / Modal / Daytona / ssh-jail) —\n * supplies its own `WorkspaceFS` implementation and reuses every\n * tool factory unchanged. Same fuzzy-match `edit_file`, same\n * checkpointer, same syntax-check, same image attachments — only\n * the underlying I/O changes.\n *\n * Path semantics belong to the implementation. The local engine\n * interprets paths as host filesystem paths; a remote engine would\n * interpret them as remote-namespace paths. Tool factories don't\n * inspect the strings beyond passing them through.\n *\n * Keep this surface minimal. Add a method only when an existing\n * tool genuinely needs it; resist the temptation to mirror all of\n * `fs/promises`.\n */\n\nimport {\n mkdir as fsMkdir,\n open as fsOpen,\n readdir as fsReaddir,\n readFile as fsReadFile,\n realpath as fsRealpath,\n stat as fsStat,\n unlink as fsUnlink,\n writeFile as fsWriteFile,\n} from 'fs/promises';\nimport type { MakeDirectoryOptions, Stats, WriteFileOptions } from 'fs';\nimport type { FileHandle } from 'fs/promises';\n\nexport type ReaddirEntry = {\n name: string;\n isFile(): boolean;\n isDirectory(): boolean;\n isSymbolicLink(): boolean;\n};\n\n/**\n * Thrown when a {@link WorkspaceFS} operation is abandoned by a client-side\n * backstop timeout (a stalled remote/sandbox RPC that never returned). This is\n * DISTINCT from \"file not found\": callers that catch generic FS failures as\n * absence — e.g. a pre-read before an overwrite, or a `stat` before snapshotting\n * — MUST rethrow this so a stalled read isn't mistaken for a missing file (which\n * would otherwise overwrite an existing file or snapshot it as absent).\n */\nexport class WorkspaceClientTimeoutError extends Error {\n readonly code = 'WORKSPACE_CLIENT_TIMEOUT';\n constructor(message: string) {\n super(message);\n this.name = 'WorkspaceClientTimeoutError';\n }\n}\n\nexport function isWorkspaceClientTimeoutError(\n error: unknown\n): error is WorkspaceClientTimeoutError {\n return (\n error instanceof WorkspaceClientTimeoutError ||\n (typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === 'WORKSPACE_CLIENT_TIMEOUT')\n );\n}\n\nexport interface WorkspaceFS {\n readFile(path: string, encoding: 'utf8'): Promise<string>;\n readFile(path: string): Promise<Buffer>;\n writeFile(\n path: string,\n content: string | Buffer,\n options?: WriteFileOptions\n ): Promise<void>;\n stat(path: string): Promise<Stats>;\n readdir(\n path: string,\n options: { withFileTypes: true }\n ): Promise<ReaddirEntry[]>;\n readdir(path: string): Promise<string[]>;\n mkdir(path: string, options?: MakeDirectoryOptions): Promise<void>;\n realpath(path: string): Promise<string>;\n unlink(path: string): Promise<void>;\n /** Open a file for low-level read access (used by binary detection). */\n open(path: string, flags: 'r'): Promise<FileHandle>;\n}\n\n/**\n * Default `WorkspaceFS` backed by Node's `fs/promises` module.\n * Returned by `getWorkspaceFS(config)` when the host hasn't supplied\n * an override on `local.exec.fs`.\n */\nexport const nodeWorkspaceFS: WorkspaceFS = {\n // The runtime impl ignores the encoding-vs-buffer distinction; the\n // overload signatures above are what callers see.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readFile: ((path: string, encoding?: 'utf8') =>\n encoding != null\n ? fsReadFile(path, encoding)\n : fsReadFile(path)) as WorkspaceFS['readFile'],\n writeFile: (path, content, options) =>\n fsWriteFile(path, content, options ?? 'utf8'),\n stat: (path) => fsStat(path),\n readdir: ((path: string, options?: { withFileTypes: true }) =>\n options?.withFileTypes === true\n ? fsReaddir(path, { withFileTypes: true })\n : fsReaddir(path)) as WorkspaceFS['readdir'],\n mkdir: async (path, options) => {\n await fsMkdir(path, options);\n },\n realpath: (path) => fsRealpath(path),\n unlink: (path) => fsUnlink(path),\n open: (path, flags) => fsOpen(path, flags),\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,8BAAb,cAAiD,MAAM;CACrD,OAAgB;CAChB,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,8BACd,OACsC;CACtC,OACE,iBAAiB,+BAChB,OAAO,UAAU,YAChB,UAAU,QACT,MAA6B,SAAS;AAE7C;;;;;;AA4BA,MAAa,kBAA+B;CAI1C,YAAY,MAAc,aACxB,YAAY,QAAA,GAAA,YAAA,SAAA,CACG,MAAM,QAAQ,KAAA,GAAA,YAAA,SAAA,CACd,IAAI;CACrB,YAAY,MAAM,SAAS,aAAA,GAAA,YAAA,UAAA,CACb,MAAM,SAAS,WAAW,MAAM;CAC9C,OAAO,UAAA,GAAA,YAAA,KAAA,CAAgB,IAAI;CAC3B,WAAW,MAAc,YACvB,SAAS,kBAAkB,QAAA,GAAA,YAAA,QAAA,CACb,MAAM,EAAE,eAAe,KAAK,CAAC,KAAA,GAAA,YAAA,QAAA,CAC7B,IAAI;CACpB,OAAO,OAAO,MAAM,YAAY;EAC9B,OAAA,GAAA,YAAA,MAAA,CAAc,MAAM,OAAO;CAC7B;CACA,WAAW,UAAA,GAAA,YAAA,SAAA,CAAoB,IAAI;CACnC,SAAS,UAAA,GAAA,YAAA,OAAA,CAAkB,IAAI;CAC/B,OAAO,MAAM,WAAA,GAAA,YAAA,KAAA,CAAiB,MAAM,KAAK;AAC3C"}
@@ -4,7 +4,7 @@ import "../common/index.mjs";
4
4
  import { apportionTokenCounts } from "../utils/tokens.mjs";
5
5
  import { createPruneMessages } from "../messages/prune.mjs";
6
6
  import { syncBudgetDerivedFields } from "../messages/budget.mjs";
7
- import { addCacheControlToStablePrefixMessages, addTailCacheControl, buildAnthropicCacheControl, buildBedrockCachePoint, cloneMessage, resolvePromptCacheTtl } from "../messages/cache.mjs";
7
+ import { addCacheControlToStablePrefixMessages, addTailCacheControl, buildAnthropicCacheControl, buildBedrockCachePoint, cloneMessage, resolveBedrockPromptCacheTtl, resolvePromptCacheTtl } from "../messages/cache.mjs";
8
8
  import "../messages/index.mjs";
9
9
  import { toJsonSchema } from "../utils/schema.mjs";
10
10
  import { isThinkingEnabled } from "../llm/request.mjs";
@@ -459,12 +459,13 @@ The following tools are available exclusively through the \`${programmaticTool.n
459
459
  return resolvePromptCacheTtl(this.clientOptions?.promptCacheTtl);
460
460
  }
461
461
  /**
462
- * Resolved TTL for Bedrock prompt-cache checkpoints (default `'1h'`).
463
- * Models that don't support the 1-hour TTL downgrade to 5m server-side.
462
+ * Resolved TTL for Bedrock prompt-cache checkpoints (default `'1h'` on Claude).
463
+ * Claude models downgrade an unsupported 1h to 5m server-side; non-Claude
464
+ * models (Nova) reject the extended TTL, so they are clamped to 5m.
464
465
  */
465
466
  getBedrockPromptCacheTtl() {
466
467
  const bedrockOptions = this.clientOptions;
467
- return resolvePromptCacheTtl(bedrockOptions?.promptCacheTtl);
468
+ return resolveBedrockPromptCacheTtl(bedrockOptions?.promptCacheTtl, bedrockOptions?.model);
468
469
  }
469
470
  buildSystemMessage({ stableInstructions, dynamicInstructions, promptCacheProvider, shouldMoveDynamicInstructions }) {
470
471
  if (!stableInstructions && !dynamicInstructions) return;