@librechat/agents 3.1.77 → 3.1.78-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/dist/cjs/common/enum.cjs +54 -0
  2. package/dist/cjs/common/enum.cjs.map +1 -1
  3. package/dist/cjs/graphs/Graph.cjs +148 -4
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs +291 -0
  6. package/dist/cjs/hooks/createWorkspacePolicyHook.cjs.map +1 -0
  7. package/dist/cjs/main.cjs +90 -0
  8. package/dist/cjs/main.cjs.map +1 -1
  9. package/dist/cjs/messages/anthropicToolCache.cjs +102 -0
  10. package/dist/cjs/messages/anthropicToolCache.cjs.map +1 -0
  11. package/dist/cjs/messages/prune.cjs +27 -0
  12. package/dist/cjs/messages/prune.cjs.map +1 -1
  13. package/dist/cjs/messages/recency.cjs +99 -0
  14. package/dist/cjs/messages/recency.cjs.map +1 -0
  15. package/dist/cjs/run.cjs +30 -0
  16. package/dist/cjs/run.cjs.map +1 -1
  17. package/dist/cjs/summarization/node.cjs +100 -6
  18. package/dist/cjs/summarization/node.cjs.map +1 -1
  19. package/dist/cjs/tools/ToolNode.cjs +635 -23
  20. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  21. package/dist/cjs/tools/local/CompileCheckTool.cjs +227 -0
  22. package/dist/cjs/tools/local/CompileCheckTool.cjs.map +1 -0
  23. package/dist/cjs/tools/local/FileCheckpointer.cjs +90 -0
  24. package/dist/cjs/tools/local/FileCheckpointer.cjs.map +1 -0
  25. package/dist/cjs/tools/local/LocalCodingTools.cjs +1098 -0
  26. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -0
  27. package/dist/cjs/tools/local/LocalExecutionEngine.cjs +1042 -0
  28. package/dist/cjs/tools/local/LocalExecutionEngine.cjs.map +1 -0
  29. package/dist/cjs/tools/local/LocalExecutionTools.cjs +122 -0
  30. package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -0
  31. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +453 -0
  32. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -0
  33. package/dist/cjs/tools/local/attachments.cjs +183 -0
  34. package/dist/cjs/tools/local/attachments.cjs.map +1 -0
  35. package/dist/cjs/tools/local/bashAst.cjs +129 -0
  36. package/dist/cjs/tools/local/bashAst.cjs.map +1 -0
  37. package/dist/cjs/tools/local/editStrategies.cjs +188 -0
  38. package/dist/cjs/tools/local/editStrategies.cjs.map +1 -0
  39. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs +141 -0
  40. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -0
  41. package/dist/cjs/tools/local/syntaxCheck.cjs +182 -0
  42. package/dist/cjs/tools/local/syntaxCheck.cjs.map +1 -0
  43. package/dist/cjs/tools/local/textEncoding.cjs +30 -0
  44. package/dist/cjs/tools/local/textEncoding.cjs.map +1 -0
  45. package/dist/cjs/tools/local/workspaceFS.cjs +51 -0
  46. package/dist/cjs/tools/local/workspaceFS.cjs.map +1 -0
  47. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +1 -0
  48. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  49. package/dist/esm/common/enum.mjs +53 -1
  50. package/dist/esm/common/enum.mjs.map +1 -1
  51. package/dist/esm/graphs/Graph.mjs +149 -5
  52. package/dist/esm/graphs/Graph.mjs.map +1 -1
  53. package/dist/esm/hooks/createWorkspacePolicyHook.mjs +289 -0
  54. package/dist/esm/hooks/createWorkspacePolicyHook.mjs.map +1 -0
  55. package/dist/esm/main.mjs +17 -2
  56. package/dist/esm/main.mjs.map +1 -1
  57. package/dist/esm/messages/anthropicToolCache.mjs +99 -0
  58. package/dist/esm/messages/anthropicToolCache.mjs.map +1 -0
  59. package/dist/esm/messages/prune.mjs +26 -1
  60. package/dist/esm/messages/prune.mjs.map +1 -1
  61. package/dist/esm/messages/recency.mjs +97 -0
  62. package/dist/esm/messages/recency.mjs.map +1 -0
  63. package/dist/esm/run.mjs +30 -0
  64. package/dist/esm/run.mjs.map +1 -1
  65. package/dist/esm/summarization/node.mjs +100 -6
  66. package/dist/esm/summarization/node.mjs.map +1 -1
  67. package/dist/esm/tools/ToolNode.mjs +635 -23
  68. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  69. package/dist/esm/tools/local/CompileCheckTool.mjs +223 -0
  70. package/dist/esm/tools/local/CompileCheckTool.mjs.map +1 -0
  71. package/dist/esm/tools/local/FileCheckpointer.mjs +87 -0
  72. package/dist/esm/tools/local/FileCheckpointer.mjs.map +1 -0
  73. package/dist/esm/tools/local/LocalCodingTools.mjs +1075 -0
  74. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -0
  75. package/dist/esm/tools/local/LocalExecutionEngine.mjs +1022 -0
  76. package/dist/esm/tools/local/LocalExecutionEngine.mjs.map +1 -0
  77. package/dist/esm/tools/local/LocalExecutionTools.mjs +117 -0
  78. package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -0
  79. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +448 -0
  80. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -0
  81. package/dist/esm/tools/local/attachments.mjs +180 -0
  82. package/dist/esm/tools/local/attachments.mjs.map +1 -0
  83. package/dist/esm/tools/local/bashAst.mjs +126 -0
  84. package/dist/esm/tools/local/bashAst.mjs.map +1 -0
  85. package/dist/esm/tools/local/editStrategies.mjs +185 -0
  86. package/dist/esm/tools/local/editStrategies.mjs.map +1 -0
  87. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs +137 -0
  88. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -0
  89. package/dist/esm/tools/local/syntaxCheck.mjs +179 -0
  90. package/dist/esm/tools/local/syntaxCheck.mjs.map +1 -0
  91. package/dist/esm/tools/local/textEncoding.mjs +27 -0
  92. package/dist/esm/tools/local/textEncoding.mjs.map +1 -0
  93. package/dist/esm/tools/local/workspaceFS.mjs +49 -0
  94. package/dist/esm/tools/local/workspaceFS.mjs.map +1 -0
  95. package/dist/esm/tools/subagent/SubagentExecutor.mjs +1 -0
  96. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  97. package/dist/types/common/enum.d.ts +39 -1
  98. package/dist/types/graphs/Graph.d.ts +34 -0
  99. package/dist/types/hooks/createWorkspacePolicyHook.d.ts +95 -0
  100. package/dist/types/hooks/index.d.ts +2 -0
  101. package/dist/types/index.d.ts +1 -0
  102. package/dist/types/messages/anthropicToolCache.d.ts +51 -0
  103. package/dist/types/messages/index.d.ts +2 -0
  104. package/dist/types/messages/prune.d.ts +11 -0
  105. package/dist/types/messages/recency.d.ts +64 -0
  106. package/dist/types/run.d.ts +21 -0
  107. package/dist/types/tools/ToolNode.d.ts +145 -2
  108. package/dist/types/tools/local/CompileCheckTool.d.ts +31 -0
  109. package/dist/types/tools/local/FileCheckpointer.d.ts +39 -0
  110. package/dist/types/tools/local/LocalCodingTools.d.ts +57 -0
  111. package/dist/types/tools/local/LocalExecutionEngine.d.ts +149 -0
  112. package/dist/types/tools/local/LocalExecutionTools.d.ts +9 -0
  113. package/dist/types/tools/local/LocalProgrammaticToolCalling.d.ts +21 -0
  114. package/dist/types/tools/local/attachments.d.ts +84 -0
  115. package/dist/types/tools/local/bashAst.d.ts +11 -0
  116. package/dist/types/tools/local/editStrategies.d.ts +28 -0
  117. package/dist/types/tools/local/index.d.ts +12 -0
  118. package/dist/types/tools/local/resolveLocalExecutionTools.d.ts +38 -0
  119. package/dist/types/tools/local/syntaxCheck.d.ts +42 -0
  120. package/dist/types/tools/local/textEncoding.d.ts +21 -0
  121. package/dist/types/tools/local/workspaceFS.d.ts +49 -0
  122. package/dist/types/types/hitl.d.ts +56 -27
  123. package/dist/types/types/run.d.ts +8 -1
  124. package/dist/types/types/summarize.d.ts +30 -0
  125. package/dist/types/types/tools.d.ts +341 -6
  126. package/package.json +21 -2
  127. package/src/common/enum.ts +54 -0
  128. package/src/graphs/Graph.ts +164 -6
  129. package/src/hooks/__tests__/compactHooks.test.ts +38 -2
  130. package/src/hooks/__tests__/createWorkspacePolicyHook.test.ts +393 -0
  131. package/src/hooks/createWorkspacePolicyHook.ts +355 -0
  132. package/src/hooks/index.ts +6 -0
  133. package/src/index.ts +1 -0
  134. package/src/messages/__tests__/anthropicToolCache.test.ts +125 -0
  135. package/src/messages/__tests__/recency.test.ts +267 -0
  136. package/src/messages/anthropicToolCache.ts +116 -0
  137. package/src/messages/index.ts +2 -0
  138. package/src/messages/prune.ts +27 -1
  139. package/src/messages/recency.ts +155 -0
  140. package/src/run.ts +31 -0
  141. package/src/scripts/compare_pi_vs_ours.ts +840 -0
  142. package/src/scripts/local_engine.ts +166 -0
  143. package/src/scripts/local_engine_checkpointer.ts +205 -0
  144. package/src/scripts/local_engine_compile.ts +263 -0
  145. package/src/scripts/local_engine_hooks.ts +226 -0
  146. package/src/scripts/local_engine_image.ts +201 -0
  147. package/src/scripts/local_engine_ptc.ts +151 -0
  148. package/src/scripts/local_engine_workspace.ts +258 -0
  149. package/src/scripts/summarization-recency.ts +462 -0
  150. package/src/specs/prune.test.ts +39 -0
  151. package/src/summarization/__tests__/node.test.ts +499 -3
  152. package/src/summarization/node.ts +124 -7
  153. package/src/tools/ToolNode.ts +769 -20
  154. package/src/tools/__tests__/LocalExecutionTools.test.ts +2647 -0
  155. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +175 -0
  156. package/src/tools/__tests__/ToolNode.outputReferences.test.ts +114 -0
  157. package/src/tools/__tests__/ToolNode.session.test.ts +84 -0
  158. package/src/tools/__tests__/directToolHITLResumeScope.test.ts +467 -0
  159. package/src/tools/__tests__/directToolHooks.test.ts +411 -0
  160. package/src/tools/__tests__/localToolNames.test.ts +73 -0
  161. package/src/tools/__tests__/workspaceSeam.test.ts +134 -0
  162. package/src/tools/local/CompileCheckTool.ts +278 -0
  163. package/src/tools/local/FileCheckpointer.ts +93 -0
  164. package/src/tools/local/LocalCodingTools.ts +1342 -0
  165. package/src/tools/local/LocalExecutionEngine.ts +1329 -0
  166. package/src/tools/local/LocalExecutionTools.ts +167 -0
  167. package/src/tools/local/LocalProgrammaticToolCalling.ts +594 -0
  168. package/src/tools/local/__tests__/FileCheckpointer.test.ts +120 -0
  169. package/src/tools/local/__tests__/editStrategies.test.ts +134 -0
  170. package/src/tools/local/attachments.ts +251 -0
  171. package/src/tools/local/bashAst.ts +151 -0
  172. package/src/tools/local/editStrategies.ts +188 -0
  173. package/src/tools/local/index.ts +12 -0
  174. package/src/tools/local/resolveLocalExecutionTools.ts +208 -0
  175. package/src/tools/local/syntaxCheck.ts +243 -0
  176. package/src/tools/local/textEncoding.ts +37 -0
  177. package/src/tools/local/workspaceFS.ts +89 -0
  178. package/src/types/hitl.ts +56 -27
  179. package/src/types/run.ts +12 -1
  180. package/src/types/summarize.ts +31 -0
  181. package/src/types/tools.ts +359 -7
