@librechat/agents 3.3.5 → 3.3.7

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 (127) hide show
  1. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +1 -1
  2. package/dist/cjs/llm/openai/index.cjs +51 -6
  3. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  4. package/dist/cjs/main.cjs +16 -0
  5. package/dist/cjs/session/JsonlSessionStore.cjs +1 -1
  6. package/dist/cjs/stream.cjs +6 -1
  7. package/dist/cjs/stream.cjs.map +1 -1
  8. package/dist/cjs/tools/BashExecutor.cjs +3 -1
  9. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  10. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +2 -0
  11. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  12. package/dist/cjs/tools/CodeExecutor.cjs +19 -16
  13. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  14. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +2 -0
  15. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  16. package/dist/cjs/tools/ReadFile.cjs +8 -4
  17. package/dist/cjs/tools/ReadFile.cjs.map +1 -1
  18. package/dist/cjs/tools/SkillTool.cjs +2 -0
  19. package/dist/cjs/tools/SkillTool.cjs.map +1 -1
  20. package/dist/cjs/tools/SubagentTool.cjs +3 -0
  21. package/dist/cjs/tools/SubagentTool.cjs.map +1 -1
  22. package/dist/cjs/tools/ToolNode.cjs +88 -27
  23. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  24. package/dist/cjs/tools/ToolSearch.cjs +5 -1
  25. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  26. package/dist/cjs/tools/intentArg.cjs +256 -0
  27. package/dist/cjs/tools/intentArg.cjs.map +1 -0
  28. package/dist/cjs/tools/local/CompileCheckTool.cjs +3 -2
  29. package/dist/cjs/tools/local/CompileCheckTool.cjs.map +1 -1
  30. package/dist/cjs/tools/local/LocalCodingTools.cjs +13 -12
  31. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  32. package/dist/cjs/tools/local/LocalExecutionEngine.cjs +2 -2
  33. package/dist/cjs/tools/ptcTimeout.cjs.map +1 -1
  34. package/dist/cjs/tools/search/schema.cjs +2 -0
  35. package/dist/cjs/tools/search/schema.cjs.map +1 -1
  36. package/dist/cjs/tools/search/tool.cjs +31 -1
  37. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  38. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +1 -0
  39. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  40. package/dist/cjs/tools/toolOutputReferences.cjs +41 -7
  41. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  42. package/dist/esm/hooks/createWorkspacePolicyHook.mjs +1 -1
  43. package/dist/esm/llm/openai/index.mjs +51 -6
  44. package/dist/esm/llm/openai/index.mjs.map +1 -1
  45. package/dist/esm/main.mjs +4 -3
  46. package/dist/esm/session/JsonlSessionStore.mjs +1 -1
  47. package/dist/esm/stream.mjs +6 -1
  48. package/dist/esm/stream.mjs.map +1 -1
  49. package/dist/esm/tools/BashExecutor.mjs +3 -1
  50. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  51. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +2 -0
  52. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  53. package/dist/esm/tools/CodeExecutor.mjs +19 -16
  54. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  55. package/dist/esm/tools/ProgrammaticToolCalling.mjs +2 -0
  56. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  57. package/dist/esm/tools/ReadFile.mjs +8 -4
  58. package/dist/esm/tools/ReadFile.mjs.map +1 -1
  59. package/dist/esm/tools/SkillTool.mjs +2 -0
  60. package/dist/esm/tools/SkillTool.mjs.map +1 -1
  61. package/dist/esm/tools/SubagentTool.mjs +3 -0
  62. package/dist/esm/tools/SubagentTool.mjs.map +1 -1
  63. package/dist/esm/tools/ToolNode.mjs +88 -28
  64. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  65. package/dist/esm/tools/ToolSearch.mjs +5 -1
  66. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  67. package/dist/esm/tools/intentArg.mjs +244 -0
  68. package/dist/esm/tools/intentArg.mjs.map +1 -0
  69. package/dist/esm/tools/local/CompileCheckTool.mjs +3 -2
  70. package/dist/esm/tools/local/CompileCheckTool.mjs.map +1 -1
  71. package/dist/esm/tools/local/LocalCodingTools.mjs +13 -12
  72. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  73. package/dist/esm/tools/local/LocalExecutionEngine.mjs +2 -2
  74. package/dist/esm/tools/ptcTimeout.mjs.map +1 -1
  75. package/dist/esm/tools/search/schema.mjs +2 -0
  76. package/dist/esm/tools/search/schema.mjs.map +1 -1
  77. package/dist/esm/tools/search/tool.mjs +31 -2
  78. package/dist/esm/tools/search/tool.mjs.map +1 -1
  79. package/dist/esm/tools/subagent/SubagentExecutor.mjs +1 -0
  80. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  81. package/dist/esm/tools/toolOutputReferences.mjs +41 -7
  82. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  83. package/dist/types/index.d.ts +1 -0
  84. package/dist/types/llm/openai/index.d.ts +0 -11
  85. package/dist/types/tools/BashExecutor.d.ts +18 -0
  86. package/dist/types/tools/CodeExecutor.d.ts +18 -0
  87. package/dist/types/tools/ReadFile.d.ts +18 -0
  88. package/dist/types/tools/SkillTool.d.ts +18 -0
  89. package/dist/types/tools/SubagentTool.d.ts +9 -0
  90. package/dist/types/tools/ToolNode.d.ts +37 -5
  91. package/dist/types/tools/ToolSearch.d.ts +18 -0
  92. package/dist/types/tools/intentArg.d.ts +181 -0
  93. package/dist/types/tools/ptcTimeout.d.ts +2 -0
  94. package/dist/types/tools/search/schema.d.ts +18 -0
  95. package/dist/types/tools/search/tool.d.ts +18 -0
  96. package/dist/types/tools/toolOutputReferences.d.ts +12 -2
  97. package/dist/types/types/stream.d.ts +18 -0
  98. package/dist/types/types/tools.d.ts +27 -2
  99. package/package.json +1 -1
  100. package/src/index.ts +1 -0
  101. package/src/llm/openai/index.ts +74 -10
  102. package/src/llm/openai/llm.spec.ts +105 -0
  103. package/src/stream.ts +12 -1
  104. package/src/tools/BashExecutor.ts +6 -0
  105. package/src/tools/BashProgrammaticToolCalling.ts +2 -0
  106. package/src/tools/CodeExecutor.ts +6 -0
  107. package/src/tools/ProgrammaticToolCalling.ts +2 -0
  108. package/src/tools/ReadFile.ts +2 -0
  109. package/src/tools/SkillTool.ts +2 -0
  110. package/src/tools/SubagentTool.ts +3 -0
  111. package/src/tools/ToolNode.ts +190 -43
  112. package/src/tools/ToolSearch.ts +3 -0
  113. package/src/tools/__tests__/ToolNode.onResultCompletion.test.ts +174 -0
  114. package/src/tools/__tests__/intentArg.test.ts +357 -0
  115. package/src/tools/__tests__/intentCoverage.test.ts +139 -0
  116. package/src/tools/__tests__/toolOutputReferences.test.ts +83 -0
  117. package/src/tools/intentArg.ts +357 -0
  118. package/src/tools/local/CompileCheckTool.ts +4 -3
  119. package/src/tools/local/LocalCodingTools.ts +14 -13
  120. package/src/tools/ptcTimeout.ts +2 -0
  121. package/src/tools/search/outcome.test.ts +90 -0
  122. package/src/tools/search/schema.ts +3 -0
  123. package/src/tools/search/tool.ts +47 -1
  124. package/src/tools/subagent/SubagentExecutor.ts +2 -1
  125. package/src/tools/toolOutputReferences.ts +77 -9
  126. package/src/types/stream.ts +18 -0
  127. package/src/types/tools.ts +24 -2
