@vessel-agent/basic-tools 0.0.0-stage → 2.3.0-beta.2

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.
@@ -0,0 +1,601 @@
1
+ /**
2
+ * basic-tools grep 工具(W1-3 纯移动自 index.ts,零行为变更):
3
+ * ripgrep 引擎文本搜索(纯 TS 兜底),pattern 当数据收,结构化 file:line:content。
4
+ */
5
+
6
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
7
+ import * as path from 'node:path';
8
+ import type { ToolContext, ToolDefinition } from '@vessel-agent/core';
9
+ import { activeBoundary } from '../call-scope.js';
10
+ import type { BasicToolsConfig } from '../config.js';
11
+ import {
12
+ dependsOnBaseCwd,
13
+ escapeRegExp,
14
+ evaluatePath,
15
+ type PathBoundary,
16
+ resolveCallCwd,
17
+ resolveToolPath,
18
+ } from '../path-boundary.js';
19
+ import {
20
+ boundToolOutput,
21
+ CANCELLED_TEXT,
22
+ isRecord,
23
+ PATH_DENIED_TEXT,
24
+ readNumber,
25
+ readString,
26
+ } from '../shared.js';
27
+ import { splitLines } from '../text.js';
28
+
29
+ // ── grep(q-tooling:ripgrep 引擎文本搜索)─────────────────────────────
30
+ //
31
+ // 补 codegraph 符号搜索之外的**文本**搜索:pattern 当数据收(argv 数组直传 rg,
32
+ // 不经 shell,无引号/展开问题),结构化输出 file:line:content(上下文行 file-line-content,
33
+ // rg 同款约定)。引擎优先系统 rg(Bun.which 探测,缓存);无 rg 时退纯 TS 扫描器
34
+ // (同一套参数语义:glob/context/max_count),结果形状一致。
35
+ // 只读工具:权限与 read 同口径(敏感路径 deny、allowed_roots 越界 ask),concurrencySafe。
36
+
37
+ /** 缺省总匹配数上限(防一次灌满窗口;超出截断并标注)。 */
38
+ const DEFAULT_GREP_MAX_COUNT = 200;
39
+ /** grep deadline:rg 子进程超时杀;兜底扫描器逐文件 + 文件内每 1024 行查(结果标注 timed out)。 */
40
+ const GREP_TIMEOUT_MS = 30_000;
41
+ /** 兜底扫描器单文件上限(搜索只跳大文件,不拒整次调用)。 */
42
+ const GREP_FALLBACK_MAX_FILE_BYTES = 1024 * 1024;
43
+ /** 兜底扫描器文件数软上限(超出截断 + 标注)。 */
44
+ const GREP_FALLBACK_MAX_FILES = 20_000;
45
+ /** 兜底扫描器跳过的目录(rg 默认 .gitignore 语义的近似;隐藏目录另跳)。 */
46
+ const GREP_IGNORED_DIRS = new Set([
47
+ 'node_modules',
48
+ '.git',
49
+ 'dist',
50
+ 'build',
51
+ 'out',
52
+ 'coverage',
53
+ '.next',
54
+ '.nuxt',
55
+ '.output',
56
+ '.svelte-kit',
57
+ 'target',
58
+ '__pycache__',
59
+ '.venv',
60
+ 'venv',
61
+ '.cache',
62
+ '.turbo',
63
+ '.parcel-cache',
64
+ ]);
65
+
66
+ interface GrepEntry {
67
+ file: string;
68
+ line: number;
69
+ content: string;
70
+ kind: 'match' | 'context';
71
+ }
72
+
73
+ interface GrepOptions {
74
+ pattern: string;
75
+ ignoreCase: boolean;
76
+ fixedStrings: boolean;
77
+ glob?: string;
78
+ context: number;
79
+ maxCount: number;
80
+ }
81
+
82
+ interface GrepResult {
83
+ entries: GrepEntry[];
84
+ matchCount: number;
85
+ fileCount: number;
86
+ truncated: boolean;
87
+ engine: 'rg' | 'builtin';
88
+ timedOut: boolean;
89
+ error?: string;
90
+ }
91
+
92
+ /** rg 二进制探测缓存(undefined=未探测;null=没有)。 */
93
+ let rgBinaryCache: string | null | undefined;
94
+
95
+ function findRgBinary(): string | null {
96
+ if (rgBinaryCache === undefined) {
97
+ try {
98
+ rgBinaryCache = Bun.which('rg') ?? null;
99
+ } catch {
100
+ rgBinaryCache = null;
101
+ }
102
+ }
103
+ return rgBinaryCache;
104
+ }
105
+
106
+ /**
107
+ * glob → 正则:支持 `**`(跨目录)/ `*`(单层)/ `?` / `{a,b}` alternation。
108
+ * 不含 `/` 的 glob 按 basename 匹配(rg --glob 同款语义),含 `/` 按相对路径匹配。
109
+ */
110
+ function globToRegExp(glob: string): RegExp {
111
+ let re = '';
112
+ let braceDepth = 0;
113
+ const normalized = glob.replace(/\\/g, '/').replace(/^\//, '');
114
+ for (let i = 0; i < normalized.length; i++) {
115
+ const c = normalized[i] ?? '';
116
+ if (c === '*') {
117
+ if (normalized[i + 1] === '*') {
118
+ re += '.*';
119
+ i++;
120
+ if (normalized[i + 1] === '/') i++;
121
+ } else {
122
+ re += '[^/]*';
123
+ }
124
+ } else if (c === '?') {
125
+ re += '[^/]';
126
+ } else if (c === '{') {
127
+ braceDepth++;
128
+ re += '(?:';
129
+ } else if (c === '}' && braceDepth > 0) {
130
+ braceDepth--;
131
+ re += ')';
132
+ } else if (c === ',' && braceDepth > 0) {
133
+ re += '|';
134
+ } else {
135
+ re += escapeRegExp(c);
136
+ }
137
+ }
138
+ return new RegExp(`^${re}$`);
139
+ }
140
+
141
+ function globMatches(glob: string, relPath: string): boolean {
142
+ const normalized = relPath.replace(/\\/g, '/');
143
+ const re = globToRegExp(glob);
144
+ if (glob.includes('/') || glob.includes('\\')) return re.test(normalized);
145
+ const base = normalized.split('/').pop() ?? normalized;
146
+ return re.test(base);
147
+ }
148
+
149
+ /** rg --json 事件流 → 结构化条目;到 maxCount 即杀进程(总量闸,非 rg -m 的每文件闸)。 */
150
+ async function runRg(
151
+ rgBinary: string,
152
+ rootDir: string,
153
+ target: string,
154
+ opts: GrepOptions,
155
+ signal: AbortSignal | undefined,
156
+ ): Promise<GrepResult> {
157
+ const argv = [rgBinary, '--json', '--no-config', '--no-messages'];
158
+ if (opts.ignoreCase) argv.push('-i');
159
+ if (opts.fixedStrings) argv.push('-F');
160
+ if (opts.context > 0) argv.push('-C', String(opts.context));
161
+ if (opts.glob !== undefined) argv.push('--glob', opts.glob);
162
+ argv.push('--', opts.pattern, target);
163
+
164
+ const result: GrepResult = {
165
+ entries: [],
166
+ matchCount: 0,
167
+ fileCount: 0,
168
+ truncated: false,
169
+ engine: 'rg',
170
+ timedOut: false,
171
+ };
172
+ const files = new Set<string>();
173
+ let proc: ReturnType<typeof Bun.spawn>;
174
+ try {
175
+ proc = Bun.spawn({
176
+ cmd: argv,
177
+ cwd: rootDir,
178
+ stdout: 'pipe',
179
+ stderr: 'pipe',
180
+ stdin: 'ignore',
181
+ windowsHide: true,
182
+ });
183
+ } catch (error) {
184
+ return { ...result, error: `rg spawn failed: ${String(error)}` };
185
+ }
186
+
187
+ let timer: ReturnType<typeof setTimeout> | undefined;
188
+ const deadline = new Promise<void>((resolve) => {
189
+ timer = setTimeout(() => {
190
+ result.timedOut = true;
191
+ try {
192
+ proc.kill();
193
+ } catch {
194
+ // 已退出
195
+ }
196
+ resolve();
197
+ }, GREP_TIMEOUT_MS);
198
+ });
199
+ const onAbort = (): void => {
200
+ try {
201
+ proc.kill();
202
+ } catch {
203
+ // 已退出
204
+ }
205
+ };
206
+ signal?.addEventListener('abort', onAbort, { once: true });
207
+
208
+ try {
209
+ const reader = (proc.stdout as ReadableStream<Uint8Array>).getReader();
210
+ const decoder = new TextDecoder();
211
+ let buffer = '';
212
+ let stop = false;
213
+ const consumeLine = (line: string): boolean => {
214
+ if (line === '') return false;
215
+ let event: unknown;
216
+ try {
217
+ event = JSON.parse(line);
218
+ } catch {
219
+ return false;
220
+ }
221
+ if (!isRecord(event)) return false;
222
+ const type = event.type;
223
+ if (type !== 'match' && type !== 'context') return false;
224
+ const data = isRecord(event.data) ? event.data : {};
225
+ const pathText = isRecord(data.path) ? data.path.text : undefined;
226
+ const linesText = isRecord(data.lines) ? data.lines.text : undefined;
227
+ const lineNumber = data.line_number;
228
+ if (
229
+ typeof pathText !== 'string' ||
230
+ typeof linesText !== 'string' ||
231
+ typeof lineNumber !== 'number'
232
+ ) {
233
+ return false;
234
+ }
235
+ if (type === 'match') {
236
+ if (result.matchCount >= opts.maxCount) {
237
+ result.truncated = true;
238
+ return true; // 停止信号
239
+ }
240
+ result.matchCount++;
241
+ files.add(pathText);
242
+ }
243
+ result.entries.push({
244
+ file: pathText,
245
+ line: lineNumber,
246
+ content: linesText.replace(/\r?\n$/, ''),
247
+ kind: type,
248
+ });
249
+ return false;
250
+ };
251
+ while (!stop) {
252
+ const chunk = await Promise.race([
253
+ reader.read(),
254
+ deadline.then(() => ({ done: true as const, value: undefined })),
255
+ ]);
256
+ if (chunk.done) break;
257
+ buffer += decoder.decode(chunk.value, { stream: true });
258
+ let nl = buffer.indexOf('\n');
259
+ while (nl >= 0) {
260
+ const line = buffer.slice(0, nl);
261
+ buffer = buffer.slice(nl + 1);
262
+ if (consumeLine(line)) {
263
+ stop = true;
264
+ break;
265
+ }
266
+ nl = buffer.indexOf('\n');
267
+ }
268
+ if (signal?.aborted) break;
269
+ }
270
+ if (stop || result.timedOut || signal?.aborted) {
271
+ try {
272
+ proc.kill();
273
+ } catch {
274
+ // 已退出
275
+ }
276
+ }
277
+ const exitCode = await proc.exited;
278
+ // rg 退出码:0=有匹配,1=无匹配,2=错误(被杀/截断时不视为错误)。
279
+ if (exitCode === 2 && !result.truncated && !result.timedOut && !signal?.aborted) {
280
+ let stderrText = '';
281
+ try {
282
+ stderrText = await new Response(proc.stderr as ReadableStream<Uint8Array>).text();
283
+ } catch {
284
+ // 忽略
285
+ }
286
+ result.error = `rg error: ${stderrText.trim().slice(0, 500) || 'exit 2'}`;
287
+ }
288
+ } finally {
289
+ if (timer !== undefined) clearTimeout(timer);
290
+ signal?.removeEventListener('abort', onAbort);
291
+ }
292
+ result.fileCount = files.size;
293
+ return result;
294
+ }
295
+
296
+ /**
297
+ * 单文件扫描(兜底引擎):匹配行 + 前后 context,全局 matchCount 闸。
298
+ * 返回 true=停止(总量已满或 deadline 到;后者置 result.timedOut)。
299
+ * deadline 文件内也查(每 1024 行一次,摊薄 Date.now 开销):
300
+ * 单文件≤1MiB 但正则回溯慢时不至于整文件扫完才超时。
301
+ */
302
+ function grepScanFile(
303
+ relPath: string,
304
+ absolute: string,
305
+ regex: RegExp,
306
+ opts: GrepOptions,
307
+ result: GrepResult,
308
+ files: Set<string>,
309
+ startedAt: number,
310
+ ): boolean {
311
+ let stat: ReturnType<typeof statSync>;
312
+ try {
313
+ stat = statSync(absolute);
314
+ } catch {
315
+ return false;
316
+ }
317
+ if (!stat.isFile() || stat.size > GREP_FALLBACK_MAX_FILE_BYTES) return false;
318
+ let text: string;
319
+ try {
320
+ text = readFileSync(absolute, 'utf-8');
321
+ } catch {
322
+ return false;
323
+ }
324
+ if (text.includes('\0')) return false;
325
+ const lines = splitLines(text);
326
+ let pendingAfter = 0;
327
+ let emittedUpTo = -1;
328
+ const ring: Array<{ line: number; content: string }> = [];
329
+ for (let i = 0; i < lines.length; i++) {
330
+ if ((i & 1023) === 0 && Date.now() - startedAt > GREP_TIMEOUT_MS) {
331
+ result.timedOut = true;
332
+ return true;
333
+ }
334
+ const lineNo = i + 1;
335
+ const content = lines[i] ?? '';
336
+ if (regex.test(content)) {
337
+ if (result.matchCount >= opts.maxCount) {
338
+ result.truncated = true;
339
+ return true;
340
+ }
341
+ for (const item of ring) {
342
+ if (item.line > emittedUpTo) {
343
+ result.entries.push({
344
+ file: relPath,
345
+ line: item.line,
346
+ content: item.content,
347
+ kind: 'context',
348
+ });
349
+ emittedUpTo = item.line;
350
+ }
351
+ }
352
+ result.entries.push({ file: relPath, line: lineNo, content, kind: 'match' });
353
+ emittedUpTo = lineNo;
354
+ result.matchCount++;
355
+ files.add(relPath);
356
+ pendingAfter = opts.context;
357
+ } else if (pendingAfter > 0 && lineNo > emittedUpTo) {
358
+ result.entries.push({ file: relPath, line: lineNo, content, kind: 'context' });
359
+ emittedUpTo = lineNo;
360
+ pendingAfter--;
361
+ }
362
+ if (opts.context > 0) {
363
+ ring.push({ line: lineNo, content });
364
+ if (ring.length > opts.context) ring.shift();
365
+ }
366
+ }
367
+ return false;
368
+ }
369
+
370
+ /** 兜底引擎:递归扫描(跳忽略/隐藏目录与符号链接目录),参数语义与 rg 路径一致。 */
371
+ function grepFallback(
372
+ rootDir: string,
373
+ target: string,
374
+ opts: GrepOptions,
375
+ signal: AbortSignal | undefined,
376
+ ): GrepResult {
377
+ const result: GrepResult = {
378
+ entries: [],
379
+ matchCount: 0,
380
+ fileCount: 0,
381
+ truncated: false,
382
+ engine: 'builtin',
383
+ timedOut: false,
384
+ };
385
+ const files = new Set<string>();
386
+ let regex: RegExp;
387
+ try {
388
+ regex = new RegExp(
389
+ opts.fixedStrings ? escapeRegExp(opts.pattern) : opts.pattern,
390
+ opts.ignoreCase ? 'i' : '',
391
+ );
392
+ } catch (error) {
393
+ return { ...result, error: `invalid pattern: ${String(error)}` };
394
+ }
395
+ const startedAt = Date.now();
396
+ let scanned = 0;
397
+ const scanOne = (relPath: string, absolute: string): boolean => {
398
+ scanned++;
399
+ if (scanned > GREP_FALLBACK_MAX_FILES) {
400
+ result.truncated = true;
401
+ return true;
402
+ }
403
+ if (Date.now() - startedAt > GREP_TIMEOUT_MS) {
404
+ result.timedOut = true;
405
+ return true;
406
+ }
407
+ return grepScanFile(relPath, absolute, regex, opts, result, files, startedAt);
408
+ };
409
+ if (target !== '.') {
410
+ // 单文件目标:relPath 用 basename(与 rg 路径 cwd=dirname 口径一致);glob 同样生效。
411
+ if (opts.glob === undefined || globMatches(opts.glob, target)) {
412
+ scanOne(target, path.join(rootDir, target));
413
+ }
414
+ result.fileCount = files.size;
415
+ return result;
416
+ }
417
+ const walk = (dir: string, rel: string): boolean => {
418
+ let entries: Array<{ name: string; isDirectory(): boolean; isFile(): boolean }>;
419
+ try {
420
+ entries = readdirSync(dir, { withFileTypes: true });
421
+ } catch {
422
+ return false;
423
+ }
424
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
425
+ for (const entry of entries) {
426
+ if (signal?.aborted) return true;
427
+ const name = entry.name;
428
+ const childRel = rel === '' ? name : `${rel}/${name}`;
429
+ const childAbs = path.join(dir, name);
430
+ if (entry.isDirectory()) {
431
+ if (GREP_IGNORED_DIRS.has(name) || name.startsWith('.')) continue;
432
+ if (walk(childAbs, childRel)) return true;
433
+ } else if (entry.isFile()) {
434
+ // 与 rg 默认一致:隐藏文件跳过(显式单文件目标不受此限)。
435
+ if (name.startsWith('.')) continue;
436
+ if (opts.glob !== undefined && !globMatches(opts.glob, childRel)) continue;
437
+ if (scanOne(childRel, childAbs)) return true;
438
+ }
439
+ // 符号链接一律跳过(防环;rg 默认也不跟随)
440
+ }
441
+ return false;
442
+ };
443
+ walk(rootDir, '');
444
+ result.fileCount = files.size;
445
+ return result;
446
+ }
447
+
448
+ /** 结构化渲染:match=file:line:content,context=file-line-content;不连续组间 '--'。 */
449
+ function renderGrep(result: GrepResult, rootDisplay: string, opts: GrepOptions): string {
450
+ if (result.error !== undefined) return `错误:grep 失败:${result.error}`;
451
+ const lines: string[] = [];
452
+ let prev: GrepEntry | undefined;
453
+ for (const entry of result.entries) {
454
+ if (prev !== undefined && (prev.file !== entry.file || entry.line > prev.line + 1)) {
455
+ lines.push('--');
456
+ }
457
+ const sep = entry.kind === 'match' ? ':' : '-';
458
+ lines.push(`${entry.file}${sep}${entry.line}${sep}${entry.content}`);
459
+ prev = entry;
460
+ }
461
+ const notes: string[] = [];
462
+ if (result.truncated) notes.push(`truncated at max_count=${opts.maxCount}`);
463
+ if (result.timedOut) notes.push(`timed out after ${GREP_TIMEOUT_MS}ms`);
464
+ const summary =
465
+ result.matchCount === 0
466
+ ? `no matches for ${JSON.stringify(opts.pattern)} (root: ${rootDisplay})`
467
+ : `${result.matchCount} matches in ${result.fileCount} files (root: ${rootDisplay})`;
468
+ const engineNote = `engine: ${result.engine}${notes.length > 0 ? `; ${notes.join('; ')}` : ''}`;
469
+ if (lines.length === 0) return `${summary}\n${engineNote}`;
470
+ return `${lines.join('\n')}\n\n${summary}\n${engineNote}`;
471
+ }
472
+
473
+ /** grep 入口:参数校验 → 路径边界 → 引擎选择(rg 优先)→ 渲染。 */
474
+ async function runGrep(
475
+ args: unknown,
476
+ ctx: ToolContext,
477
+ boundary: PathBoundary,
478
+ config: BasicToolsConfig,
479
+ ): Promise<string> {
480
+ const signal = ctx.signal;
481
+ if (signal?.aborted) return CANCELLED_TEXT;
482
+ if (!isRecord(args)) return '错误:grep 需要 { pattern: string }';
483
+ const pattern = readString(args, 'pattern');
484
+ if (pattern === '') return '错误:pattern 不能为空';
485
+
486
+ const context = readNumber(args, 'context') ?? 0;
487
+ if (!Number.isInteger(context) || context < 0 || context > 50) {
488
+ return '错误:context 必须是 0-50 的整数';
489
+ }
490
+ const maxCount = readNumber(args, 'max_count') ?? DEFAULT_GREP_MAX_COUNT;
491
+ if (!Number.isInteger(maxCount) || maxCount < 1) {
492
+ return '错误:max_count 必须是不小于 1 的整数';
493
+ }
494
+ const glob = readString(args, 'glob');
495
+ const opts: GrepOptions = {
496
+ pattern,
497
+ ignoreCase: args.ignore_case === true,
498
+ fixedStrings: args.fixed_strings === true,
499
+ context,
500
+ maxCount,
501
+ ...(glob !== '' ? { glob } : {}),
502
+ };
503
+ if (opts.glob !== undefined) {
504
+ try {
505
+ globToRegExp(opts.glob);
506
+ } catch (error) {
507
+ return `错误:glob 无效:${String(error)}`;
508
+ }
509
+ }
510
+ if (!opts.fixedStrings) {
511
+ try {
512
+ new RegExp(opts.pattern);
513
+ } catch (error) {
514
+ return `错误:pattern 不是合法正则:${String(error)}(字面搜索传 fixed_strings: true)`;
515
+ }
516
+ }
517
+
518
+ const inputPath = readString(args, 'path');
519
+ const baseCwd = resolveCallCwd(config, ctx.cwd);
520
+ const absolute = resolveToolPath(baseCwd.path, inputPath === '' ? '.' : inputPath);
521
+ if (evaluatePath(absolute, boundary) === 'deny') return PATH_DENIED_TEXT;
522
+ if (inputPath !== '' && dependsOnBaseCwd(inputPath) && baseCwd.issue !== undefined) {
523
+ return baseCwd.issue;
524
+ }
525
+ let stat: ReturnType<typeof statSync>;
526
+ try {
527
+ stat = statSync(absolute);
528
+ } catch {
529
+ return `错误:路径不存在:${inputPath === '' ? '.' : inputPath}`;
530
+ }
531
+ const isDir = stat.isDirectory();
532
+ if (!isDir && !stat.isFile()) return `错误:${inputPath} 不是文件或目录`;
533
+ const rootDir = isDir ? absolute : path.dirname(absolute);
534
+ const target = isDir ? '.' : path.basename(absolute);
535
+
536
+ const rgBinary = findRgBinary();
537
+ const result =
538
+ rgBinary !== null
539
+ ? await runRg(rgBinary, rootDir, target, opts, signal)
540
+ : grepFallback(rootDir, target, opts, signal);
541
+ if (signal?.aborted) return CANCELLED_TEXT;
542
+ return renderGrep(result, absolute, opts);
543
+ }
544
+
545
+ /** 构造 grep 工具(只读;路径边界与 read 同一套)。 */
546
+ export function createGrepTool(boundary: PathBoundary, config: BasicToolsConfig): ToolDefinition {
547
+ return {
548
+ name: 'grep',
549
+ description:
550
+ 'Search file contents with a ripgrep engine (pure-TS fallback when rg is absent) and ' +
551
+ 'return structured matches as file:line:content (context lines as file-line-content). ' +
552
+ 'The pattern is passed as data, never through a shell — no quoting or expansion issues. ' +
553
+ 'Use it for text search across files; use codegraph for symbol-level questions and read ' +
554
+ 'for a known file. Respects .gitignore (rg) / skips node_modules, .git, dist, hidden dirs ' +
555
+ '(fallback). Read-only: sensitive paths are denied like read.',
556
+ inputSchema: {
557
+ type: 'object',
558
+ properties: {
559
+ pattern: {
560
+ type: 'string',
561
+ description:
562
+ 'Regular expression to search for (or literal text with fixed_strings: true)',
563
+ },
564
+ path: {
565
+ type: 'string',
566
+ description:
567
+ 'File or directory to search (default: agent cwd, else member cwd, else process cwd)',
568
+ },
569
+ glob: {
570
+ type: 'string',
571
+ description: 'Only search files matching this glob, e.g. "*.ts" or "src/**/*.{ts,tsx}"',
572
+ },
573
+ context: {
574
+ type: 'number',
575
+ description: 'Lines of context before and after each match (0-50, default 0)',
576
+ },
577
+ max_count: {
578
+ type: 'number',
579
+ description: `Stop after this many matches total (default ${DEFAULT_GREP_MAX_COUNT}; output marks truncation)`,
580
+ },
581
+ ignore_case: { type: 'boolean', description: 'Case-insensitive search (default false)' },
582
+ fixed_strings: {
583
+ type: 'boolean',
584
+ description: 'Treat pattern as literal text, not a regex (default false)',
585
+ },
586
+ },
587
+ required: ['pattern'],
588
+ },
589
+ concurrencySafe: true,
590
+ checkPermission: async (input, ctx) => {
591
+ if (!isRecord(input)) return 'allow';
592
+ const inputPath = readString(input, 'path');
593
+ return evaluatePath(
594
+ resolveToolPath(resolveCallCwd(config, ctx.cwd).path, inputPath === '' ? '.' : inputPath),
595
+ boundary,
596
+ );
597
+ },
598
+ handler: async (args, ctx) =>
599
+ boundToolOutput(ctx, 'grep', await runGrep(args, ctx, activeBoundary(boundary), config)),
600
+ };
601
+ }