@@ -0,0 +1,1075 @@
1
+ import { dirname, basename } from 'path';
2
+ import { tool } from '@langchain/core/tools';
3
+ import { createTwoFilesPatch } from 'diff';
4
+ import { createLocalBashExecutionTool, createLocalCodeExecutionTool } from './LocalExecutionTools.mjs';
5
+ import { createLocalProgrammaticToolCallingTool, createLocalBashProgrammaticToolCallingTool } from './LocalProgrammaticToolCalling.mjs';
6
+ import { getWorkspaceFS, resolveWorkspacePathSafe, spawnLocalProcess, getSpawn, truncateLocalOutput } from './LocalExecutionEngine.mjs';
7
+ import { createLocalFileCheckpointer } from './FileCheckpointer.mjs';
8
+ import { locateEdit, applyEdit } from './editStrategies.mjs';
9
+ import { decodeFile, encodeFile } from './textEncoding.mjs';
10
+ import { classifyAttachment, imageAttachmentContent } from './attachments.mjs';
11
+ import { runPostEditSyntaxCheck } from './syntaxCheck.mjs';
12
+ import { createCompileCheckToolDefinition, createCompileCheckTool } from './CompileCheckTool.mjs';
13
+ import { Constants } from '../../common/enum.mjs';
14
+
15
+ const MAX_READ_CHARS = 256000;
16
+ const DEFAULT_MAX_RESULTS = 200;
17
+ const DEFAULT_MAX_READ_BYTES = 10 * 1024 * 1024;
18
+ const BINARY_DETECTION_BYTES = 8000;
19
+ /**
20
+ * Tool name aliases retained for back-compat with consumers that imported
21
+ * the per-file `Local*ToolName` constants. The canonical names live on
22
+ * `Constants.*` (see `src/common/enum.ts`); these aliases just point at
23
+ * them so a typo upstream gets caught at the type level.
24
+ */
25
+ const LocalWriteFileToolName = Constants.WRITE_FILE;
26
+ const LocalEditFileToolName = Constants.EDIT_FILE;
27
+ const LocalGrepSearchToolName = Constants.GREP_SEARCH;
28
+ const LocalGlobSearchToolName = Constants.GLOB_SEARCH;
29
+ const LocalListDirectoryToolName = Constants.LIST_DIRECTORY;
30
+ const LocalReadFileToolSchema = {
31
+ type: 'object',
32
+ properties: {
33
+ file_path: {
34
+ type: 'string',
35
+ description: 'Path to a local file, relative to the configured cwd unless absolute paths are allowed.',
36
+ },
37
+ offset: {
38
+ type: 'integer',
39
+ description: 'Optional 1-indexed line offset for large files.',
40
+ },
41
+ limit: {
42
+ type: 'integer',
43
+ description: 'Optional maximum number of lines to return.',
44
+ },
45
+ },
46
+ required: ['file_path'],
47
+ };
48
+ const LocalWriteFileToolSchema = {
49
+ type: 'object',
50
+ properties: {
51
+ file_path: {
52
+ type: 'string',
53
+ description: 'Path to write, relative to the configured cwd unless absolute paths are allowed.',
54
+ },
55
+ content: {
56
+ type: 'string',
57
+ description: 'Complete file contents to write.',
58
+ },
59
+ },
60
+ required: ['file_path', 'content'],
61
+ };
62
+ const LocalEditFileToolSchema = {
63
+ type: 'object',
64
+ properties: {
65
+ file_path: {
66
+ type: 'string',
67
+ description: 'Path to edit, relative to the configured cwd unless absolute paths are allowed.',
68
+ },
69
+ old_text: {
70
+ type: 'string',
71
+ description: 'Exact text to replace. Must appear exactly once.',
72
+ },
73
+ new_text: {
74
+ type: 'string',
75
+ description: 'Replacement text.',
76
+ },
77
+ edits: {
78
+ type: 'array',
79
+ description: 'Optional batch of exact replacements. Each old_text must appear exactly once in the original file.',
80
+ items: {
81
+ type: 'object',
82
+ properties: {
83
+ old_text: { type: 'string' },
84
+ new_text: { type: 'string' },
85
+ },
86
+ required: ['old_text', 'new_text'],
87
+ },
88
+ },
89
+ },
90
+ required: ['file_path'],
91
+ };
92
+ const LocalGrepSearchToolSchema = {
93
+ type: 'object',
94
+ properties: {
95
+ pattern: {
96
+ type: 'string',
97
+ description: 'Regex pattern to search for.',
98
+ },
99
+ path: {
100
+ type: 'string',
101
+ description: 'Directory or file to search. Defaults to cwd.',
102
+ },
103
+ glob: {
104
+ type: 'string',
105
+ description: 'Optional file glob passed to rg -g.',
106
+ },
107
+ max_results: {
108
+ type: 'integer',
109
+ description: 'Maximum matching lines to return.',
110
+ },
111
+ },
112
+ required: ['pattern'],
113
+ };
114
+ const LocalGlobSearchToolSchema = {
115
+ type: 'object',
116
+ properties: {
117
+ pattern: {
118
+ type: 'string',
119
+ description: 'File glob pattern, for example "src/**/*.ts".',
120
+ },
121
+ path: {
122
+ type: 'string',
123
+ description: 'Directory to search. Defaults to cwd.',
124
+ },
125
+ max_results: {
126
+ type: 'integer',
127
+ description: 'Maximum file paths to return.',
128
+ },
129
+ },
130
+ required: ['pattern'],
131
+ };
132
+ const LocalListDirectoryToolSchema = {
133
+ type: 'object',
134
+ properties: {
135
+ path: {
136
+ type: 'string',
137
+ description: 'Directory to list. Defaults to cwd.',
138
+ },
139
+ },
140
+ };
141
+ function lineWindow(content, offset, limit) {
142
+ const start = Math.max((offset ?? 1) - 1, 0);
143
+ // Avoid splitting the whole file when the caller asked for a small
144
+ // window. For a 10 MB file with `offset: 1, limit: 10`, the prior
145
+ // `content.split('\n')` allocated millions of strings to throw all
146
+ // but 10 away. We walk newline indices directly: O(start + limit)
147
+ // instead of O(file). When `limit` is omitted, fall back to the
148
+ // simple split — it's the same amount of work either way.
149
+ if (limit == null || limit <= 0) {
150
+ const lines = content.split('\n');
151
+ const selected = lines.slice(start);
152
+ const numbered = selected
153
+ .map((line, index) => `${String(start + index + 1).padStart(6, ' ')}\t${line}`)
154
+ .join('\n');
155
+ return {
156
+ text: truncateLocalOutput(numbered, MAX_READ_CHARS),
157
+ truncated: numbered.length > MAX_READ_CHARS,
158
+ };
159
+ }
160
+ // Walk to the start line by counting newlines.
161
+ let cursor = 0;
162
+ for (let i = 0; i < start; i++) {
163
+ const next = content.indexOf('\n', cursor);
164
+ if (next === -1) {
165
+ // File has fewer lines than `offset` — return empty window.
166
+ return { text: '', truncated: false };
167
+ }
168
+ cursor = next + 1;
169
+ }
170
+ // Collect up to `limit` lines from `cursor`.
171
+ const out = [];
172
+ let pos = cursor;
173
+ let exhausted = true;
174
+ for (let k = 0; k < limit; k++) {
175
+ const next = content.indexOf('\n', pos);
176
+ if (next === -1) {
177
+ out.push(content.slice(pos));
178
+ break;
179
+ }
180
+ out.push(content.slice(pos, next));
181
+ pos = next + 1;
182
+ if (k === limit - 1 && pos < content.length) {
183
+ exhausted = false;
184
+ }
185
+ }
186
+ const numbered = out
187
+ .map((text, index) => `${String(start + index + 1).padStart(6, ' ')}\t${text}`)
188
+ .join('\n');
189
+ return {
190
+ text: truncateLocalOutput(numbered, MAX_READ_CHARS),
191
+ truncated: !exhausted || numbered.length > MAX_READ_CHARS,
192
+ };
193
+ }
194
+ const MAX_DIFF_CHARS = 4000;
195
+ async function maybeRunSyntaxCheck(path, config) {
196
+ const mode = config.postEditSyntaxCheck ?? 'off';
197
+ if (mode === 'off')
198
+ return undefined;
199
+ const outcome = await runPostEditSyntaxCheck(path, config);
200
+ if (outcome == null)
201
+ return undefined;
202
+ return { mode, outcome };
203
+ }
204
+ function appendSyntaxCheckSummary(base, run) {
205
+ if (run == null)
206
+ return base;
207
+ if (run.outcome.ok)
208
+ return base;
209
+ const banner = run.mode === 'strict'
210
+ ? `\n\n[syntax-check FAILED via ${run.outcome.checker}]\n`
211
+ : `\n\n[syntax-check warning via ${run.outcome.checker}]\n`;
212
+ return `${base}${banner}${run.outcome.output}`;
213
+ }
214
+ /**
215
+ * Revert a write_file/edit_file mutation in `postEditSyntaxCheck:
216
+ * 'strict'` mode after the post-write syntax check failed. Strict
217
+ * mode advertises a safety gate, so leaving the corrupted file on
218
+ * disk + throwing is a half-broken contract — the model "reacts" to
219
+ * the error but the next call sees broken on-disk state. Codex P2
220
+ * [49]. Best-effort: a swallowed error here means the workspace is
221
+ * still in the bad post-write state, but we still throw the
222
+ * original syntax-check error so the caller knows.
223
+ *
224
+ * - If the file existed pre-write: restore the previous bytes with
225
+ * the original encoding.
226
+ * - If the file is brand-new: unlink it.
227
+ */
228
+ async function revertStrictWrite(fs, path, existed, before, encoding) {
229
+ try {
230
+ if (existed) {
231
+ // encodeFile uses encoding.{hasBom,newline} to restore the
232
+ // on-disk shape; the `text` field is overridden by the
233
+ // explicit `before` arg we pass in.
234
+ await fs.writeFile(path, encodeFile(before, { ...encoding, text: before }), 'utf8');
235
+ }
236
+ else {
237
+ await fs.unlink(path);
238
+ }
239
+ }
240
+ catch {
241
+ /* best-effort: caller still sees the original syntax error */
242
+ }
243
+ }
244
+ function summariseDiff(filePath, before, after) {
245
+ if (before === after) {
246
+ return '(no textual changes)';
247
+ }
248
+ const name = basename(filePath);
249
+ const patch = createTwoFilesPatch(name, name, before, after, '', '', {
250
+ context: 3,
251
+ });
252
+ if (patch.length <= MAX_DIFF_CHARS) {
253
+ return patch;
254
+ }
255
+ return (patch.slice(0, MAX_DIFF_CHARS) +
256
+ `\n[... diff truncated, ${patch.length - MAX_DIFF_CHARS} more chars ...]`);
257
+ }
258
+ function normalizeEdits(input) {
259
+ const edits = Array.isArray(input.edits)
260
+ ? input.edits.map((edit) => ({
261
+ oldText: edit.old_text ?? '',
262
+ newText: edit.new_text ?? '',
263
+ }))
264
+ : [];
265
+ if (input.old_text != null || input.new_text != null) {
266
+ edits.push({
267
+ oldText: input.old_text ?? '',
268
+ newText: input.new_text ?? '',
269
+ });
270
+ }
271
+ return edits;
272
+ }
273
+ function toolDefinition(name, description, parameters) {
274
+ return {
275
+ name,
276
+ description,
277
+ parameters,
278
+ allowed_callers: ['direct', 'code_execution'],
279
+ responseFormat: Constants.CONTENT_AND_ARTIFACT,
280
+ toolType: 'builtin',
281
+ };
282
+ }
283
+ async function looksBinary(path, fs) {
284
+ let handle;
285
+ try {
286
+ handle = await fs.open(path, 'r');
287
+ const sample = Buffer.alloc(BINARY_DETECTION_BYTES);
288
+ const { bytesRead } = await handle.read(sample, 0, BINARY_DETECTION_BYTES, 0);
289
+ for (let i = 0; i < bytesRead; i++) {
290
+ if (sample[i] === 0) {
291
+ return true;
292
+ }
293
+ }
294
+ return false;
295
+ }
296
+ finally {
297
+ await handle?.close();
298
+ }
299
+ }
300
+ const DEFAULT_MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024;
301
+ function createLocalReadFileTool(config = {}) {
302
+ const fs = getWorkspaceFS(config);
303
+ return tool(async (rawInput) => {
304
+ const input = rawInput;
305
+ const path = await resolveWorkspacePathSafe(input.file_path, config, 'read');
306
+ const fileStat = await fs.stat(path);
307
+ if (!fileStat.isFile()) {
308
+ throw new Error(`Path is not a file: ${input.file_path}`);
309
+ }
310
+ const maxBytes = Math.max(config.maxReadBytes ?? DEFAULT_MAX_READ_BYTES, 1);
311
+ if (fileStat.size > maxBytes) {
312
+ 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.`;
313
+ return [stub, { path, bytes: fileStat.size, truncated: true }];
314
+ }
315
+ if (await looksBinary(path, fs)) {
316
+ const attachmentMode = config.attachReadAttachments ?? 'off';
317
+ if (attachmentMode !== 'off') {
318
+ const attachment = await classifyAttachment({
319
+ path,
320
+ bytes: fileStat.size,
321
+ mode: attachmentMode,
322
+ maxBytes: config.maxAttachmentBytes ?? DEFAULT_MAX_ATTACHMENT_BYTES,
323
+ // Route through the configured WorkspaceFS so a custom
324
+ // engine sees the same path semantics as `read_file`
325
+ // itself (manual review finding F).
326
+ fs,
327
+ });
328
+ if (attachment.kind === 'image') {
329
+ return [
330
+ imageAttachmentContent(path, attachment),
331
+ {
332
+ path,
333
+ bytes: fileStat.size,
334
+ mime: attachment.mime,
335
+ attachment: 'image',
336
+ },
337
+ ];
338
+ }
339
+ if (attachment.kind === 'pdf') {
340
+ return [
341
+ [
342
+ {
343
+ type: 'text',
344
+ text: `Read ${path} (application/pdf, ${fileStat.size} bytes). PDF attached as base64 data URL; vision-capable models that accept PDF will render it.`,
345
+ },
346
+ {
347
+ type: 'image_url',
348
+ image_url: { url: attachment.dataUrl },
349
+ },
350
+ ],
351
+ {
352
+ path,
353
+ bytes: fileStat.size,
354
+ mime: attachment.mime,
355
+ attachment: 'pdf',
356
+ },
357
+ ];
358
+ }
359
+ if (attachment.kind === 'oversize') {
360
+ return [
361
+ `Refusing to embed ${attachment.mime} attachment (${attachment.bytes} bytes exceeds ${attachment.maxBytes}-byte cap).`,
362
+ {
363
+ path,
364
+ bytes: fileStat.size,
365
+ mime: attachment.mime,
366
+ attachment: 'oversize',
367
+ },
368
+ ];
369
+ }
370
+ if (attachment.kind === 'binary') {
371
+ return [
372
+ `Refusing to read binary file (${fileStat.size} bytes, ${attachment.mime}): ${path}`,
373
+ {
374
+ path,
375
+ bytes: fileStat.size,
376
+ mime: attachment.mime,
377
+ binary: true,
378
+ },
379
+ ];
380
+ }
381
+ // text-or-unknown falls through to the text-read path below.
382
+ }
383
+ else {
384
+ return [
385
+ `Refusing to read binary file (${fileStat.size} bytes): ${path}`,
386
+ { path, bytes: fileStat.size, binary: true },
387
+ ];
388
+ }
389
+ }
390
+ const content = await fs.readFile(path, 'utf8');
391
+ const result = lineWindow(content, input.offset, input.limit);
392
+ return [
393
+ result.truncated ? `${result.text}\n[truncated]` : result.text,
394
+ { path, bytes: fileStat.size },
395
+ ];
396
+ }, {
397
+ name: Constants.READ_FILE,
398
+ description: 'Read a local text file from the configured working directory with line numbers. ' +
399
+ 'When `attachReadAttachments` is enabled (e.g. images-only), reading an image returns an ' +
400
+ '`image_url` content block so vision-capable models can see the file directly.',
401
+ schema: LocalReadFileToolSchema,
402
+ responseFormat: Constants.CONTENT_AND_ARTIFACT,
403
+ });
404
+ }
405
+ function createLocalWriteFileTool(config = {}, checkpointer) {
406
+ const fs = getWorkspaceFS(config);
407
+ return tool(async (rawInput) => {
408
+ const input = rawInput;
409
+ if (config.readOnly === true) {
410
+ throw new Error('write_file is blocked in read-only local mode.');
411
+ }
412
+ const path = await resolveWorkspacePathSafe(input.file_path, config, 'write');
413
+ if (checkpointer != null) {
414
+ await checkpointer.captureBeforeWrite(path);
415
+ }
416
+ let before = '';
417
+ let encoding = { text: '', hasBom: false, newline: '\n' };
418
+ let existed = false;
419
+ try {
420
+ const raw = await fs.readFile(path, 'utf8');
421
+ const decoded = decodeFile(raw);
422
+ before = decoded.text;
423
+ encoding = decoded;
424
+ existed = true;
425
+ }
426
+ catch {
427
+ existed = false;
428
+ }
429
+ await fs.mkdir(dirname(path), { recursive: true });
430
+ const finalText = encodeFile(input.content, encoding);
431
+ await fs.writeFile(path, finalText, 'utf8');
432
+ const syntax = await maybeRunSyntaxCheck(path, config);
433
+ const diff = existed
434
+ ? summariseDiff(path, before, input.content)
435
+ : `(new file, ${input.content.length} chars)`;
436
+ const baseSummary = existed
437
+ ? `Overwrote ${path} (${input.content.length} chars). Diff:\n${diff}`
438
+ : `Created ${path} (${input.content.length} chars).`;
439
+ const summary = appendSyntaxCheckSummary(baseSummary, syntax);
440
+ if (syntax?.outcome.ok === false && syntax.mode === 'strict') {
441
+ // Roll back the write so strict mode is an actual gate, not
442
+ // "fail the call AND leave the corrupted file on disk".
443
+ // Codex P2 [49].
444
+ await revertStrictWrite(fs, path, existed, before, encoding);
445
+ throw new Error(`write_file syntax check failed (${syntax.outcome.checker}); reverted to pre-write state.\n${syntax.outcome.output}`);
446
+ }
447
+ return [
448
+ summary,
449
+ {
450
+ path,
451
+ bytes: finalText.length,
452
+ new_file: !existed,
453
+ newline: encoding.newline === '\r\n' ? 'CRLF' : 'LF',
454
+ had_bom: encoding.hasBom,
455
+ ...(syntax != null && syntax.outcome.ok === false
456
+ ? { syntax_error: syntax.outcome.checker }
457
+ : {}),
458
+ },
459
+ ];
460
+ }, {
461
+ name: LocalWriteFileToolName,
462
+ description: 'Create or overwrite a local text file in the configured working directory. ' +
463
+ 'Preserves the existing BOM and line endings when overwriting; defaults to LF without BOM for new files. ' +
464
+ 'Returns a unified diff of the changes when overwriting.',
465
+ schema: LocalWriteFileToolSchema,
466
+ responseFormat: Constants.CONTENT_AND_ARTIFACT,
467
+ });
468
+ }
469
+ function createLocalEditFileTool(config = {}, checkpointer) {
470
+ const fs = getWorkspaceFS(config);
471
+ return tool(async (rawInput) => {
472
+ const input = rawInput;
473
+ if (config.readOnly === true) {
474
+ throw new Error('edit_file is blocked in read-only local mode.');
475
+ }
476
+ const edits = normalizeEdits(input);
477
+ if (edits.length === 0) {
478
+ throw new Error('edit_file requires old_text/new_text or edits[].');
479
+ }
480
+ const path = await resolveWorkspacePathSafe(input.file_path, config, 'write');
481
+ const raw = await fs.readFile(path, 'utf8');
482
+ const encoding = decodeFile(raw);
483
+ const original = encoding.text;
484
+ let next = original;
485
+ const strategiesUsed = [];
486
+ for (let i = 0; i < edits.length; i++) {
487
+ const edit = edits[i];
488
+ const match = locateEdit(next, edit.oldText);
489
+ if (match == null) {
490
+ throw new Error(`Edit ${i + 1}/${edits.length}: could not locate old_text in ${input.file_path}. ` +
491
+ 'Tried exact, line-trimmed, whitespace-normalized, and indentation-flexible matching. ' +
492
+ 'Re-read the file and copy the literal lines.');
493
+ }
494
+ strategiesUsed.push(match.strategy);
495
+ next = applyEdit(next, match, edit.newText);
496
+ }
497
+ if (checkpointer != null) {
498
+ await checkpointer.captureBeforeWrite(path);
499
+ }
500
+ const finalText = encodeFile(next, encoding);
501
+ await fs.writeFile(path, finalText, 'utf8');
502
+ const syntax = await maybeRunSyntaxCheck(path, config);
503
+ const diff = summariseDiff(path, original, next);
504
+ const fuzzy = strategiesUsed.some((s) => s !== 'exact');
505
+ const baseSummary = `Applied ${edits.length} edit(s) to ${path}` +
506
+ (fuzzy ? ` (strategies: ${strategiesUsed.join(', ')})` : '') +
507
+ `. Diff:\n${diff}`;
508
+ const summary = appendSyntaxCheckSummary(baseSummary, syntax);
509
+ if (syntax?.outcome.ok === false && syntax.mode === 'strict') {
510
+ // Restore the pre-edit bytes so strict mode is an actual
511
+ // gate (Codex P2 [49]). edit_file always operates on an
512
+ // existing file, so `existed = true` here.
513
+ await revertStrictWrite(fs, path, true, original, encoding);
514
+ throw new Error(`edit_file syntax check failed (${syntax.outcome.checker}); reverted to pre-edit state.\n${syntax.outcome.output}`);
515
+ }
516
+ return [
517
+ summary,
518
+ {
519
+ path,
520
+ edits: edits.length,
521
+ strategies: strategiesUsed,
522
+ newline: encoding.newline === '\r\n' ? 'CRLF' : 'LF',
523
+ had_bom: encoding.hasBom,
524
+ ...(syntax != null && syntax.outcome.ok === false
525
+ ? { syntax_error: syntax.outcome.checker }
526
+ : {}),
527
+ },
528
+ ];
529
+ }, {
530
+ name: LocalEditFileToolName,
531
+ description: '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.',
532
+ schema: LocalEditFileToolSchema,
533
+ responseFormat: Constants.CONTENT_AND_ARTIFACT,
534
+ });
535
+ }
536
+ /**
537
+ * Ripgrep availability cache, keyed on the *effective execution
538
+ * backend* — whatever function `getSpawn(config)` returns. Without
539
+ * the backend key, a Run that probes `rg` over Node's
540
+ * `child_process.spawn` would poison subsequent Runs whose
541
+ * `local.exec.spawn` routes to a remote sandbox or container that
542
+ * doesn't have rg installed: the cached `true` would skip the probe,
543
+ * the rg invocation would throw, and the Node fallback wouldn't be
544
+ * reached. Per-backend caching avoids that without paying for a
545
+ * spawn-per-search.
546
+ */
547
+ // Per-backend × per-env cache. Codex P1 #34 — keying by spawn
548
+ // backend alone misses the case where two Runs share a backend but
549
+ // vary `local.env` (especially PATH). Stale cache then claims `rg`
550
+ // is available, the rg path runs, and the spawn fails with ENOENT
551
+ // instead of falling back to the Node walker. The inner Map is
552
+ // keyed by a stable JSON hash of the effective env so each unique
553
+ // env gets its own probe.
554
+ let ripgrepAvailabilityByBackend = new WeakMap();
555
+ function envCacheKey(env) {
556
+ // PATH is the only env entry that affects command lookup, but
557
+ // hashing the whole env keeps the key correct for hosts that
558
+ // vary anything else relevant. Stable JSON via sorted keys so
559
+ // {A:1,B:2} and {B:2,A:1} produce the same hash.
560
+ if (env == null)
561
+ return '';
562
+ const sorted = {};
563
+ for (const k of Object.keys(env).sort()) {
564
+ sorted[k] = env[k];
565
+ }
566
+ return JSON.stringify(sorted);
567
+ }
568
+ async function isRipgrepAvailable(config) {
569
+ const backend = getSpawn(config);
570
+ let envMap = ripgrepAvailabilityByBackend.get(backend);
571
+ if (envMap == null) {
572
+ envMap = new Map();
573
+ ripgrepAvailabilityByBackend.set(backend, envMap);
574
+ }
575
+ const envKey = envCacheKey(config.env);
576
+ let probePromise = envMap.get(envKey);
577
+ if (probePromise == null) {
578
+ probePromise = spawnLocalProcess('rg', ['--version'], { ...config, timeoutMs: 5000, sandbox: { enabled: false } }, { internal: true })
579
+ .then((probe) => probe != null && probe.exitCode === 0)
580
+ .catch(() => false);
581
+ envMap.set(envKey, probePromise);
582
+ }
583
+ return probePromise;
584
+ }
585
+ /**
586
+ * Test-only reset hook. Clears the ripgrep-availability cache so
587
+ * tests can swap in mocked spawn backends and reprobe deterministically.
588
+ *
589
+ * @internal Not part of the public SDK surface; the leading underscore
590
+ * and `@internal` tag together signal that consumers should not call
591
+ * this. Tests import it via the module path directly.
592
+ */
593
+ function _resetRipgrepCacheForTests() {
594
+ ripgrepAvailabilityByBackend = new WeakMap();
595
+ }
596
+ // Skipped by the Node-fallback walker (used when ripgrep is
597
+ // unavailable). Covers common build outputs, virtualenvs, and
598
+ // caches so a `grep_search`/`glob_search` on a large monorepo or a
599
+ // Python project with `.venv/` doesn't read every file under those
600
+ // trees. ripgrep itself respects .gitignore so it doesn't need this
601
+ // list. Audit follow-up from the comprehensive review (finding #3).
602
+ const SKIP_DIRS = new Set([
603
+ '.git',
604
+ '.svn',
605
+ '.hg',
606
+ 'node_modules',
607
+ '.next',
608
+ '.nuxt',
609
+ '.cache',
610
+ '.parcel-cache',
611
+ '.turbo',
612
+ 'dist',
613
+ 'build',
614
+ 'out',
615
+ 'target',
616
+ 'vendor',
617
+ 'coverage',
618
+ '.nyc_output',
619
+ '__pycache__',
620
+ '.venv',
621
+ 'venv',
622
+ 'env',
623
+ '.tox',
624
+ '.mypy_cache',
625
+ '.pytest_cache',
626
+ '.ruff_cache',
627
+ ]);
628
+ function globToRegExp(pattern) {
629
+ let result = '^';
630
+ for (let i = 0; i < pattern.length; i++) {
631
+ const c = pattern[i];
632
+ if (c === '*') {
633
+ if (pattern[i + 1] === '*') {
634
+ result += '.*';
635
+ i += 1;
636
+ if (pattern[i + 1] === '/') {
637
+ i += 1;
638
+ }
639
+ }
640
+ else {
641
+ result += '[^/]*';
642
+ }
643
+ }
644
+ else if (c === '?') {
645
+ result += '[^/]';
646
+ }
647
+ else if ('.+^$|(){}[]\\'.includes(c)) {
648
+ result += '\\' + c;
649
+ }
650
+ else {
651
+ result += c;
652
+ }
653
+ }
654
+ result += '$';
655
+ return new RegExp(result);
656
+ }
657
+ async function* walkFiles(root, fs) {
658
+ const stack = [root];
659
+ while (stack.length > 0) {
660
+ const dir = stack.pop();
661
+ let entries;
662
+ try {
663
+ entries = await fs.readdir(dir, { withFileTypes: true });
664
+ }
665
+ catch {
666
+ continue;
667
+ }
668
+ for (const entry of entries) {
669
+ if (entry.name.startsWith('.git') || SKIP_DIRS.has(entry.name)) {
670
+ continue;
671
+ }
672
+ const full = `${dir}/${entry.name}`;
673
+ if (entry.isDirectory()) {
674
+ stack.push(full);
675
+ }
676
+ else if (entry.isFile()) {
677
+ yield full;
678
+ }
679
+ }
680
+ }
681
+ }
682
+ /**
683
+ * Catastrophic-backtracking guardrails for the fallback grep path.
684
+ *
685
+ * Without ripgrep we run the model-supplied pattern through Node's
686
+ * `RegExp` engine, which uses a backtracking implementation. Patterns
687
+ * with nested unbounded quantifiers (`(a+)+`, `(.*)*`, etc.) can
688
+ * monopolise the event loop for arbitrary wall-clock time on
689
+ * pathological input, and `setTimeout` cannot interrupt a synchronous
690
+ * `RegExp.exec`. Manual review (finding D) flagged this as a real DoS.
691
+ *
692
+ * Mitigations applied here, in order of severity:
693
+ * 1. Cap pattern length so an obviously oversize regex is rejected
694
+ * before compile.
695
+ * 2. Reject patterns that contain a nested unbounded quantifier of
696
+ * the form `(...+|*)([+*]|{n,})` — the standard pathological
697
+ * shape. Still a heuristic (not a full safety proof), but blocks
698
+ * every common DoS construction we've seen in coding-agent logs.
699
+ * 3. Wall-clock budget for the overall search: each file's regex
700
+ * pass is checked against a deadline; once exceeded the search
701
+ * bails with a partial result. Doesn't interrupt a stuck
702
+ * `exec()` call, but stops a slow pattern from making the whole
703
+ * Run hang once the first hung file finishes.
704
+ *
705
+ * Hosts that need bulletproof regex safety should install `rg` —
706
+ * ripgrep uses RE2 internally and has no backtracking.
707
+ */
708
+ const MAX_FALLBACK_PATTERN_LENGTH = 1024;
709
+ const FALLBACK_GREP_BUDGET_MS = 5000;
710
+ // Per-file byte cap. Codex P2 #41 — without it, the whole-file
711
+ // `readFile` + `split('\n')` for a multi-GB log is an unbounded
712
+ // allocation that the wall-clock budget (checked between files)
713
+ // can't interrupt. Hosts that need to grep large files should
714
+ // install ripgrep.
715
+ const FALLBACK_GREP_MAX_FILE_BYTES = 5 * 1024 * 1024;
716
+ /**
717
+ * Heuristic: walks `pattern` to find any `(<contents>)<quant>` where
718
+ * `<contents>` itself has an unbounded quantifier. Catches the
719
+ * classic `(a+)+` form AND the double-nested `((a+)+)` form (which a
720
+ * single-pass regex misses because `[^)]*` stops at the first inner
721
+ * close-paren). Misses sufficiently obfuscated cases — bulletproof
722
+ * ReDoS detection requires a real parser. The 5 s wall-clock budget
723
+ * is the hard backstop for anything this slip past.
724
+ */
725
+ function hasNestedUnboundedQuantifier(pattern) {
726
+ for (let i = 1; i < pattern.length - 1; i++) {
727
+ if (pattern[i] !== ')')
728
+ continue;
729
+ if (pattern[i - 1] === '\\')
730
+ continue;
731
+ const next = pattern[i + 1];
732
+ if (next !== '+' && next !== '*' && next !== '{')
733
+ continue;
734
+ // Walk back to find the matching opening paren (respecting depth
735
+ // and `\(` escapes).
736
+ let depth = 1;
737
+ let j = i - 1;
738
+ while (j >= 0) {
739
+ const c = pattern[j];
740
+ const escaped = j > 0 && pattern[j - 1] === '\\';
741
+ if (!escaped) {
742
+ if (c === ')')
743
+ depth++;
744
+ else if (c === '(') {
745
+ depth--;
746
+ if (depth === 0)
747
+ break;
748
+ }
749
+ }
750
+ j--;
751
+ }
752
+ if (j < 0)
753
+ continue;
754
+ const inner = pattern.slice(j + 1, i);
755
+ if (/(?<!\\)[+*]/.test(inner))
756
+ return true;
757
+ }
758
+ return false;
759
+ }
760
+ class FallbackGrepError extends Error {
761
+ kind;
762
+ constructor(kind, message) {
763
+ super(message);
764
+ this.kind = kind;
765
+ }
766
+ }
767
+ function compileFallbackRegex(pattern) {
768
+ if (pattern.length > MAX_FALLBACK_PATTERN_LENGTH) {
769
+ throw new FallbackGrepError('pattern-too-long', `Pattern exceeds ${MAX_FALLBACK_PATTERN_LENGTH}-char fallback cap (install ripgrep for unbounded patterns).`);
770
+ }
771
+ if (hasNestedUnboundedQuantifier(pattern)) {
772
+ throw new FallbackGrepError('unsafe-pattern', '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.');
773
+ }
774
+ try {
775
+ return new RegExp(pattern);
776
+ }
777
+ catch (e) {
778
+ throw new FallbackGrepError('invalid-pattern', `Invalid regex: ${e.message}`);
779
+ }
780
+ }
781
+ async function fallbackGrep(root, pattern, globFilter, maxResults, fs) {
782
+ const rx = compileFallbackRegex(pattern);
783
+ const deadline = Date.now() + FALLBACK_GREP_BUDGET_MS;
784
+ const globRx = globFilter != null && globFilter !== '' ? globToRegExp(globFilter) : undefined;
785
+ const matches = [];
786
+ // Track skipped (oversize) files separately so they don't consume
787
+ // the maxResults budget. Codex P2 [43]: round 14's fix pushed skip
788
+ // sentinels into `matches`, so a directory of one oversize non-
789
+ // matching file falsely reported `matches: 1`, and enough
790
+ // oversize files could fill the budget before any real match was
791
+ // scanned. Now diagnostics are appended after real matches and
792
+ // independent of the budget.
793
+ const skippedDiagnostics = [];
794
+ for await (const file of walkFiles(root, fs)) {
795
+ if (Date.now() > deadline) {
796
+ // Wall-clock budget exceeded — return partial results rather
797
+ // than letting a slow pattern hang the Run.
798
+ return { matches, skipped: skippedDiagnostics };
799
+ }
800
+ if (globRx != null) {
801
+ const rel = file.startsWith(root + '/') ? file.slice(root.length + 1) : file;
802
+ if (!globRx.test(rel)) {
803
+ continue;
804
+ }
805
+ }
806
+ // Skip files larger than the per-file cap and remember them as
807
+ // diagnostics (NOT as matches). Codex P2 [41]: pre-fix
808
+ // `fs.readFile` then `.split('\n')` allocated the whole file +
809
+ // an array of every line, which a single multi-GB log could
810
+ // turn into an OOM even after the regex DoS guards.
811
+ let stat;
812
+ try {
813
+ stat = await fs.stat(file);
814
+ }
815
+ catch {
816
+ continue;
817
+ }
818
+ if (stat.size > FALLBACK_GREP_MAX_FILE_BYTES) {
819
+ skippedDiagnostics.push(`${file}:0:[skipped: file > ${FALLBACK_GREP_MAX_FILE_BYTES} bytes; install ripgrep for unbounded grep]`);
820
+ continue;
821
+ }
822
+ let content;
823
+ try {
824
+ content = await fs.readFile(file, 'utf8');
825
+ }
826
+ catch {
827
+ continue;
828
+ }
829
+ if (content.includes('\0')) {
830
+ continue;
831
+ }
832
+ // Re-check the deadline AFTER the read — a slow disk on one
833
+ // file can blow the budget without us noticing.
834
+ if (Date.now() > deadline) {
835
+ return { matches, skipped: skippedDiagnostics };
836
+ }
837
+ const lines = content.split('\n');
838
+ for (let i = 0; i < lines.length; i++) {
839
+ if (rx.test(lines[i])) {
840
+ matches.push(`${file}:${i + 1}:${lines[i]}`);
841
+ if (matches.length >= maxResults) {
842
+ return { matches, skipped: skippedDiagnostics };
843
+ }
844
+ }
845
+ }
846
+ }
847
+ return { matches, skipped: skippedDiagnostics };
848
+ }
849
+ async function fallbackGlob(root, pattern, maxResults, fs) {
850
+ const rx = globToRegExp(pattern);
851
+ const out = [];
852
+ for await (const file of walkFiles(root, fs)) {
853
+ const rel = file.startsWith(root + '/') ? file.slice(root.length + 1) : file;
854
+ if (rx.test(rel)) {
855
+ out.push(file);
856
+ if (out.length >= maxResults) {
857
+ break;
858
+ }
859
+ }
860
+ }
861
+ return out;
862
+ }
863
+ function createLocalGrepSearchTool(config = {}) {
864
+ const fs = getWorkspaceFS(config);
865
+ return tool(async (rawInput) => {
866
+ const input = rawInput;
867
+ const target = await resolveWorkspacePathSafe(input.path ?? '.', config, 'read');
868
+ const maxResults = Math.max(input.max_results ?? DEFAULT_MAX_RESULTS, 1);
869
+ if (await isRipgrepAvailable(config)) {
870
+ // Pass the pattern through `-e` so dash-prefixed patterns
871
+ // like `-foo` are treated as the search regex, not as a
872
+ // (probably-unknown) flag. `rg --help` explicitly requires
873
+ // `-e/--regexp` (or `--`) for that case. Same trick avoids
874
+ // any future flag-conflict if a user query happens to look
875
+ // like an rg long option.
876
+ const args = [
877
+ '--line-number',
878
+ '--column',
879
+ '--hidden',
880
+ '--glob',
881
+ '!.git/**',
882
+ ...(input.glob != null && input.glob !== '' ? ['--glob', input.glob] : []),
883
+ '-e',
884
+ input.pattern,
885
+ target,
886
+ ];
887
+ const result = await spawnLocalProcess('rg', args, {
888
+ ...config,
889
+ timeoutMs: config.timeoutMs ?? 30000,
890
+ });
891
+ // ripgrep exit codes:
892
+ // 0 → at least one match
893
+ // 1 → no matches (clean — "No matches found.")
894
+ // 2 → real error (bad regex, unreadable target, etc.)
895
+ // Without this branch (Codex P2 #23 — same fix shape glob_search
896
+ // got from P2 #13), exit-2 errors silently mapped to
897
+ // `matches: 0`, so the agent treated tooling failures as a
898
+ // genuine absence of matches.
899
+ if (result.timedOut || (result.exitCode != null && result.exitCode > 1)) {
900
+ const detail = result.stderr.trim() || `rg exited ${result.exitCode}`;
901
+ return [
902
+ `grep_search failed: ${detail}`,
903
+ {
904
+ matches: 0,
905
+ engine: 'ripgrep',
906
+ error: detail,
907
+ exitCode: result.exitCode,
908
+ },
909
+ ];
910
+ }
911
+ const lines = result.stdout.split('\n').filter(Boolean).slice(0, maxResults);
912
+ const output = lines.length > 0
913
+ ? lines.join('\n')
914
+ : result.stderr.trim() || 'No matches found.';
915
+ return [output, { matches: lines.length, engine: 'ripgrep' }];
916
+ }
917
+ try {
918
+ const { matches, skipped } = await fallbackGrep(target, input.pattern, input.glob, maxResults, fs);
919
+ // Display: real matches first, skip diagnostics appended.
920
+ // Artifact count: ONLY real matches (Codex P2 [43] —
921
+ // skip sentinels used to inflate the count and the budget).
922
+ const display = matches.length > 0
923
+ ? [...matches, ...skipped].join('\n')
924
+ : skipped.length > 0
925
+ ? skipped.join('\n')
926
+ : 'No matches found.';
927
+ return [
928
+ display,
929
+ {
930
+ matches: matches.length,
931
+ skipped: skipped.length,
932
+ engine: 'node-fallback',
933
+ },
934
+ ];
935
+ }
936
+ catch (e) {
937
+ if (e instanceof FallbackGrepError) {
938
+ return [
939
+ `grep_search refused the pattern: ${e.message}`,
940
+ {
941
+ matches: 0,
942
+ engine: 'node-fallback',
943
+ error: e.message,
944
+ kind: e.kind,
945
+ },
946
+ ];
947
+ }
948
+ throw e;
949
+ }
950
+ }, {
951
+ name: LocalGrepSearchToolName,
952
+ description: 'Search local files for a regex pattern (ripgrep when available, Node fallback otherwise).',
953
+ schema: LocalGrepSearchToolSchema,
954
+ responseFormat: Constants.CONTENT_AND_ARTIFACT,
955
+ });
956
+ }
957
+ function createLocalGlobSearchTool(config = {}) {
958
+ const fs = getWorkspaceFS(config);
959
+ return tool(async (rawInput) => {
960
+ const input = rawInput;
961
+ const target = await resolveWorkspacePathSafe(input.path ?? '.', config, 'read');
962
+ const maxResults = Math.max(input.max_results ?? DEFAULT_MAX_RESULTS, 1);
963
+ if (await isRipgrepAvailable(config)) {
964
+ const result = await spawnLocalProcess('rg', ['--files', '--hidden', '--glob', '!.git/**', '--glob', input.pattern, target], { ...config, timeoutMs: config.timeoutMs ?? 30000 });
965
+ // rg --files exit codes:
966
+ // 0 → at least one file matched
967
+ // 1 → no files matched (clean — "No files found.")
968
+ // 2 → real error (bad glob, unreadable target, etc.)
969
+ // Without this branch, exit-2 errors used to silently map to
970
+ // "No files found." — the agent then treats a tooling failure
971
+ // as a real absence of matches.
972
+ if (result.timedOut || (result.exitCode != null && result.exitCode > 1)) {
973
+ const detail = result.stderr.trim() || `rg exited ${result.exitCode}`;
974
+ return [
975
+ `glob_search failed: ${detail}`,
976
+ {
977
+ files: [],
978
+ engine: 'ripgrep',
979
+ error: detail,
980
+ exitCode: result.exitCode,
981
+ },
982
+ ];
983
+ }
984
+ const lines = result.stdout
985
+ .split('\n')
986
+ .filter(Boolean)
987
+ .slice(0, maxResults);
988
+ return [
989
+ lines.length > 0 ? lines.join('\n') : 'No files found.',
990
+ { files: lines, engine: 'ripgrep' },
991
+ ];
992
+ }
993
+ const files = await fallbackGlob(target, input.pattern, maxResults, fs);
994
+ return [
995
+ files.length > 0 ? files.join('\n') : 'No files found.',
996
+ { files, engine: 'node-fallback' },
997
+ ];
998
+ }, {
999
+ name: LocalGlobSearchToolName,
1000
+ description: 'Find local files matching a glob pattern (ripgrep when available, Node fallback otherwise).',
1001
+ schema: LocalGlobSearchToolSchema,
1002
+ responseFormat: Constants.CONTENT_AND_ARTIFACT,
1003
+ });
1004
+ }
1005
+ function createLocalListDirectoryTool(config = {}) {
1006
+ const fs = getWorkspaceFS(config);
1007
+ return tool(async (rawInput) => {
1008
+ const input = rawInput;
1009
+ const path = await resolveWorkspacePathSafe(input.path ?? '.', config, 'read');
1010
+ const entries = await fs.readdir(path, { withFileTypes: true });
1011
+ const output = entries
1012
+ .map((entry) => `${entry.isDirectory() ? 'dir ' : 'file'}\t${entry.name}`)
1013
+ .join('\n');
1014
+ return [output || 'Directory is empty.', { path, count: entries.length }];
1015
+ }, {
1016
+ name: LocalListDirectoryToolName,
1017
+ description: 'List files and directories in a local directory.',
1018
+ schema: LocalListDirectoryToolSchema,
1019
+ responseFormat: Constants.CONTENT_AND_ARTIFACT,
1020
+ });
1021
+ }
1022
+ function createLocalCodingTools(config = {}, options = {}) {
1023
+ const checkpointer = options.checkpointer ??
1024
+ (config.fileCheckpointing === true
1025
+ ? createLocalFileCheckpointer({ fs: config.exec?.fs })
1026
+ : undefined);
1027
+ return [
1028
+ createLocalReadFileTool(config),
1029
+ createLocalWriteFileTool(config, checkpointer),
1030
+ createLocalEditFileTool(config, checkpointer),
1031
+ createLocalGrepSearchTool(config),
1032
+ createLocalGlobSearchTool(config),
1033
+ createLocalListDirectoryTool(config),
1034
+ createCompileCheckTool(config),
1035
+ createLocalBashExecutionTool({ config }),
1036
+ createLocalCodeExecutionTool(config),
1037
+ createLocalProgrammaticToolCallingTool(config),
1038
+ createLocalBashProgrammaticToolCallingTool(config),
1039
+ ];
1040
+ }
1041
+ /**
1042
+ * Variant of `createLocalCodingTools` that returns the bundle alongside
1043
+ * the file checkpointer so callers can later call
1044
+ * `bundle.checkpointer?.rewind()`.
1045
+ */
1046
+ function createLocalCodingToolBundle(config = {}, options = {}) {
1047
+ const checkpointer = options.checkpointer ??
1048
+ (config.fileCheckpointing === true
1049
+ ? createLocalFileCheckpointer({ fs: config.exec?.fs })
1050
+ : undefined);
1051
+ return {
1052
+ tools: createLocalCodingTools(config, { checkpointer }),
1053
+ checkpointer,
1054
+ };
1055
+ }
1056
+ function createLocalCodingToolDefinitions() {
1057
+ return [
1058
+ toolDefinition(Constants.READ_FILE, 'Read a local text file from the configured working directory with line numbers.', LocalReadFileToolSchema),
1059
+ toolDefinition(LocalWriteFileToolName, 'Create or overwrite a local text file in the configured working directory.', LocalWriteFileToolSchema),
1060
+ toolDefinition(LocalEditFileToolName, 'Apply exact text replacements to a local file.', LocalEditFileToolSchema),
1061
+ toolDefinition(LocalGrepSearchToolName, 'Search local files with ripgrep and return matching lines.', LocalGrepSearchToolSchema),
1062
+ toolDefinition(LocalGlobSearchToolName, 'Find local files matching a glob pattern.', LocalGlobSearchToolSchema),
1063
+ toolDefinition(LocalListDirectoryToolName, 'List files and directories in a local directory.', LocalListDirectoryToolSchema),
1064
+ createCompileCheckToolDefinition(),
1065
+ ];
1066
+ }
1067
+ function createLocalCodingToolRegistry() {
1068
+ return new Map(createLocalCodingToolDefinitions().map((definition) => [
1069
+ definition.name,
1070
+ definition,
1071
+ ]));
1072
+ }
1073
+
1074
+ export { LocalEditFileToolName, LocalEditFileToolSchema, LocalGlobSearchToolName, LocalGlobSearchToolSchema, LocalGrepSearchToolName, LocalGrepSearchToolSchema, LocalListDirectoryToolName, LocalListDirectoryToolSchema, LocalReadFileToolSchema, LocalWriteFileToolName, LocalWriteFileToolSchema, _resetRipgrepCacheForTests, createLocalCodingToolBundle, createLocalCodingToolDefinitions, createLocalCodingToolRegistry, createLocalCodingTools, createLocalEditFileTool, createLocalGlobSearchTool, createLocalGrepSearchTool, createLocalListDirectoryTool, createLocalReadFileTool, createLocalWriteFileTool };
1075
+ //# sourceMappingURL=LocalCodingTools.mjs.map