@causyne/agent 1.20.91 → 1.20.94
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/agentLoop.js +116 -26
- package/src/agentLoop.ts +121 -26
- package/src/contextManager.js +2 -0
- package/src/decideTools.js +9 -0
- package/src/decideTools.ts +9 -0
- package/src/decisionPolicy.js +119 -1
- package/src/decisionPolicy.ts +129 -1
- package/src/historyPruner.js +16 -1
- package/src/historyPruner.ts +13 -1
- package/src/sandbox.js +33 -7
- package/src/skills/skillResourceSafety.js +70 -0
- package/src/skills/skillResourceSafety.ts +77 -0
- package/src/smartToolsUse.js +28 -11
- package/src/smartToolsUse.ts +34 -11
- package/src/taskShape.js +28 -13
- package/src/taskShape.ts +31 -12
- package/src/tools/codeSearcher.js +349 -210
- package/src/tools/codeSearcher.ts +408 -0
- package/src/tools/codebaseSearch.js +182 -68
- package/src/tools/codebaseSearch.ts +221 -0
- package/src/tools/deferredMcpSearch.js +94 -40
- package/src/tools/deferredMcpSearch.ts +89 -30
- package/src/tools/fsFind.js +180 -115
- package/src/tools/fsFind.ts +228 -0
- package/src/tools/fsList.js +149 -69
- package/src/tools/fsList.ts +224 -0
- package/src/tools/fsSearch.js +192 -189
- package/src/tools/fsSearch.ts +241 -0
- package/src/tools/readNativeSkill.js +34 -42
- package/src/tools/readNativeSkill.ts +38 -36
- package/src/tools/searchRelevance.js +70 -0
- package/src/tools/searchRelevance.ts +72 -0
- package/src/tools/toolSelfRepair.js +56 -20
- package/src/tools/toolSelfRepair.ts +58 -19
- package/src/tools/walkerSafety.js +445 -0
- package/src/tools/walkerSafety.ts +516 -0
- package/src/tui/composerGeometry.js +45 -0
- package/src/tui/composerGeometry.ts +80 -0
- package/src/tui/homeView.js +10 -6
- package/src/tui/homeView.ts +10 -6
- package/src/tui/lineEditor.js +8 -0
- package/src/tui/prompt.js +9 -4
- package/src/userSkills.js +183 -203
- package/src/userSkills.ts +301 -0
- package/src/userSkills.d.ts +0 -26
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import fsSync from 'node:fs';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import {
|
|
7
|
+
DEFAULT_TIMEOUT_MS,
|
|
8
|
+
MAX_FILE_BYTES,
|
|
9
|
+
buildHomeGlobExcludes,
|
|
10
|
+
buildTopLevelHomeExcludes,
|
|
11
|
+
checkSearchScope,
|
|
12
|
+
compileSafeSearchRegex,
|
|
13
|
+
createTraversalGuard,
|
|
14
|
+
isSafeSymlinkTarget,
|
|
15
|
+
looksBinaryFile,
|
|
16
|
+
resolveSearchRoot,
|
|
17
|
+
shouldExcludeChild,
|
|
18
|
+
validateRegexSafety,
|
|
19
|
+
type SearchExecutionContext
|
|
20
|
+
} from './walkerSafety.js';
|
|
21
|
+
|
|
22
|
+
const execFileAsync = promisify(execFile);
|
|
23
|
+
const MAX_MATCHES = 100;
|
|
24
|
+
const RG_MAX_PER_FILE = 50;
|
|
25
|
+
|
|
26
|
+
export interface CodeSearchArgs {
|
|
27
|
+
query: string;
|
|
28
|
+
searchPath?: string | undefined;
|
|
29
|
+
isRegex?: boolean | undefined;
|
|
30
|
+
caseInsensitive?: boolean | undefined;
|
|
31
|
+
filePattern?: string | undefined;
|
|
32
|
+
astMode?: boolean | undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface CodeSearchMatch {
|
|
36
|
+
File: string;
|
|
37
|
+
LineNumber: number;
|
|
38
|
+
LineContent: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface CodeSearchResult {
|
|
42
|
+
success: boolean;
|
|
43
|
+
output?: string;
|
|
44
|
+
error?: string;
|
|
45
|
+
aborted?: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function getRipgrepBinary(): string | null {
|
|
49
|
+
const isWin = process.platform === 'win32';
|
|
50
|
+
const fixedCandidates = isWin
|
|
51
|
+
? ['C:\\Program Files\\ripgrep\\rg.exe']
|
|
52
|
+
: ['/opt/homebrew/bin/rg', '/usr/local/bin/rg', '/usr/bin/rg'];
|
|
53
|
+
|
|
54
|
+
for (const candidate of fixedCandidates) {
|
|
55
|
+
try {
|
|
56
|
+
if (fsSync.existsSync(candidate)) return candidate;
|
|
57
|
+
} catch {
|
|
58
|
+
// Ignore permission errors probing candidate paths.
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const pathEnv = process.env.PATH || '';
|
|
63
|
+
const exeName = isWin ? 'rg.exe' : 'rg';
|
|
64
|
+
for (const dir of pathEnv.split(path.delimiter)) {
|
|
65
|
+
if (!dir) continue;
|
|
66
|
+
const candidate = path.join(dir, exeName);
|
|
67
|
+
try {
|
|
68
|
+
if (fsSync.existsSync(candidate)) return candidate;
|
|
69
|
+
} catch {
|
|
70
|
+
// Ignore unreadable PATH directory entries.
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function globToSuffix(filePattern: string): string | null {
|
|
77
|
+
if (!filePattern || filePattern === '*') return null;
|
|
78
|
+
if (filePattern.startsWith('*.') && !filePattern.slice(2).includes('*')) {
|
|
79
|
+
return filePattern.slice(1).toLowerCase();
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function escapeLiteralRegex(text: string): string {
|
|
85
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function parseRgLine(line: string): CodeSearchMatch | null {
|
|
89
|
+
let idx = line.indexOf(':');
|
|
90
|
+
// Skip Windows drive letter prefix like C:\foo:12:bar
|
|
91
|
+
if (idx === 1 && /^[a-zA-Z]$/.test(line[0] ?? '') && (line[2] === '\\' || line[2] === '/')) {
|
|
92
|
+
idx = line.indexOf(':', 2);
|
|
93
|
+
}
|
|
94
|
+
while (idx > 0) {
|
|
95
|
+
const nextColon = line.indexOf(':', idx + 1);
|
|
96
|
+
if (nextColon === -1) return null;
|
|
97
|
+
const lineNumStr = line.slice(idx + 1, nextColon);
|
|
98
|
+
if (lineNumStr.length > 0 && /^\d+$/.test(lineNumStr)) {
|
|
99
|
+
return {
|
|
100
|
+
File: line.slice(0, idx),
|
|
101
|
+
LineNumber: Number.parseInt(lineNumStr, 10) || 0,
|
|
102
|
+
LineContent: line.slice(nextColon + 1).trim().slice(0, 300)
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
idx = nextColon;
|
|
106
|
+
}
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function isInvalidGlob(filePattern: string): boolean {
|
|
111
|
+
return (
|
|
112
|
+
filePattern.startsWith('-') ||
|
|
113
|
+
/[\x00-\x1f\r\n]/.test(filePattern)
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export const codeSearcher = {
|
|
118
|
+
schema: {
|
|
119
|
+
name: 'code.search_ripgrep',
|
|
120
|
+
description:
|
|
121
|
+
'Fast regex, literal string, and symbol search across codebases using ripgrep with bounded async Node fallback.',
|
|
122
|
+
parameters: {
|
|
123
|
+
type: 'object',
|
|
124
|
+
properties: {
|
|
125
|
+
query: {
|
|
126
|
+
type: 'string',
|
|
127
|
+
description: 'The exact string, symbol, or regular expression pattern to look for across files.'
|
|
128
|
+
},
|
|
129
|
+
searchPath: {
|
|
130
|
+
type: 'string',
|
|
131
|
+
description: 'Directory or file path to search. Defaults to workspace root.'
|
|
132
|
+
},
|
|
133
|
+
isRegex: {
|
|
134
|
+
type: 'boolean',
|
|
135
|
+
description: 'If true, treats query as a regular expression pattern. If false, treats as literal string.'
|
|
136
|
+
},
|
|
137
|
+
caseInsensitive: {
|
|
138
|
+
type: 'boolean',
|
|
139
|
+
description: 'If true, performs case-insensitive search (default true).'
|
|
140
|
+
},
|
|
141
|
+
filePattern: {
|
|
142
|
+
type: 'string',
|
|
143
|
+
description: 'Optional glob filter (e.g. "*.js", "*.py", "*.kt", "*.ts") to restrict file extensions.'
|
|
144
|
+
},
|
|
145
|
+
astMode: {
|
|
146
|
+
type: 'boolean',
|
|
147
|
+
description: 'If true, filters results specifically for symbol definitions (classes, functions, interfaces, structs, defs).'
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
required: ['query']
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
|
|
154
|
+
async execute(
|
|
155
|
+
args: CodeSearchArgs,
|
|
156
|
+
context?: SearchExecutionContext
|
|
157
|
+
): Promise<CodeSearchResult> {
|
|
158
|
+
try {
|
|
159
|
+
if (!args || typeof args.query !== 'string' || args.query.length === 0) {
|
|
160
|
+
return { success: false, error: 'Query parameter is required.' };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const query = args.query;
|
|
164
|
+
const isRegex = args.isRegex === true;
|
|
165
|
+
const caseInsensitive = args.caseInsensitive !== false;
|
|
166
|
+
const filePattern = typeof args.filePattern === 'string' ? args.filePattern.trim() : '*';
|
|
167
|
+
const astMode = args.astMode === true;
|
|
168
|
+
|
|
169
|
+
if (filePattern && filePattern !== '*' && isInvalidGlob(filePattern)) {
|
|
170
|
+
return { success: false, error: `Invalid filePattern glob: ${filePattern}` };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (isRegex) {
|
|
174
|
+
const unsafeReason = validateRegexSafety(query);
|
|
175
|
+
if (unsafeReason) {
|
|
176
|
+
return { success: false, error: unsafeReason };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const targetDir = resolveSearchRoot(args.searchPath, context);
|
|
181
|
+
const scope = checkSearchScope(targetDir, context);
|
|
182
|
+
if (!scope.allowed || !scope.realPath) {
|
|
183
|
+
return { success: false, error: scope.error || `Search path not allowed: ${targetDir}` };
|
|
184
|
+
}
|
|
185
|
+
const realTargetDir = scope.realPath;
|
|
186
|
+
|
|
187
|
+
let targetStat;
|
|
188
|
+
try {
|
|
189
|
+
targetStat = await fs.stat(realTargetDir);
|
|
190
|
+
} catch {
|
|
191
|
+
return { success: false, error: `Search path does not exist: ${targetDir}` };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const matches: CodeSearchMatch[] = [];
|
|
195
|
+
const rgBin = getRipgrepBinary();
|
|
196
|
+
let engineLabel = rgBin ? `Ripgrep Binary (${rgBin})` : 'Node Async Stream Engine';
|
|
197
|
+
let useNodeFallback = !rgBin;
|
|
198
|
+
let stoppedNotice = '';
|
|
199
|
+
|
|
200
|
+
if (rgBin) {
|
|
201
|
+
const rgArgs = [
|
|
202
|
+
'-n',
|
|
203
|
+
'--no-heading',
|
|
204
|
+
'--with-filename',
|
|
205
|
+
`--max-count=${RG_MAX_PER_FILE}`,
|
|
206
|
+
`--max-filesize=${MAX_FILE_BYTES}`
|
|
207
|
+
];
|
|
208
|
+
if (caseInsensitive) rgArgs.push('-i');
|
|
209
|
+
if (!isRegex && !astMode) rgArgs.push('-F');
|
|
210
|
+
if (filePattern && filePattern !== '*') rgArgs.push('-g', filePattern);
|
|
211
|
+
|
|
212
|
+
for (const glob of buildHomeGlobExcludes()) {
|
|
213
|
+
rgArgs.push('-g', glob);
|
|
214
|
+
}
|
|
215
|
+
for (const glob of buildTopLevelHomeExcludes(realTargetDir)) {
|
|
216
|
+
rgArgs.push('-g', glob);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const effectiveQuery =
|
|
220
|
+
astMode && !isRegex
|
|
221
|
+
? `(class|function|def|interface|struct|const|let|var|type|func|module)\\s+[^\\s(]*${escapeLiteralRegex(query)}`
|
|
222
|
+
: query;
|
|
223
|
+
rgArgs.push('-e', effectiveQuery, '--', realTargetDir);
|
|
224
|
+
|
|
225
|
+
try {
|
|
226
|
+
const { stdout } = await execFileAsync(rgBin, rgArgs, {
|
|
227
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
228
|
+
timeout: DEFAULT_TIMEOUT_MS,
|
|
229
|
+
signal: context?.signal
|
|
230
|
+
});
|
|
231
|
+
for (const line of stdout.split('\n')) {
|
|
232
|
+
if (!line) continue;
|
|
233
|
+
if (matches.length >= MAX_MATCHES) break;
|
|
234
|
+
const parsed = parseRgLine(line);
|
|
235
|
+
if (parsed) matches.push(parsed);
|
|
236
|
+
}
|
|
237
|
+
} catch (rgErr: unknown) {
|
|
238
|
+
if (context?.signal?.aborted) {
|
|
239
|
+
return { success: false, aborted: true, error: 'Code search aborted.' };
|
|
240
|
+
}
|
|
241
|
+
const errObj = rgErr as {
|
|
242
|
+
code?: number | string | undefined;
|
|
243
|
+
killed?: boolean | undefined;
|
|
244
|
+
stdout?: string | undefined;
|
|
245
|
+
stderr?: string | undefined;
|
|
246
|
+
};
|
|
247
|
+
if (typeof errObj.stdout === 'string' && errObj.stdout.length > 0) {
|
|
248
|
+
for (const line of errObj.stdout.split('\n')) {
|
|
249
|
+
if (!line) continue;
|
|
250
|
+
if (matches.length >= MAX_MATCHES) break;
|
|
251
|
+
const parsed = parseRgLine(line);
|
|
252
|
+
if (parsed) matches.push(parsed);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (errObj.killed) {
|
|
256
|
+
stoppedNotice = `stopped after ${DEFAULT_TIMEOUT_MS}ms budget`;
|
|
257
|
+
} else if (errObj.code === 1) {
|
|
258
|
+
// Exit code 1 means zero matches found.
|
|
259
|
+
} else if (errObj.code === 2) {
|
|
260
|
+
const stderr = String(errObj.stderr || '').trim();
|
|
261
|
+
if (/regex parse error|error parsing regex/i.test(stderr)) {
|
|
262
|
+
return { success: false, error: `Invalid regex pattern: ${stderr}` };
|
|
263
|
+
}
|
|
264
|
+
useNodeFallback = true;
|
|
265
|
+
} else if (errObj.code === 'ENOENT' || errObj.code === 'EACCES') {
|
|
266
|
+
useNodeFallback = true;
|
|
267
|
+
} else if (matches.length === 0) {
|
|
268
|
+
useNodeFallback = true;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (useNodeFallback && matches.length === 0) {
|
|
274
|
+
engineLabel = 'Node Async Stream Engine';
|
|
275
|
+
let regex: RegExp;
|
|
276
|
+
if (astMode && !isRegex) {
|
|
277
|
+
const astPat = `(class|function|def|interface|struct|const|let|var|type|func|module)\\s+[^\\s(]*${escapeLiteralRegex(query)}`;
|
|
278
|
+
regex = new RegExp(astPat, caseInsensitive ? 'i' : '');
|
|
279
|
+
} else {
|
|
280
|
+
const compiled = compileSafeSearchRegex(query, { isRegex, caseInsensitive });
|
|
281
|
+
if (!compiled.regex) {
|
|
282
|
+
return { success: false, error: compiled.error || 'Invalid regex pattern.' };
|
|
283
|
+
}
|
|
284
|
+
regex = compiled.regex;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const extFilter = globToSuffix(filePattern);
|
|
288
|
+
const guard = createTraversalGuard({ signal: context?.signal });
|
|
289
|
+
const seen = new Set<string>();
|
|
290
|
+
|
|
291
|
+
const scanFile = async (filePath: string): Promise<void> => {
|
|
292
|
+
if (matches.length >= MAX_MATCHES || guard.checkStopped()) return;
|
|
293
|
+
if (extFilter && !filePath.toLowerCase().endsWith(extFilter)) return;
|
|
294
|
+
if (!guard.countFile()) return;
|
|
295
|
+
|
|
296
|
+
let fileStat;
|
|
297
|
+
try {
|
|
298
|
+
fileStat = await fs.stat(filePath);
|
|
299
|
+
} catch {
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (fileStat.size > MAX_FILE_BYTES) return;
|
|
303
|
+
if (await looksBinaryFile(filePath)) return;
|
|
304
|
+
|
|
305
|
+
let content: string;
|
|
306
|
+
try {
|
|
307
|
+
content = await fs.readFile(filePath, 'utf8');
|
|
308
|
+
} catch {
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const lines = content.split('\n');
|
|
313
|
+
for (let i = 0; i < lines.length; i++) {
|
|
314
|
+
if (matches.length >= MAX_MATCHES || guard.checkStopped()) break;
|
|
315
|
+
const line = lines[i]!;
|
|
316
|
+
if (regex.test(line)) {
|
|
317
|
+
matches.push({
|
|
318
|
+
File: filePath,
|
|
319
|
+
LineNumber: i + 1,
|
|
320
|
+
LineContent: line.trim().slice(0, 300)
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
if (targetStat.isFile()) {
|
|
327
|
+
await scanFile(realTargetDir);
|
|
328
|
+
} else {
|
|
329
|
+
const queue: Array<{ dir: string; real: string; depth: number }> = [
|
|
330
|
+
{ dir: realTargetDir, real: realTargetDir, depth: 0 }
|
|
331
|
+
];
|
|
332
|
+
while (queue.length > 0 && matches.length < MAX_MATCHES) {
|
|
333
|
+
if (guard.checkStopped()) break;
|
|
334
|
+
const current = queue.shift()!;
|
|
335
|
+
if (seen.has(current.real)) continue;
|
|
336
|
+
if (!guard.enterDir(current.depth)) continue;
|
|
337
|
+
seen.add(current.real);
|
|
338
|
+
|
|
339
|
+
let dirents;
|
|
340
|
+
try {
|
|
341
|
+
dirents = await fs.readdir(current.dir, { withFileTypes: true });
|
|
342
|
+
} catch {
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
for (const dirent of dirents) {
|
|
347
|
+
if (matches.length >= MAX_MATCHES || guard.checkStopped()) break;
|
|
348
|
+
if (shouldExcludeChild(current.real, dirent.name)) continue;
|
|
349
|
+
const full = path.join(current.dir, dirent.name);
|
|
350
|
+
|
|
351
|
+
if (dirent.isDirectory()) {
|
|
352
|
+
try {
|
|
353
|
+
const childReal = await fs.realpath(full);
|
|
354
|
+
if (isSafeSymlinkTarget(childReal, realTargetDir, context) && !seen.has(childReal)) {
|
|
355
|
+
queue.push({ dir: full, real: childReal, depth: current.depth + 1 });
|
|
356
|
+
}
|
|
357
|
+
} catch {
|
|
358
|
+
// Ignore unreadable subdirectories.
|
|
359
|
+
}
|
|
360
|
+
} else if (dirent.isFile()) {
|
|
361
|
+
await scanFile(full);
|
|
362
|
+
} else if (dirent.isSymbolicLink()) {
|
|
363
|
+
try {
|
|
364
|
+
const linkReal = await fs.realpath(full);
|
|
365
|
+
if (!isSafeSymlinkTarget(linkReal, realTargetDir, context)) continue;
|
|
366
|
+
const linkStat = await fs.stat(linkReal);
|
|
367
|
+
if (linkStat.isDirectory()) {
|
|
368
|
+
if (!seen.has(linkReal)) {
|
|
369
|
+
queue.push({ dir: linkReal, real: linkReal, depth: current.depth + 1 });
|
|
370
|
+
}
|
|
371
|
+
} else if (linkStat.isFile()) {
|
|
372
|
+
await scanFile(full);
|
|
373
|
+
}
|
|
374
|
+
} catch {
|
|
375
|
+
// Ignore broken symlinks.
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
if (guard.stopReason === 'aborted') {
|
|
383
|
+
return { success: false, aborted: true, error: 'Code search aborted.' };
|
|
384
|
+
}
|
|
385
|
+
if (guard.stopReason) {
|
|
386
|
+
stoppedNotice = guard.stopNotice();
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
return {
|
|
391
|
+
success: true,
|
|
392
|
+
output: JSON.stringify(
|
|
393
|
+
{
|
|
394
|
+
engine: engineLabel,
|
|
395
|
+
query,
|
|
396
|
+
total_matches: matches.length,
|
|
397
|
+
...(stoppedNotice ? { stopped_reason: stoppedNotice } : {}),
|
|
398
|
+
matches: matches.length > 0 ? matches : 'No matches found in target codebase.'
|
|
399
|
+
},
|
|
400
|
+
null,
|
|
401
|
+
2
|
|
402
|
+
)
|
|
403
|
+
};
|
|
404
|
+
} catch (error: unknown) {
|
|
405
|
+
return { success: false, error: error instanceof Error ? error.message : String(error) };
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
};
|
|
@@ -1,75 +1,189 @@
|
|
|
1
|
-
import fs from 'fs/promises';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
async function
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
await walkDir(filePath, excludes, fileList);
|
|
12
|
-
} else {
|
|
13
|
-
fileList.push(filePath);
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { MAX_FILE_BYTES, checkSearchScope, compileSafeSearchRegex, createTraversalGuard, isSafeSymlinkTarget, looksBinaryFile, resolveSearchRoot, shouldExcludeChild } from './walkerSafety.js';
|
|
4
|
+
const MAX_MATCHES = 50;
|
|
5
|
+
async function* walkBounded(dir, rootReal, seen, guard, depth, context) {
|
|
6
|
+
if (!guard.enterDir(depth))
|
|
7
|
+
return;
|
|
8
|
+
let real;
|
|
9
|
+
try {
|
|
10
|
+
real = await fs.realpath(dir);
|
|
14
11
|
}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export const codebaseSearch = {
|
|
20
|
-
schema: {
|
|
21
|
-
name: 'codebase_search',
|
|
22
|
-
description: 'Find snippets of code natively. Understands architecture without shell commands.',
|
|
23
|
-
parameters: {
|
|
24
|
-
type: 'object',
|
|
25
|
-
properties: {
|
|
26
|
-
query: { type: 'string', description: 'The search query to find relevant code.' },
|
|
27
|
-
target_directories: { type: 'array', items: { type: 'string' }, description: 'Directories to search' }
|
|
28
|
-
},
|
|
29
|
-
required: ['query'],
|
|
30
|
-
additionalProperties: false
|
|
12
|
+
catch {
|
|
13
|
+
return;
|
|
31
14
|
}
|
|
32
|
-
|
|
33
|
-
|
|
15
|
+
if (!isSafeSymlinkTarget(real, rootReal, context))
|
|
16
|
+
return;
|
|
17
|
+
if (seen.has(real))
|
|
18
|
+
return;
|
|
19
|
+
seen.add(real);
|
|
20
|
+
let entries;
|
|
34
21
|
try {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
22
|
+
entries = await fs.readdir(dir, { withFileTypes: true });
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
for (const entry of entries) {
|
|
28
|
+
if (guard.checkStopped())
|
|
29
|
+
return;
|
|
30
|
+
if (shouldExcludeChild(real, entry.name))
|
|
31
|
+
continue;
|
|
32
|
+
const full = path.join(dir, entry.name);
|
|
33
|
+
if (entry.isDirectory()) {
|
|
34
|
+
yield* walkBounded(full, rootReal, seen, guard, depth + 1, context);
|
|
35
|
+
}
|
|
36
|
+
else if (entry.isFile()) {
|
|
37
|
+
yield full;
|
|
38
|
+
}
|
|
39
|
+
else if (entry.isSymbolicLink()) {
|
|
40
|
+
try {
|
|
41
|
+
const targetReal = await fs.realpath(full);
|
|
42
|
+
if (!isSafeSymlinkTarget(targetReal, rootReal, context))
|
|
43
|
+
continue;
|
|
44
|
+
const stat = await fs.stat(targetReal);
|
|
45
|
+
if (stat.isDirectory()) {
|
|
46
|
+
yield* walkBounded(targetReal, rootReal, seen, guard, depth + 1, context);
|
|
47
|
+
}
|
|
48
|
+
else if (stat.isFile()) {
|
|
49
|
+
yield full;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// Ignore broken symlinks.
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export const codebaseSearch = {
|
|
59
|
+
schema: {
|
|
60
|
+
name: 'codebase_search',
|
|
61
|
+
description: 'Find snippets of code safely across target workspace directories with bounded traversal and literal matching by default.',
|
|
62
|
+
parameters: {
|
|
63
|
+
type: 'object',
|
|
64
|
+
properties: {
|
|
65
|
+
query: { type: 'string', description: 'The search query to find relevant code.' },
|
|
66
|
+
target_directories: {
|
|
67
|
+
type: 'array',
|
|
68
|
+
items: { type: 'string' },
|
|
69
|
+
description: 'Directories or files to search'
|
|
70
|
+
},
|
|
71
|
+
isRegex: {
|
|
72
|
+
type: 'boolean',
|
|
73
|
+
description: 'Optional. Treat query as a regular expression (defaults to literal case-insensitive search).'
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
required: ['query'],
|
|
77
|
+
additionalProperties: false
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
async execute(args, context) {
|
|
57
81
|
try {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
82
|
+
if (!args || typeof args.query !== 'string' || args.query.length === 0) {
|
|
83
|
+
return { success: false, error: 'Missing required "query" argument.' };
|
|
84
|
+
}
|
|
85
|
+
const compiled = compileSafeSearchRegex(args.query, {
|
|
86
|
+
isRegex: args.isRegex === true,
|
|
87
|
+
caseInsensitive: true
|
|
88
|
+
});
|
|
89
|
+
if (!compiled.regex) {
|
|
90
|
+
return { success: false, error: compiled.error || 'Invalid query pattern.' };
|
|
91
|
+
}
|
|
92
|
+
const regex = compiled.regex;
|
|
93
|
+
const dirs = Array.isArray(args.target_directories) && args.target_directories.length > 0
|
|
94
|
+
? args.target_directories
|
|
95
|
+
: ['.'];
|
|
96
|
+
const scopedRoots = [];
|
|
97
|
+
for (const dir of dirs) {
|
|
98
|
+
if (typeof dir !== 'string' || !dir.trim())
|
|
99
|
+
continue;
|
|
100
|
+
const candidate = resolveSearchRoot(dir, context);
|
|
101
|
+
const scope = checkSearchScope(candidate, context);
|
|
102
|
+
if (!scope.allowed || !scope.realPath) {
|
|
103
|
+
return {
|
|
104
|
+
success: false,
|
|
105
|
+
error: scope.error || `Target directory not allowed: ${dir}`
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
scopedRoots.push({ requested: candidate, realPath: scope.realPath });
|
|
109
|
+
}
|
|
110
|
+
if (scopedRoots.length === 0) {
|
|
111
|
+
const fallback = resolveSearchRoot('.', context);
|
|
112
|
+
const scope = checkSearchScope(fallback, context);
|
|
113
|
+
if (!scope.allowed || !scope.realPath) {
|
|
114
|
+
return { success: false, error: scope.error || `Target directory not allowed: ${fallback}` };
|
|
115
|
+
}
|
|
116
|
+
scopedRoots.push({ requested: fallback, realPath: scope.realPath });
|
|
117
|
+
}
|
|
118
|
+
const guard = createTraversalGuard({ signal: context?.signal });
|
|
119
|
+
const results = [];
|
|
120
|
+
const scanFile = async (file) => {
|
|
121
|
+
if (!guard.countFile())
|
|
122
|
+
return;
|
|
123
|
+
let stat;
|
|
124
|
+
try {
|
|
125
|
+
stat = await fs.stat(file);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (stat.size > MAX_FILE_BYTES)
|
|
131
|
+
return;
|
|
132
|
+
if (await looksBinaryFile(file))
|
|
133
|
+
return;
|
|
134
|
+
let content;
|
|
135
|
+
try {
|
|
136
|
+
content = await fs.readFile(file, 'utf8');
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const lines = content.split('\n');
|
|
142
|
+
for (let i = 0; i < lines.length; i++) {
|
|
143
|
+
if (guard.checkStopped())
|
|
144
|
+
break;
|
|
145
|
+
const line = lines[i];
|
|
146
|
+
if (regex.test(line)) {
|
|
147
|
+
results.push(`${file}:${i + 1}:${line.trim().slice(0, 300)}`);
|
|
148
|
+
if (results.length >= MAX_MATCHES)
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
for (const root of scopedRoots) {
|
|
154
|
+
if (results.length >= MAX_MATCHES || guard.checkStopped())
|
|
155
|
+
break;
|
|
156
|
+
let stat;
|
|
157
|
+
try {
|
|
158
|
+
stat = await fs.stat(root.realPath);
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (stat.isFile()) {
|
|
164
|
+
await scanFile(root.realPath);
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
const seen = new Set();
|
|
168
|
+
for await (const file of walkBounded(root.realPath, root.realPath, seen, guard, 0, context)) {
|
|
169
|
+
if (results.length >= MAX_MATCHES || guard.checkStopped())
|
|
170
|
+
break;
|
|
171
|
+
await scanFile(file);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if (guard.stopReason === 'aborted') {
|
|
175
|
+
return { success: false, aborted: true, error: 'Codebase search aborted.' };
|
|
64
176
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
177
|
+
const stopSuffix = guard.stopReason ? `\n\n[${guard.stopNotice()}]` : '';
|
|
178
|
+
return {
|
|
179
|
+
success: true,
|
|
180
|
+
output: results.length > 0
|
|
181
|
+
? results.join('\n') + stopSuffix
|
|
182
|
+
: `No results found.${guard.stopReason ? ` (${guard.stopNotice()})` : ''}`
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
return { success: false, error: error instanceof Error ? error.message : String(error) };
|
|
187
|
+
}
|
|
73
188
|
}
|
|
74
|
-
}
|
|
75
189
|
};
|