import { lstatSync, readdirSync, statSync } from 'fs'; import { join, resolve } from 'path'; import { z } from 'zod'; import type { ToolDefinition, ToolContext, ToolResult } from '../../agent/types.js'; import { stringParam, workspacePathPreflight } from './confine.js'; // Directorios que siempre se excluyen (mismo set que list.ts y grep.ts) const EXCLUDED_DIRS = new Set([ 'node_modules', '.git', 'dist', '__pycache__', '.venv', 'venv', 'target', '.next', 'build', 'coverage', '.turbo', ]); const MAX_RESULTS = 200; /** * Convierte un patrón glob minimal a RegExp. * Soporta: ** (cualquier secuencia de segmentos), * (cualquier secuencia en un segmento), ? (un char). */ function globToRegExp(pattern: string): RegExp { let regStr = ''; let i = 0; // Normalizar separadores de ruta const p = pattern.replace(/\\/g, '/'); while (i < p.length) { const ch = p[i]!; if (ch === '*' && p[i + 1] === '*') { // "**/" → match cero o más segmentos de directorio if (p[i + 2] === '/') { regStr += '(?:.+/)?'; i += 3; } else { // "**" al final o sin / → match cualquier cosa regStr += '.*'; i += 2; } } else if (ch === '*') { regStr += '[^/]*'; i++; } else if (ch === '?') { regStr += '[^/]'; i++; } else if ('.+^${}()|[]\\'.includes(ch)) { regStr += '\\' + ch; i++; } else { regStr += ch; i++; } } return new RegExp('^' + regStr + '$'); } /** `followLinks: false` (workspace de Desktop, D2): no recorre symlinks ni junctions. */ function walkGlob( dir: string, relDir: string, re: RegExp, results: string[], followLinks = true, ): void { if (results.length >= MAX_RESULTS) return; let entries: string[]; try { entries = readdirSync(dir); } catch { return; } for (const entry of entries) { if (EXCLUDED_DIRS.has(entry)) continue; const relPath = relDir ? `${relDir}/${entry}` : entry; const fullPath = join(dir, entry); let isDir = false; try { const stat = followLinks ? statSync(fullPath) : lstatSync(fullPath); if (stat.isSymbolicLink()) continue; isDir = stat.isDirectory(); } catch { continue; } if (isDir) { walkGlob(fullPath, relPath, re, results, followLinks); } else { if (re.test(relPath)) { results.push(relPath); if (results.length >= MAX_RESULTS) return; } } } } const schema = z.object({ pattern: z.string().describe('Glob pattern (supports **, *, ?). Examples: **/*.ts, src/*.json'), cwd: z.string().optional().describe('Base directory to search from (default: process.cwd())'), }); export const globTool: ToolDefinition = { name: 'glob', description: '- Fast file pattern matching tool that works with any codebase size\n' + '- Supports glob patterns like "**/*.js" or "src/**/*.ts" (also * and ?)\n' + '- Returns up to 200 matching relative paths. Excludes node_modules, .git, dist, etc.\n' + '- Use this tool when you need to find files by name patterns\n' + '- You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.', schema, destructive: false, preflight(params: unknown, ctx: ToolContext): ToolResult | null { return workspacePathPreflight(stringParam(params, 'cwd'), ctx, 'read'); }, async execute(params: unknown, ctx: ToolContext): Promise { const { pattern, cwd } = schema.parse(params); const vetoed = workspacePathPreflight(cwd, ctx, 'read'); if (vetoed) return vetoed; const base = resolve(ctx.cwd, cwd ?? '.'); try { const re = globToRegExp(pattern); const results: string[] = []; walkGlob(base, '', re, results, !ctx.workspace); if (results.length === 0) { return { ok: true, output: '(no matches)' }; } const overflow = results.length >= MAX_RESULTS ? `\n… (limitado a ${MAX_RESULTS} resultados)` : ''; return { ok: true, output: results.join('\n') + overflow }; } catch (err) { return { ok: false, error: `glob failed: ${(err as Error).message}`, recoverable: true, }; } }, };