@@ -1 +1 @@
1
- {"version":3,"file":"CompileCheckTool.mjs","names":[],"sources":["../../../../src/tools/local/CompileCheckTool.ts"],"sourcesContent":["/**\n * `compile_check` — a thin LLM-callable wrapper around the project's\n * standard typecheck/lint command. Lets the agent answer \"did my\n * change break anything?\" without us shipping a real LSP client.\n *\n * Auto-detection priority (first hit wins):\n *\n * 1. `local.compileCheck.command` — explicit override\n * 2. `tsconfig.json` → `npx --no-install tsc --noEmit`\n * 3. `package.json` with a typescript dep → same as 2\n * 4. `pyproject.toml` or `setup.py` / `setup.cfg`\n * with a dev dep on mypy → `python3 -m mypy .`\n * else → `python3 -m py_compile <every .py>`\n * (bounded by find-walk so node_modules\n * and `.venv` don't blow up)\n * 5. `Cargo.toml` → `cargo check --message-format=short`\n * 6. `go.mod` → `go vet ./...`\n * 7. otherwise → tells the agent there's\n * no detected toolchain.\n *\n * Output is the spawn process's stdout/stderr passed through\n * `truncateLocalOutput` so a 10MB tsc dump can't blow context. The\n * exit code is reported.\n */\n\nimport { resolve } from 'path';\nimport { tool } from '@langchain/core/tools';\nimport type { DynamicStructuredTool } from '@langchain/core/tools';\nimport type { WorkspaceFS } from './workspaceFS';\nimport { isWorkspaceClientTimeoutError } from './workspaceFS';\nimport type * as t from '@/types';\nimport {\n getLocalCwd,\n getWorkspaceFS,\n spawnLocalProcess,\n truncateLocalOutput,\n validateBashCommand,\n} from './LocalExecutionEngine';\nimport { Constants } from '@/common';\n\n/** Back-compat alias; canonical name lives on `Constants.COMPILE_CHECK`. */\nexport const CompileCheckToolName = Constants.COMPILE_CHECK;\n\nconst CompileCheckSchema: t.JsonSchemaType = {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description:\n 'Optional explicit command to run instead of the auto-detected one. Runs verbatim from the local engine cwd; honours the standard sandbox/AST gate.',\n },\n timeout_ms: {\n type: 'integer',\n description:\n 'Optional timeout in milliseconds. Defaults to 120000 (2 min).',\n },\n },\n};\n\ntype DetectedKind =\n | 'typescript'\n | 'python-mypy'\n | 'python-compile'\n | 'rust'\n | 'go'\n | 'unknown';\n\ntype Detection = {\n kind: DetectedKind;\n command: string;\n reason: string;\n};\n\nasync function pathExists(fs: WorkspaceFS, p: string): Promise<boolean> {\n try {\n await fs.stat(p);\n return true;\n } catch (error) {\n // A stalled-RPC timeout is not \"absent\" — don't let it pick a weaker/wrong\n // toolchain after waiting through the backstop; surface it.\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n return false;\n }\n}\n\n// Probes for project markers via the configured WorkspaceFS so a Run\n// with `local.exec.fs` (in-memory or remote engine) detects the right\n// toolchain against the actual workspace — not the host filesystem.\n// Codex P1 #25.\nasync function detect(cwd: string, fs: WorkspaceFS): Promise<Detection> {\n if (await pathExists(fs, resolve(cwd, 'tsconfig.json'))) {\n return {\n kind: 'typescript',\n command: 'npx --no-install tsc --noEmit',\n reason: 'tsconfig.json present',\n };\n }\n if (await pathExists(fs, resolve(cwd, 'package.json'))) {\n const pkgRaw = await fs\n .readFile(resolve(cwd, 'package.json'), 'utf8')\n .catch((error) => {\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n return '';\n });\n if (pkgRaw.includes('\"typescript\"')) {\n return {\n kind: 'typescript',\n command: 'npx --no-install tsc --noEmit',\n reason: 'package.json declares typescript',\n };\n }\n }\n if (await pathExists(fs, resolve(cwd, 'Cargo.toml'))) {\n return {\n kind: 'rust',\n command: 'cargo check --message-format=short',\n reason: 'Cargo.toml present',\n };\n }\n if (await pathExists(fs, resolve(cwd, 'go.mod'))) {\n return {\n kind: 'go',\n command: 'go vet ./...',\n reason: 'go.mod present',\n };\n }\n if (\n (await pathExists(fs, resolve(cwd, 'pyproject.toml'))) ||\n (await pathExists(fs, resolve(cwd, 'setup.py'))) ||\n (await pathExists(fs, resolve(cwd, 'setup.cfg')))\n ) {\n const pyToml = await fs\n .readFile(resolve(cwd, 'pyproject.toml'), 'utf8')\n .catch((error) => {\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n return '';\n });\n if (pyToml.includes('mypy')) {\n return {\n kind: 'python-mypy',\n command: 'python3 -m mypy .',\n reason: 'pyproject.toml declares mypy',\n };\n }\n return {\n kind: 'python-compile',\n command:\n 'python3 -c \"import compileall, sys; sys.exit(0 if compileall.compile_dir(\\'.\\', quiet=1, rx=__import__(\\'re\\').compile(r\\'(node_modules|\\\\.venv|\\\\.git|build|dist)\\')) else 1)\"',\n reason: 'Python project (no mypy detected)',\n };\n }\n return {\n kind: 'unknown',\n command: '',\n reason:\n 'no recognised project marker (tsconfig.json, package.json[typescript], Cargo.toml, go.mod, pyproject.toml, setup.py)',\n };\n}\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\n\nexport function createCompileCheckTool(\n config: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput) => {\n const input = rawInput as {\n command?: string;\n timeout_ms?: number;\n };\n const cwd = getLocalCwd(config);\n const fs = getWorkspaceFS(config);\n const overrideCommand = input.command ?? config.compileCheck?.command;\n let detection: Detection;\n if (overrideCommand != null && overrideCommand.trim() !== '') {\n detection = {\n kind: 'unknown',\n command: overrideCommand,\n reason: 'explicit override',\n };\n } else {\n detection = await detect(cwd, fs);\n }\n\n if (detection.command === '') {\n const explainer = `compile_check: ${detection.reason}. Pass an explicit \\`command\\` (e.g. \\`npm run typecheck\\`) to override.`;\n return [\n explainer,\n {\n kind: detection.kind,\n ran: false,\n reason: detection.reason,\n cwd,\n },\n ];\n }\n\n // Codex P1 #21: route the resolved command through the same\n // safety gates the rest of the local engine uses. Without this\n // a host with `readOnly: true` (or relying on the destructive-\n // command guard) could be bypassed by passing a `command`\n // override to compile_check that performs writes/deletes.\n // Auto-detected commands (tsc/cargo/etc.) pass these gates\n // unchanged — the validation is only blocking for genuinely\n // mutating overrides.\n const validation = await validateBashCommand(detection.command, config);\n if (!validation.valid) {\n const explainer = `compile_check refused to run \\`${detection.command}\\`: ${validation.errors.join('; ')}`;\n return [\n explainer,\n {\n kind: detection.kind,\n ran: false,\n reason: validation.errors.join('; '),\n cwd,\n },\n ];\n }\n\n const timeoutMs =\n input.timeout_ms ??\n config.compileCheck?.timeoutMs ??\n DEFAULT_TIMEOUT_MS;\n const result = await spawnLocalProcess(\n config.shell ?? (process.platform === 'win32' ? 'bash.exe' : 'bash'),\n ['-lc', detection.command],\n {\n ...config,\n timeoutMs,\n maxOutputChars: config.maxOutputChars ?? 8000,\n }\n );\n\n const passed = result.exitCode === 0 && !result.timedOut;\n const headline = passed\n ? `compile_check (${detection.kind}) PASSED via \\`${detection.command}\\``\n : `compile_check (${detection.kind}) FAILED via \\`${detection.command}\\` ` +\n `(exit=${result.exitCode ?? 'unknown'}${result.timedOut ? ', timed_out=true' : ''})`;\n\n let body = '';\n if (result.stdout !== '') {\n body += `\\n\\nstdout:\\n${truncateLocalOutput(result.stdout, 4000)}`;\n }\n if (result.stderr !== '') {\n body += `\\n\\nstderr:\\n${truncateLocalOutput(result.stderr, 4000)}`;\n }\n if (result.fullOutputPath != null) {\n body += `\\n\\nfull_output_path: ${result.fullOutputPath}`;\n }\n const summary = `${headline}${body}\\n\\nworking_directory: ${cwd}\\nreason: ${detection.reason}`;\n\n return [\n summary,\n {\n kind: detection.kind,\n ran: true,\n passed,\n exit_code: result.exitCode,\n timed_out: result.timedOut,\n command: detection.command,\n cwd,\n },\n ];\n },\n {\n name: CompileCheckToolName,\n description:\n 'Run the project\\'s standard typecheck or lint pass and return its output. Auto-detects from project markers (tsconfig.json/package.json -> tsc; Cargo.toml -> cargo check; go.mod -> go vet; pyproject.toml -> mypy or py_compile). Pass `command` to override.',\n schema: CompileCheckSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createCompileCheckToolDefinition(): t.LCTool {\n return {\n name: CompileCheckToolName,\n description:\n 'Run the project\\'s standard typecheck or lint pass and return its output.',\n parameters: CompileCheckSchema,\n allowed_callers: ['direct', 'code_execution'],\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n toolType: 'builtin',\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,uBAAA;AAEb,MAAM,qBAAuC;CAC3C,MAAM;CACN,YAAY;EACV,SAAS;GACP,MAAM;GACN,aACE;EACJ;EACA,YAAY;GACV,MAAM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AAI,OAAO;EACX,IAAI,OAAO,WAAW,IACpB,QAAQ,gBAAgB,oBAAoB,OAAO,QAAQ,GAAI;EAEjE,IAAI,OAAO,WAAW,IACpB,QAAQ,gBAAgB,oBAAoB,OAAO,QAAQ,GAAI;EAEjE,IAAI,OAAO,kBAAkB,MAC3B,QAAQ,yBAAyB,OAAO;EAI1C,OAAO,CACL,GAHiB,WAAW,KAAK,yBAAyB,IAAI,YAAY,UAAU,UAIpF;GACE,MAAM,UAAU;GAChB,KAAK;GACL;GACA,WAAW,OAAO;GAClB,WAAW,OAAO;GAClB,SAAS,UAAU;GACnB;EACF,CACF;CACF,GACA;EACE,MAAM;EACN,aACE;EACF,QAAQ;EACR,gBAAA;CACF,CACF;AACF;AAEA,SAAgB,mCAA6C;CAC3D,OAAO;EACL,MAAM;EACN,aACE;EACF,YAAY;EACZ,iBAAiB,CAAC,UAAU,gBAAgB;EAC5C,gBAAA;EACA,UAAU;CACZ;AACF"}
1
+ {"version":3,"file":"CompileCheckTool.mjs","names":[],"sources":["../../../../src/tools/local/CompileCheckTool.ts"],"sourcesContent":["/**\n * `compile_check` — a thin LLM-callable wrapper around the project's\n * standard typecheck/lint command. Lets the agent answer \"did my\n * change break anything?\" without us shipping a real LSP client.\n *\n * Auto-detection priority (first hit wins):\n *\n * 1. `local.compileCheck.command` — explicit override\n * 2. `tsconfig.json` → `npx --no-install tsc --noEmit`\n * 3. `package.json` with a typescript dep → same as 2\n * 4. `pyproject.toml` or `setup.py` / `setup.cfg`\n * with a dev dep on mypy → `python3 -m mypy .`\n * else → `python3 -m py_compile <every .py>`\n * (bounded by find-walk so node_modules\n * and `.venv` don't blow up)\n * 5. `Cargo.toml` → `cargo check --message-format=short`\n * 6. `go.mod` → `go vet ./...`\n * 7. otherwise → tells the agent there's\n * no detected toolchain.\n *\n * Output is the spawn process's stdout/stderr passed through\n * `truncateLocalOutput` so a 10MB tsc dump can't blow context. The\n * exit code is reported.\n */\n\nimport { resolve } from 'path';\nimport { tool } from '@langchain/core/tools';\nimport type { DynamicStructuredTool } from '@langchain/core/tools';\nimport type { WorkspaceFS } from './workspaceFS';\nimport type * as t from '@/types';\nimport {\n getLocalCwd,\n getWorkspaceFS,\n spawnLocalProcess,\n truncateLocalOutput,\n validateBashCommand,\n} from './LocalExecutionEngine';\nimport { isWorkspaceClientTimeoutError } from './workspaceFS';\nimport { withIntent } from '@/tools/intentArg';\nimport { Constants } from '@/common';\n\n/** Back-compat alias; canonical name lives on `Constants.COMPILE_CHECK`. */\nexport const CompileCheckToolName = Constants.COMPILE_CHECK;\n\nconst CompileCheckSchema: t.JsonSchemaType = withIntent({\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description:\n 'Optional explicit command to run instead of the auto-detected one. Runs verbatim from the local engine cwd; honours the standard sandbox/AST gate.',\n },\n timeout_ms: {\n type: 'integer',\n description:\n 'Optional timeout in milliseconds. Defaults to 120000 (2 min).',\n },\n },\n});\n\ntype DetectedKind =\n | 'typescript'\n | 'python-mypy'\n | 'python-compile'\n | 'rust'\n | 'go'\n | 'unknown';\n\ntype Detection = {\n kind: DetectedKind;\n command: string;\n reason: string;\n};\n\nasync function pathExists(fs: WorkspaceFS, p: string): Promise<boolean> {\n try {\n await fs.stat(p);\n return true;\n } catch (error) {\n // A stalled-RPC timeout is not \"absent\" — don't let it pick a weaker/wrong\n // toolchain after waiting through the backstop; surface it.\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n return false;\n }\n}\n\n// Probes for project markers via the configured WorkspaceFS so a Run\n// with `local.exec.fs` (in-memory or remote engine) detects the right\n// toolchain against the actual workspace — not the host filesystem.\n// Codex P1 #25.\nasync function detect(cwd: string, fs: WorkspaceFS): Promise<Detection> {\n if (await pathExists(fs, resolve(cwd, 'tsconfig.json'))) {\n return {\n kind: 'typescript',\n command: 'npx --no-install tsc --noEmit',\n reason: 'tsconfig.json present',\n };\n }\n if (await pathExists(fs, resolve(cwd, 'package.json'))) {\n const pkgRaw = await fs\n .readFile(resolve(cwd, 'package.json'), 'utf8')\n .catch((error) => {\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n return '';\n });\n if (pkgRaw.includes('\"typescript\"')) {\n return {\n kind: 'typescript',\n command: 'npx --no-install tsc --noEmit',\n reason: 'package.json declares typescript',\n };\n }\n }\n if (await pathExists(fs, resolve(cwd, 'Cargo.toml'))) {\n return {\n kind: 'rust',\n command: 'cargo check --message-format=short',\n reason: 'Cargo.toml present',\n };\n }\n if (await pathExists(fs, resolve(cwd, 'go.mod'))) {\n return {\n kind: 'go',\n command: 'go vet ./...',\n reason: 'go.mod present',\n };\n }\n if (\n (await pathExists(fs, resolve(cwd, 'pyproject.toml'))) ||\n (await pathExists(fs, resolve(cwd, 'setup.py'))) ||\n (await pathExists(fs, resolve(cwd, 'setup.cfg')))\n ) {\n const pyToml = await fs\n .readFile(resolve(cwd, 'pyproject.toml'), 'utf8')\n .catch((error) => {\n if (isWorkspaceClientTimeoutError(error)) {\n throw error;\n }\n return '';\n });\n if (pyToml.includes('mypy')) {\n return {\n kind: 'python-mypy',\n command: 'python3 -m mypy .',\n reason: 'pyproject.toml declares mypy',\n };\n }\n return {\n kind: 'python-compile',\n command:\n 'python3 -c \"import compileall, sys; sys.exit(0 if compileall.compile_dir(\\'.\\', quiet=1, rx=__import__(\\'re\\').compile(r\\'(node_modules|\\\\.venv|\\\\.git|build|dist)\\')) else 1)\"',\n reason: 'Python project (no mypy detected)',\n };\n }\n return {\n kind: 'unknown',\n command: '',\n reason:\n 'no recognised project marker (tsconfig.json, package.json[typescript], Cargo.toml, go.mod, pyproject.toml, setup.py)',\n };\n}\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\n\nexport function createCompileCheckTool(\n config: t.LocalExecutionConfig = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput) => {\n const input = rawInput as {\n command?: string;\n timeout_ms?: number;\n };\n const cwd = getLocalCwd(config);\n const fs = getWorkspaceFS(config);\n const overrideCommand = input.command ?? config.compileCheck?.command;\n let detection: Detection;\n if (overrideCommand != null && overrideCommand.trim() !== '') {\n detection = {\n kind: 'unknown',\n command: overrideCommand,\n reason: 'explicit override',\n };\n } else {\n detection = await detect(cwd, fs);\n }\n\n if (detection.command === '') {\n const explainer = `compile_check: ${detection.reason}. Pass an explicit \\`command\\` (e.g. \\`npm run typecheck\\`) to override.`;\n return [\n explainer,\n {\n kind: detection.kind,\n ran: false,\n reason: detection.reason,\n cwd,\n },\n ];\n }\n\n // Codex P1 #21: route the resolved command through the same\n // safety gates the rest of the local engine uses. Without this\n // a host with `readOnly: true` (or relying on the destructive-\n // command guard) could be bypassed by passing a `command`\n // override to compile_check that performs writes/deletes.\n // Auto-detected commands (tsc/cargo/etc.) pass these gates\n // unchanged — the validation is only blocking for genuinely\n // mutating overrides.\n const validation = await validateBashCommand(detection.command, config);\n if (!validation.valid) {\n const explainer = `compile_check refused to run \\`${detection.command}\\`: ${validation.errors.join('; ')}`;\n return [\n explainer,\n {\n kind: detection.kind,\n ran: false,\n reason: validation.errors.join('; '),\n cwd,\n },\n ];\n }\n\n const timeoutMs =\n input.timeout_ms ??\n config.compileCheck?.timeoutMs ??\n DEFAULT_TIMEOUT_MS;\n const result = await spawnLocalProcess(\n config.shell ?? (process.platform === 'win32' ? 'bash.exe' : 'bash'),\n ['-lc', detection.command],\n {\n ...config,\n timeoutMs,\n maxOutputChars: config.maxOutputChars ?? 8000,\n }\n );\n\n const passed = result.exitCode === 0 && !result.timedOut;\n const headline = passed\n ? `compile_check (${detection.kind}) PASSED via \\`${detection.command}\\``\n : `compile_check (${detection.kind}) FAILED via \\`${detection.command}\\` ` +\n `(exit=${result.exitCode ?? 'unknown'}${result.timedOut ? ', timed_out=true' : ''})`;\n\n let body = '';\n if (result.stdout !== '') {\n body += `\\n\\nstdout:\\n${truncateLocalOutput(result.stdout, 4000)}`;\n }\n if (result.stderr !== '') {\n body += `\\n\\nstderr:\\n${truncateLocalOutput(result.stderr, 4000)}`;\n }\n if (result.fullOutputPath != null) {\n body += `\\n\\nfull_output_path: ${result.fullOutputPath}`;\n }\n const summary = `${headline}${body}\\n\\nworking_directory: ${cwd}\\nreason: ${detection.reason}`;\n\n return [\n summary,\n {\n kind: detection.kind,\n ran: true,\n passed,\n exit_code: result.exitCode,\n timed_out: result.timedOut,\n command: detection.command,\n cwd,\n },\n ];\n },\n {\n name: CompileCheckToolName,\n description:\n 'Run the project\\'s standard typecheck or lint pass and return its output. Auto-detects from project markers (tsconfig.json/package.json -> tsc; Cargo.toml -> cargo check; go.mod -> go vet; pyproject.toml -> mypy or py_compile). Pass `command` to override.',\n schema: CompileCheckSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport function createCompileCheckToolDefinition(): t.LCTool {\n return {\n name: CompileCheckToolName,\n description:\n 'Run the project\\'s standard typecheck or lint pass and return its output.',\n parameters: CompileCheckSchema,\n allowed_callers: ['direct', 'code_execution'],\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n toolType: 'builtin',\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAa,uBAAA;AAEb,MAAM,qBAAuC,WAAW;CACtD,MAAM;CACN,YAAY;EACV,SAAS;GACP,MAAM;GACN,aACE;EACJ;EACA,YAAY;GACV,MAAM;GACN,aACE;EACJ;CACF;AACF,CAAC;AAgBD,eAAe,WAAW,IAAiB,GAA6B;CACtE,IAAI;EACF,MAAM,GAAG,KAAK,CAAC;EACf,OAAO;CACT,SAAS,OAAO;EAGd,IAAI,8BAA8B,KAAK,GACrC,MAAM;EAER,OAAO;CACT;AACF;AAMA,eAAe,OAAO,KAAa,IAAqC;CACtE,IAAI,MAAM,WAAW,IAAI,QAAQ,KAAK,eAAe,CAAC,GACpD,OAAO;EACL,MAAM;EACN,SAAS;EACT,QAAQ;CACV;CAEF,IAAI,MAAM,WAAW,IAAI,QAAQ,KAAK,cAAc,CAAC;OAS/C,MARiB,GAClB,SAAS,QAAQ,KAAK,cAAc,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AQ;EACR,gBAAA;CACF,CACF;AACF;AAEA,SAAgB,mCAA6C;CAC3D,OAAO;EACL,MAAM;EACN,aACE;EACF,YAAY;EACZ,iBAAiB,CAAC,UAAU,gBAAgB;EAC5C,gBAAA;EACA,UAAU;CACZ;AACF"}
@@ -1,5 +1,6 @@
1
1
  import "../../common/enum.mjs";
2
2
  import "../../common/index.mjs";
3
+ import { withIntent } from "../intentArg.mjs";
3
4
  import { isWorkspaceClientTimeoutError } from "./workspaceFS.mjs";
4
5
  import { getSpawn, getWorkspaceFS, resolveWorkspacePathSafe, spawnLocalProcess, truncateLocalOutput } from "./LocalExecutionEngine.mjs";
5
6
  import { createCompileCheckTool, createCompileCheckToolDefinition } from "./CompileCheckTool.mjs";
@@ -29,7 +30,7 @@ const LocalEditFileToolName = "edit_file";
29
30
  const LocalGrepSearchToolName = "grep_search";
30
31
  const LocalGlobSearchToolName = "glob_search";
31
32
  const LocalListDirectoryToolName = "list_directory";
32
- const LocalReadFileToolSchema = {
33
+ const LocalReadFileToolSchema = withIntent({
33
34
  type: "object",
34
35
  properties: {
35
36
  path: {
@@ -46,8 +47,8 @@ const LocalReadFileToolSchema = {
46
47
  }
47
48
  },
48
49
  required: ["path"]
49
- };
50
- const LocalWriteFileToolSchema = {
50
+ });
51
+ const LocalWriteFileToolSchema = withIntent({
51
52
  type: "object",
52
53
  properties: {
53
54
  path: {
@@ -60,8 +61,8 @@ const LocalWriteFileToolSchema = {
60
61
  }
61
62
  },
62
63
  required: ["path", "content"]
63
- };
64
- const LocalEditFileToolSchema = {
64
+ });
65
+ const LocalEditFileToolSchema = withIntent({
65
66
  type: "object",
66
67
  properties: {
67
68
  path: {
@@ -90,8 +91,8 @@ const LocalEditFileToolSchema = {
90
91
  }
91
92
  },
92
93
  required: ["path"]
93
- };
94
- const LocalGrepSearchToolSchema = {
94
+ });
95
+ const LocalGrepSearchToolSchema = withIntent({
95
96
  type: "object",
96
97
  properties: {
97
98
  pattern: {
@@ -112,8 +113,8 @@ const LocalGrepSearchToolSchema = {
112
113
  }
113
114
  },
114
115
  required: ["pattern"]
115
- };
116
- const LocalGlobSearchToolSchema = {
116
+ });
117
+ const LocalGlobSearchToolSchema = withIntent({
117
118
  type: "object",
118
119
  properties: {
119
120
  pattern: {
@@ -130,14 +131,14 @@ const LocalGlobSearchToolSchema = {
130
131
  }
131
132
  },
132
133
  required: ["pattern"]
133
- };
134
- const LocalListDirectoryToolSchema = {
134
+ });
135
+ const LocalListDirectoryToolSchema = withIntent({
135
136
  type: "object",
136
137
  properties: { path: {
137
138
  type: "string",
138
139
  description: "Directory to list. Defaults to cwd."
139
140
  } }
140
- };
141
+ });
141
142
  function lineWindow(content, offset, limit) {
142
143
  const start = Math.max((offset ?? 1) - 1, 0);
143
144
  if (limit == null || limit <= 0) {
@@ -1 +1 @@
1
- {"version":3,"file":"LocalCodingTools.mjs","names":["input"],"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;AAEb,MAAa,0BAA4C;CACvD,MAAM;CACN,YAAY;EACV,MAAM;GACJ,MAAM;GACN,aACE;EACJ;EACA,QAAQ;GACN,MAAM;GACN,aAAa;EACf;EACA,OAAO;GACL,MAAM;GACN,aAAa;EACf;CACF;CACA,UAAU,CAAC,MAAM;AACnB;AAEA,MAAa,2BAA6C;CACxD,MAAM;CACN,YAAY;EACV,MAAM;GACJ,MAAM;GACN,aACE;EACJ;EACA,SAAS;GACP,MAAM;GACN,aAAa;EACf;CACF;CACA,UAAU,CAAC,QAAQ,SAAS;AAC9B;AAEA,MAAa,0BAA4C;CACvD,MAAM;CACN,YAAY;EACV,MAAM;GACJ,MAAM;GACN,aACE;EACJ;EACA,UAAU;GACR,MAAM;GACN,aAAa;EACf;EACA,UAAU;GACR,MAAM;GACN,aAAa;EACf;EACA,OAAO;GACL,MAAM;GACN,aACE;GACF,OAAO;IACL,MAAM;IACN,YAAY;KACV,UAAU,EAAE,MAAM,SAAS;KAC3B,UAAU,EAAE,MAAM,SAAS;IAC7B;IACA,UAAU,CAAC,YAAY,UAAU;GACnC;EACF;CACF;CACA,UAAU,CAAC,MAAM;AACnB;AAEA,MAAa,4BAA8C;CACzD,MAAM;CACN,YAAY;EACV,SAAS;GACP,MAAM;GACN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,8DACA,yBACF;EACA,eACE,yBACA,6CACA,yBACF;EACA,eACE,4BACA,oDACA,4BACF;EACA,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.mjs","names":["input"],"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 { isWorkspaceClientTimeoutError } from './workspaceFS';\nimport { applyEdit, locateEdit } from './editStrategies';\nimport { decodeFile, encodeFile } from './textEncoding';\nimport { runPostEditSyntaxCheck } from './syntaxCheck';\nimport { withIntent } from '@/tools/intentArg';\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 = withIntent({\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 = withIntent({\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 = withIntent({\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 = withIntent({\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 = withIntent({\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 = withIntent({\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":";;;;;;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,WAAW,MACX,UACF,CAAC,CACH;AACF"}
@@ -1,11 +1,11 @@
1
- import { nodeWorkspaceFS } from "./workspaceFS.mjs";
2
1
  import { bashAstFindingsToErrors, runBashAstChecks } from "./bashAst.mjs";
2
+ import { nodeWorkspaceFS } from "./workspaceFS.mjs";
3
3
  import { isAbsolute, relative, resolve } from "path";
4
- import { mkdir, realpath, rm, writeFile } from "fs/promises";
5
4
  import { tmpdir } from "os";
6
5
  import { spawn } from "child_process";
7
6
  import { createWriteStream } from "fs";
8
7
  import { createHash, randomUUID } from "crypto";
8
+ import { mkdir, realpath, rm, writeFile } from "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 +1 @@
1
- {"version":3,"file":"ptcTimeout.mjs","names":[],"sources":["../../../src/tools/ptcTimeout.ts"],"sourcesContent":["import { EnvVar } from '@/common';\n\nexport const DEFAULT_CODE_API_RUN_TIMEOUT_MS = 15_000;\nexport const MIN_CODE_API_RUN_TIMEOUT_MS = 1_000;\nexport const MAX_CODE_API_RUN_TIMEOUT_SCHEMA_MS = 300_000;\n\ntype TimeoutSchema = {\n type: 'integer';\n minimum: number;\n maximum: number;\n default: number;\n description: string;\n};\n\nexport type ProgrammaticToolCallingJsonSchema = {\n type: 'object';\n properties: {\n code: {\n type: 'string';\n minLength: number;\n description: string;\n };\n timeout: TimeoutSchema;\n };\n required: readonly ['code'];\n};\n\nfunction normalizeTimeoutMs(value: number | undefined): number | undefined {\n if (value == null || !Number.isFinite(value)) {\n return undefined;\n }\n\n return Math.max(MIN_CODE_API_RUN_TIMEOUT_MS, Math.floor(value));\n}\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (value == null || value.trim() === '') {\n return undefined;\n }\n\n return normalizeTimeoutMs(Number(value));\n}\n\nfunction formatTimeout(timeoutMs: number): string {\n return timeoutMs % 1000 === 0\n ? `${timeoutMs / 1000} seconds`\n : `${timeoutMs} milliseconds`;\n}\n\nexport function resolveCodeApiRunTimeoutMs(override?: number): number {\n return (\n normalizeTimeoutMs(override) ??\n parseTimeoutMs(process.env[EnvVar.CODE_API_RUN_TIMEOUT_MS]) ??\n DEFAULT_CODE_API_RUN_TIMEOUT_MS\n );\n}\n\nexport function clampCodeApiRunTimeoutMs(\n timeoutMs: number | undefined,\n maxRunTimeoutMs = resolveCodeApiRunTimeoutMs()\n): number {\n const normalizedMaxRunTimeoutMs =\n normalizeTimeoutMs(maxRunTimeoutMs) ?? DEFAULT_CODE_API_RUN_TIMEOUT_MS;\n const normalizedTimeoutMs = normalizeTimeoutMs(timeoutMs);\n\n if (normalizedTimeoutMs == null) {\n return normalizedMaxRunTimeoutMs;\n }\n\n return Math.min(normalizedTimeoutMs, normalizedMaxRunTimeoutMs);\n}\n\nexport function createCodeApiRunTimeoutSchema(\n maxRunTimeoutMs = resolveCodeApiRunTimeoutMs()\n): TimeoutSchema {\n const normalizedMaxRunTimeoutMs =\n normalizeTimeoutMs(maxRunTimeoutMs) ?? DEFAULT_CODE_API_RUN_TIMEOUT_MS;\n const normalizedSchemaMaxRunTimeoutMs = Math.max(\n normalizedMaxRunTimeoutMs,\n MAX_CODE_API_RUN_TIMEOUT_SCHEMA_MS\n );\n const formattedTimeout = formatTimeout(normalizedMaxRunTimeoutMs);\n const formattedSchemaMaxTimeout = formatTimeout(\n normalizedSchemaMaxRunTimeoutMs\n );\n\n return {\n type: 'integer',\n minimum: MIN_CODE_API_RUN_TIMEOUT_MS,\n maximum: normalizedSchemaMaxRunTimeoutMs,\n default: normalizedMaxRunTimeoutMs,\n description:\n 'Maximum wall-clock time in milliseconds for one sandbox run or replay iteration. ' +\n 'This is not the total multi-round-trip task budget. ' +\n `Default: ${formattedTimeout}. ` +\n 'Accepted values above the configured cap are clamped before execution. ' +\n `Schema max: ${formattedSchemaMaxTimeout}. Configured cap: ${formattedTimeout}.`,\n };\n}\n"],"mappings":";;AAGA,MAAa,8BAA8B;AAC3C,MAAa,qCAAqC;AAuBlD,SAAS,mBAAmB,OAA+C;CACzE,IAAI,SAAS,QAAQ,CAAC,OAAO,SAAS,KAAK,GACzC;CAGF,OAAO,KAAK,IAAI,6BAA6B,KAAK,MAAM,KAAK,CAAC;AAChE;AAEA,SAAS,eAAe,OAA+C;CACrE,IAAI,SAAS,QAAQ,MAAM,KAAK,MAAM,IACpC;CAGF,OAAO,mBAAmB,OAAO,KAAK,CAAC;AACzC;AAEA,SAAS,cAAc,WAA2B;CAChD,OAAO,YAAY,QAAS,IACxB,GAAG,YAAY,IAAK,YACpB,GAAG,UAAU;AACnB;AAEA,SAAgB,2BAA2B,UAA2B;CACpE,OACE,mBAAmB,QAAQ,KAC3B,eAAe,QAAQ,IAAA,0BAAmC,KAAA;AAG9D;AAEA,SAAgB,yBACd,WACA,kBAAkB,2BAA2B,GACrC;CACR,MAAM,4BACJ,mBAAmB,eAAe,KAAA;CACpC,MAAM,sBAAsB,mBAAmB,SAAS;CAExD,IAAI,uBAAuB,MACzB,OAAO;CAGT,OAAO,KAAK,IAAI,qBAAqB,yBAAyB;AAChE;AAEA,SAAgB,8BACd,kBAAkB,2BAA2B,GAC9B;CACf,MAAM,4BACJ,mBAAmB,eAAe,KAAA;CACpC,MAAM,kCAAkC,KAAK,IAC3C,2BACA,kCACF;CACA,MAAM,mBAAmB,cAAc,yBAAyB;CAKhE,OAAO;EACL,MAAM;EACN,SAAS;EACT,SAAS;EACT,SAAS;EACT,aACE,iJAEY,iBAAiB,uFAZC,cAChC,+BAayC,EAAE,oBAAoB,iBAAiB;CAClF;AACF"}
1
+ {"version":3,"file":"ptcTimeout.mjs","names":[],"sources":["../../../src/tools/ptcTimeout.ts"],"sourcesContent":["import type { JsonSchemaType } from '@/types';\nimport { EnvVar } from '@/common';\n\nexport const DEFAULT_CODE_API_RUN_TIMEOUT_MS = 15_000;\nexport const MIN_CODE_API_RUN_TIMEOUT_MS = 1_000;\nexport const MAX_CODE_API_RUN_TIMEOUT_SCHEMA_MS = 300_000;\n\ntype TimeoutSchema = {\n type: 'integer';\n minimum: number;\n maximum: number;\n default: number;\n description: string;\n};\n\nexport type ProgrammaticToolCallingJsonSchema = {\n type: 'object';\n properties: {\n intent: JsonSchemaType;\n code: {\n type: 'string';\n minLength: number;\n description: string;\n };\n timeout: TimeoutSchema;\n };\n required: readonly ['code'];\n};\n\nfunction normalizeTimeoutMs(value: number | undefined): number | undefined {\n if (value == null || !Number.isFinite(value)) {\n return undefined;\n }\n\n return Math.max(MIN_CODE_API_RUN_TIMEOUT_MS, Math.floor(value));\n}\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (value == null || value.trim() === '') {\n return undefined;\n }\n\n return normalizeTimeoutMs(Number(value));\n}\n\nfunction formatTimeout(timeoutMs: number): string {\n return timeoutMs % 1000 === 0\n ? `${timeoutMs / 1000} seconds`\n : `${timeoutMs} milliseconds`;\n}\n\nexport function resolveCodeApiRunTimeoutMs(override?: number): number {\n return (\n normalizeTimeoutMs(override) ??\n parseTimeoutMs(process.env[EnvVar.CODE_API_RUN_TIMEOUT_MS]) ??\n DEFAULT_CODE_API_RUN_TIMEOUT_MS\n );\n}\n\nexport function clampCodeApiRunTimeoutMs(\n timeoutMs: number | undefined,\n maxRunTimeoutMs = resolveCodeApiRunTimeoutMs()\n): number {\n const normalizedMaxRunTimeoutMs =\n normalizeTimeoutMs(maxRunTimeoutMs) ?? DEFAULT_CODE_API_RUN_TIMEOUT_MS;\n const normalizedTimeoutMs = normalizeTimeoutMs(timeoutMs);\n\n if (normalizedTimeoutMs == null) {\n return normalizedMaxRunTimeoutMs;\n }\n\n return Math.min(normalizedTimeoutMs, normalizedMaxRunTimeoutMs);\n}\n\nexport function createCodeApiRunTimeoutSchema(\n maxRunTimeoutMs = resolveCodeApiRunTimeoutMs()\n): TimeoutSchema {\n const normalizedMaxRunTimeoutMs =\n normalizeTimeoutMs(maxRunTimeoutMs) ?? DEFAULT_CODE_API_RUN_TIMEOUT_MS;\n const normalizedSchemaMaxRunTimeoutMs = Math.max(\n normalizedMaxRunTimeoutMs,\n MAX_CODE_API_RUN_TIMEOUT_SCHEMA_MS\n );\n const formattedTimeout = formatTimeout(normalizedMaxRunTimeoutMs);\n const formattedSchemaMaxTimeout = formatTimeout(\n normalizedSchemaMaxRunTimeoutMs\n );\n\n return {\n type: 'integer',\n minimum: MIN_CODE_API_RUN_TIMEOUT_MS,\n maximum: normalizedSchemaMaxRunTimeoutMs,\n default: normalizedMaxRunTimeoutMs,\n description:\n 'Maximum wall-clock time in milliseconds for one sandbox run or replay iteration. ' +\n 'This is not the total multi-round-trip task budget. ' +\n `Default: ${formattedTimeout}. ` +\n 'Accepted values above the configured cap are clamped before execution. ' +\n `Schema max: ${formattedSchemaMaxTimeout}. Configured cap: ${formattedTimeout}.`,\n };\n}\n"],"mappings":";;AAIA,MAAa,8BAA8B;AAC3C,MAAa,qCAAqC;AAwBlD,SAAS,mBAAmB,OAA+C;CACzE,IAAI,SAAS,QAAQ,CAAC,OAAO,SAAS,KAAK,GACzC;CAGF,OAAO,KAAK,IAAI,6BAA6B,KAAK,MAAM,KAAK,CAAC;AAChE;AAEA,SAAS,eAAe,OAA+C;CACrE,IAAI,SAAS,QAAQ,MAAM,KAAK,MAAM,IACpC;CAGF,OAAO,mBAAmB,OAAO,KAAK,CAAC;AACzC;AAEA,SAAS,cAAc,WAA2B;CAChD,OAAO,YAAY,QAAS,IACxB,GAAG,YAAY,IAAK,YACpB,GAAG,UAAU;AACnB;AAEA,SAAgB,2BAA2B,UAA2B;CACpE,OACE,mBAAmB,QAAQ,KAC3B,eAAe,QAAQ,IAAA,0BAAmC,KAAA;AAG9D;AAEA,SAAgB,yBACd,WACA,kBAAkB,2BAA2B,GACrC;CACR,MAAM,4BACJ,mBAAmB,eAAe,KAAA;CACpC,MAAM,sBAAsB,mBAAmB,SAAS;CAExD,IAAI,uBAAuB,MACzB,OAAO;CAGT,OAAO,KAAK,IAAI,qBAAqB,yBAAyB;AAChE;AAEA,SAAgB,8BACd,kBAAkB,2BAA2B,GAC9B;CACf,MAAM,4BACJ,mBAAmB,eAAe,KAAA;CACpC,MAAM,kCAAkC,KAAK,IAC3C,2BACA,kCACF;CACA,MAAM,mBAAmB,cAAc,yBAAyB;CAKhE,OAAO;EACL,MAAM;EACN,SAAS;EACT,SAAS;EACT,SAAS;EACT,aACE,iJAEY,iBAAiB,uFAZC,cAChC,+BAayC,EAAE,oBAAoB,iBAAiB;CAClF;AACF"}
@@ -1,3 +1,4 @@
1
+ import { INTENT_PROPERTY } from "../intentArg.mjs";
1
2
  //#region src/tools/search/schema.ts
2
3
  let DATE_RANGE = /* @__PURE__ */ function(DATE_RANGE) {
3
4
  DATE_RANGE["PAST_HOUR"] = "h";
@@ -63,6 +64,7 @@ const newsSchema = {
63
64
  const WebSearchToolSchema = {
64
65
  type: "object",
65
66
  properties: {
67
+ intent: { ...INTENT_PROPERTY },
66
68
  query: querySchema,
67
69
  date: dateSchema,
68
70
  country: countrySchema,
@@ -1 +1 @@
1
- {"version":3,"file":"schema.mjs","names":[],"sources":["../../../../src/tools/search/schema.ts"],"sourcesContent":["export enum DATE_RANGE {\n PAST_HOUR = 'h',\n PAST_24_HOURS = 'd',\n PAST_WEEK = 'w',\n PAST_MONTH = 'm',\n PAST_YEAR = 'y',\n}\n\nexport const DEFAULT_QUERY_DESCRIPTION = `\nGUIDELINES:\n- Start broad, then narrow: Begin with key concepts, then refine with specifics\n- Think like sources: Use terminology experts would use in the field\n- Consider perspective: Frame queries from different viewpoints for better results\n- Quality over quantity: A precise 3-4 word query often beats lengthy sentences\n\nTECHNIQUES (combine for power searches):\n- EXACT PHRASES: Use quotes (\"climate change report\")\n- EXCLUDE TERMS: Use minus to remove unwanted results (-wikipedia)\n- SITE-SPECIFIC: Restrict to websites (site:edu research)\n- FILETYPE: Find specific documents (filetype:pdf study)\n- OR OPERATOR: Find alternatives (electric OR hybrid cars)\n- DATE RANGE: Recent information (data after:2020)\n- WILDCARDS: Use * for unknown terms (how to * bread)\n- SPECIFIC QUESTIONS: Use who/what/when/where/why/how\n- DOMAIN TERMS: Include technical terminology for specialized topics\n- CONCISE TERMS: Prioritize keywords over sentences\n`.trim();\n\nexport const DEFAULT_COUNTRY_DESCRIPTION =\n `Country code to localize search results.\nUse standard 2-letter country codes: \"us\", \"uk\", \"ca\", \"de\", \"fr\", \"jp\", \"br\", etc.\nProvide this when the search should return results specific to a particular country.\nExamples:\n- \"us\" for United States (default)\n- \"de\" for Germany\n- \"in\" for India\n`.trim();\n\nexport const querySchema = {\n type: 'string',\n description: DEFAULT_QUERY_DESCRIPTION,\n} as const;\n\nexport const dateSchema = {\n type: 'string',\n enum: Object.values(DATE_RANGE),\n description: 'Date range for search results.',\n} as const;\n\nexport const countrySchema = {\n type: 'string',\n description: DEFAULT_COUNTRY_DESCRIPTION,\n} as const;\n\nexport const imagesSchema = {\n type: 'boolean',\n description: 'Whether to also run an image search.',\n} as const;\n\nexport const videosSchema = {\n type: 'boolean',\n description: 'Whether to also run a video search.',\n} as const;\n\nexport const newsSchema = {\n type: 'boolean',\n description: 'Whether to also run a news search.',\n} as const;\n\n/** Combined web search tool schema with all properties */\nexport const WebSearchToolSchema = {\n type: 'object',\n properties: {\n query: querySchema,\n date: dateSchema,\n country: countrySchema,\n images: imagesSchema,\n videos: videosSchema,\n news: newsSchema,\n },\n required: ['query'],\n} as const;\n\nexport const WebSearchToolName = 'web_search';\n\nexport const WebSearchToolDescription = `Real-time search. Results have required citation anchors.\n\nNote: Use ONCE per reply unless instructed otherwise.\n\nAnchors:\n- \\\\ue202turnXtypeY\n- X = turn idx, type = 'search' | 'news' | 'image' | 'ref', Y = item idx\n\nSpecial Markers:\n- \\\\ue203...\\\\ue204 — highlight start/end of cited text (for Standalone or Group citations)\n- \\\\ue200...\\\\ue201 — group block (e.g. \\\\ue200\\\\ue202turn0search1\\\\ue202turn0news2\\\\ue201)\n\n**CITE EVERY NON-OBVIOUS FACT/QUOTE:**\nUse anchor marker(s) immediately after the statement:\n- Standalone: \"Pure functions produce same output. \\\\ue202turn0search0\"\n- Standalone (multiple): \"Today's News \\\\ue202turn0search0\\\\ue202turn0news0\"\n- Highlight: \"\\\\ue203Highlight text.\\\\ue204\\\\ue202turn0news1\"\n- Group: \"Sources. \\\\ue200\\\\ue202turn0search0\\\\ue202turn0news1\\\\ue201\"\n- Group Highlight: \"\\\\ue203Highlight for group.\\\\ue204 \\\\ue200\\\\ue202turn0search0\\\\ue202turn0news1\\\\ue201\"\n- Image: \"See photo \\\\ue202turn0image0.\"\n\n**NEVER use markdown links, [1], or footnotes. CITE ONLY with anchors provided.**`;\n\nexport const WebSearchToolDefinition = {\n name: WebSearchToolName,\n description: WebSearchToolDescription,\n schema: WebSearchToolSchema,\n} as const;\n"],"mappings":";AAAA,IAAY,aAAL,yBAAA,YAAA;CACL,WAAA,eAAA;CACA,WAAA,mBAAA;CACA,WAAA,eAAA;CACA,WAAA,gBAAA;CACA,WAAA,eAAA;;AACF,EAAA,CAAA,CAAA;AAEA,MAAa,4BAA4B;;;;;;;;;;;;;;;;;;EAkBvC,KAAK;AAEP,MAAa,8BACX;;;;;;;EAOA,KAAK;AAEP,MAAa,cAAc;CACzB,MAAM;CACN,aAAa;AACf;AAEA,MAAa,aAAa;CACxB,MAAM;CACN,MAAM,OAAO,OAAO,UAAU;CAC9B,aAAa;AACf;AAEA,MAAa,gBAAgB;CAC3B,MAAM;CACN,aAAa;AACf;AAEA,MAAa,eAAe;CAC1B,MAAM;CACN,aAAa;AACf;AAEA,MAAa,eAAe;CAC1B,MAAM;CACN,aAAa;AACf;AAEA,MAAa,aAAa;CACxB,MAAM;CACN,aAAa;AACf;;AAGA,MAAa,sBAAsB;CACjC,MAAM;CACN,YAAY;EACV,OAAO;EACP,MAAM;EACN,SAAS;EACT,QAAQ;EACR,QAAQ;EACR,MAAM;CACR;CACA,UAAU,CAAC,OAAO;AACpB;AAEA,MAAa,oBAAoB;AAEjC,MAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;;AAuBxC,MAAa,0BAA0B;CACrC,MAAM;CACN,aAAa;CACb,QAAQ;AACV"}
1
+ {"version":3,"file":"schema.mjs","names":[],"sources":["../../../../src/tools/search/schema.ts"],"sourcesContent":["import { INTENT_PROPERTY } from '@/tools/intentArg';\n\nexport enum DATE_RANGE {\n PAST_HOUR = 'h',\n PAST_24_HOURS = 'd',\n PAST_WEEK = 'w',\n PAST_MONTH = 'm',\n PAST_YEAR = 'y',\n}\n\nexport const DEFAULT_QUERY_DESCRIPTION = `\nGUIDELINES:\n- Start broad, then narrow: Begin with key concepts, then refine with specifics\n- Think like sources: Use terminology experts would use in the field\n- Consider perspective: Frame queries from different viewpoints for better results\n- Quality over quantity: A precise 3-4 word query often beats lengthy sentences\n\nTECHNIQUES (combine for power searches):\n- EXACT PHRASES: Use quotes (\"climate change report\")\n- EXCLUDE TERMS: Use minus to remove unwanted results (-wikipedia)\n- SITE-SPECIFIC: Restrict to websites (site:edu research)\n- FILETYPE: Find specific documents (filetype:pdf study)\n- OR OPERATOR: Find alternatives (electric OR hybrid cars)\n- DATE RANGE: Recent information (data after:2020)\n- WILDCARDS: Use * for unknown terms (how to * bread)\n- SPECIFIC QUESTIONS: Use who/what/when/where/why/how\n- DOMAIN TERMS: Include technical terminology for specialized topics\n- CONCISE TERMS: Prioritize keywords over sentences\n`.trim();\n\nexport const DEFAULT_COUNTRY_DESCRIPTION =\n `Country code to localize search results.\nUse standard 2-letter country codes: \"us\", \"uk\", \"ca\", \"de\", \"fr\", \"jp\", \"br\", etc.\nProvide this when the search should return results specific to a particular country.\nExamples:\n- \"us\" for United States (default)\n- \"de\" for Germany\n- \"in\" for India\n`.trim();\n\nexport const querySchema = {\n type: 'string',\n description: DEFAULT_QUERY_DESCRIPTION,\n} as const;\n\nexport const dateSchema = {\n type: 'string',\n enum: Object.values(DATE_RANGE),\n description: 'Date range for search results.',\n} as const;\n\nexport const countrySchema = {\n type: 'string',\n description: DEFAULT_COUNTRY_DESCRIPTION,\n} as const;\n\nexport const imagesSchema = {\n type: 'boolean',\n description: 'Whether to also run an image search.',\n} as const;\n\nexport const videosSchema = {\n type: 'boolean',\n description: 'Whether to also run a video search.',\n} as const;\n\nexport const newsSchema = {\n type: 'boolean',\n description: 'Whether to also run a news search.',\n} as const;\n\n/** Combined web search tool schema with all properties */\nexport const WebSearchToolSchema = {\n type: 'object',\n properties: {\n intent: { ...INTENT_PROPERTY },\n query: querySchema,\n date: dateSchema,\n country: countrySchema,\n images: imagesSchema,\n videos: videosSchema,\n news: newsSchema,\n },\n required: ['query'],\n} as const;\n\nexport const WebSearchToolName = 'web_search';\n\nexport const WebSearchToolDescription = `Real-time search. Results have required citation anchors.\n\nNote: Use ONCE per reply unless instructed otherwise.\n\nAnchors:\n- \\\\ue202turnXtypeY\n- X = turn idx, type = 'search' | 'news' | 'image' | 'ref', Y = item idx\n\nSpecial Markers:\n- \\\\ue203...\\\\ue204 — highlight start/end of cited text (for Standalone or Group citations)\n- \\\\ue200...\\\\ue201 — group block (e.g. \\\\ue200\\\\ue202turn0search1\\\\ue202turn0news2\\\\ue201)\n\n**CITE EVERY NON-OBVIOUS FACT/QUOTE:**\nUse anchor marker(s) immediately after the statement:\n- Standalone: \"Pure functions produce same output. \\\\ue202turn0search0\"\n- Standalone (multiple): \"Today's News \\\\ue202turn0search0\\\\ue202turn0news0\"\n- Highlight: \"\\\\ue203Highlight text.\\\\ue204\\\\ue202turn0news1\"\n- Group: \"Sources. \\\\ue200\\\\ue202turn0search0\\\\ue202turn0news1\\\\ue201\"\n- Group Highlight: \"\\\\ue203Highlight for group.\\\\ue204 \\\\ue200\\\\ue202turn0search0\\\\ue202turn0news1\\\\ue201\"\n- Image: \"See photo \\\\ue202turn0image0.\"\n\n**NEVER use markdown links, [1], or footnotes. CITE ONLY with anchors provided.**`;\n\nexport const WebSearchToolDefinition = {\n name: WebSearchToolName,\n description: WebSearchToolDescription,\n schema: WebSearchToolSchema,\n} as const;\n"],"mappings":";;AAEA,IAAY,aAAL,yBAAA,YAAA;CACL,WAAA,eAAA;CACA,WAAA,mBAAA;CACA,WAAA,eAAA;CACA,WAAA,gBAAA;CACA,WAAA,eAAA;;AACF,EAAA,CAAA,CAAA;AAEA,MAAa,4BAA4B;;;;;;;;;;;;;;;;;;EAkBvC,KAAK;AAEP,MAAa,8BACX;;;;;;;EAOA,KAAK;AAEP,MAAa,cAAc;CACzB,MAAM;CACN,aAAa;AACf;AAEA,MAAa,aAAa;CACxB,MAAM;CACN,MAAM,OAAO,OAAO,UAAU;CAC9B,aAAa;AACf;AAEA,MAAa,gBAAgB;CAC3B,MAAM;CACN,aAAa;AACf;AAEA,MAAa,eAAe;CAC1B,MAAM;CACN,aAAa;AACf;AAEA,MAAa,eAAe;CAC1B,MAAM;CACN,aAAa;AACf;AAEA,MAAa,aAAa;CACxB,MAAM;CACN,aAAa;AACf;;AAGA,MAAa,sBAAsB;CACjC,MAAM;CACN,YAAY;EACV,QAAQ,EAAE,GAAG,gBAAgB;EAC7B,OAAO;EACP,MAAM;EACN,SAAS;EACT,QAAQ;EACR,QAAQ;EACR,MAAM;CACR;CACA,UAAU,CAAC,OAAO;AACpB;AAEA,MAAa,oBAAoB;AAEjC,MAAa,2BAA2B;;;;;;;;;;;;;;;;;;;;;;AAuBxC,MAAa,0BAA0B;CACrC,MAAM;CACN,aAAa;CACb,QAAQ;AACV"}
@@ -2,6 +2,7 @@ import "../../common/enum.mjs";
2
2
  import "../../common/index.mjs";
3
3
  import { createDefaultLogger } from "./utils.mjs";
4
4
  import { formatResultsForLLM } from "./format.mjs";
5
+ import { INTENT_PROPERTY } from "../intentArg.mjs";
5
6
  import { WebSearchToolDescription, WebSearchToolName, countrySchema, dateSchema, imagesSchema, newsSchema, querySchema, videosSchema } from "./schema.mjs";
6
7
  import { createSearchAPI, createSourceProcessor } from "./search.mjs";
7
8
  import { createKeenableScraper } from "./keenable-scraper.mjs";
@@ -14,6 +15,29 @@ import { createReranker } from "./rerankers.mjs";
14
15
  import { tool } from "@langchain/core/tools";
15
16
  //#region src/tools/search/tool.ts
16
17
  /**
18
+ * Settled label for a `web_search` call's intent (see `intentArg.ts`).
19
+ *
20
+ * Counts the result kinds `formatResultsForLLM` actually renders —
21
+ * `references` only tracks links embedded in extracted highlights, so it
22
+ * undercounts ordinary results and can overcount when one highlight embeds
23
+ * several links.
24
+ *
25
+ * A caught provider or processing failure is reported through `data.error`
26
+ * while the tool still returns NORMALLY, so that case must author its own
27
+ * label: the `ToolMessage` carries success status, so without an authored
28
+ * outcome the in-flight intent ("Searching…") would stand as the settled
29
+ * label and present a failed search as an ordinary one.
30
+ *
31
+ * Returns undefined for a genuine zero-result search, leaving the
32
+ * model-authored intent to stand unchanged as the label.
33
+ */
34
+ function resolveSearchOutcome(data, query) {
35
+ if (data.error != null && data.error !== "") return `Search failed for "${query}"`;
36
+ const count = (data.organic?.length ?? 0) + (data.topStories?.length ?? 0) + (data.news?.length ?? 0) + (data.images?.length ?? 0) + (data.videos?.length ?? 0) + (data.places?.length ?? 0) + (data.peopleAlsoAsk?.length ?? 0) + (data.knowledgeGraph != null ? 1 : 0) + (data.answerBox != null ? 1 : 0);
37
+ if (count === 0) return;
38
+ return `Found ${count} result${count === 1 ? "" : "s"} for "${query}"`;
39
+ }
40
+ /**
17
41
  * Executes parallel searches and merges the results,
18
42
  * deduplicating top stories by link
19
43
  */
@@ -173,7 +197,11 @@ function createTool({ schema, search, maxOutputChars, onSearchResults: _onSearch
173
197
  ...searchResult,
174
198
  references
175
199
  };
176
- return [output, { ["web_search"]: data }];
200
+ const outcome = resolveSearchOutcome(data, query);
201
+ return [output, {
202
+ ["web_search"]: data,
203
+ ...outcome != null && { outcome }
204
+ }];
177
205
  }, {
178
206
  name: WebSearchToolName,
179
207
  description: WebSearchToolDescription,
@@ -189,6 +217,7 @@ const createSearchTool = (config = {}) => {
189
217
  safeSearch: config.safeSearch !== 0
190
218
  } : tavilySearchOptions;
191
219
  const schemaProperties = {
220
+ intent: { ...INTENT_PROPERTY },
192
221
  query: querySchema,
193
222
  date: dateSchema,
194
223
  images: imagesSchema,
@@ -293,6 +322,6 @@ const createSearchTool = (config = {}) => {
293
322
  });
294
323
  };
295
324
  //#endregion
296
- export { createSearchTool, executeParallelSearches };
325
+ export { createSearchTool, executeParallelSearches, resolveSearchOutcome };
297
326
 
298
327
  //# sourceMappingURL=tool.mjs.map