/** * ============================================================ * src/tools/glob.ts —— Glob 工具(按文件名模式匹配) * ------------------------------------------------------------ * 对应 kakadeai 主仓库的 GlobTool。 * 实现用 fast-glob(npm 包),默认按发现顺序流式返回。 * 支持限制候选数量,并通过结构化元数据返回大小和修改时间。 * ============================================================ */ import { isAbsolute, relative, resolve, sep } from 'node:path'; import fg from 'fast-glob'; import { stat } from 'node:fs/promises'; import { z } from 'zod'; import { getWorkingDir } from '../../bootstrap/workingDir.js'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; // ---------------- 1. Zod 输入 schema ---------------- const inputSchema = z.object({ pattern: z .string() .min(1) .describe('glob 模式,例如 "**/*.ts" 或 "src/components/**/*.tsx"'), path: z .string() .optional() .describe( '搜索的根目录(默认当前工作目录);省略时不要传 "undefined" 字符串', ), strategy: z .enum(['fast', 'complete']) .default('fast') .optional() .describe('fast 在收集够分页候选后提前停止;完整排序请用 complete'), sort_by: z .enum(['discovery', 'modified', 'path']) .default('discovery') .optional() .describe('排序字段,默认 discovery'), order: z .enum(['asc', 'desc']) .optional() .describe('排序方向:discovery 默认 asc;modified/path 默认 desc'), offset: z .number() .int() .min(0) .optional() .describe('跳过前 N 个结果,默认 0'), limit: z .number() .int() .min(0) .max(10_000) .optional() .describe('最多返回多少个候选文件;默认 200,0 表示不限制'), }); type GlobInput = z.infer; // ---------------- 2. JSON Schema(由 Zod 自动派生) ---------------- const parameters = toToolParameters(inputSchema); // ---------------- 3. Description(搬自 kakadeai/tools/GlobTool/prompt.ts 的 DESCRIPTION) ---------------- const description = `- Fast file pattern matching tool that works with any codebase size - Supports glob patterns like "**/*.js" or "src/**/*.ts" - Returns structured file candidates with path, size, and modification time - Defaults to streaming discovery order; request sort_by=modified with strategy=complete for newest-file queries - Discovery does not present files to the user; use Read for selected source files and PresentResult for delivered files - Use this tool when you need to find files by name patterns - When you need to do an open ended search that may require multiple rounds, prefer the Grep tool for content search`; // ---------------- 4. call() ---------------- async function call( input: GlobInput, runCwd = getWorkingDir(), signal?: AbortSignal, ): Promise { // 以 getWorkingDir() 为锚,而非裸 resolve()(同 grep.ts 的坑:后者落回 process.cwd(), // 多工作区宿主进程里会与当前工作区脱节)。resolve 对绝对路径行为不变。 const cwd = input.path ? resolve(runCwd, input.path) : runCwd; // 跨平台:fast-glob 强制要求 pattern 用正斜杠。 // Windows 用户/模型可能传 "src\**\*.ts",这里统一替换。 // (cwd 用原生路径没问题;fast-glob 内部会处理) const pattern = input.pattern.replace(/\\/g, '/'); const offset = input.offset ?? 0, limit = input.limit ?? 200, strategy = input.strategy ?? 'fast', sortBy = input.sort_by ?? 'discovery'; const needed = limit === 0 ? Number.POSITIVE_INFINITY : offset + limit + 1; const ignore = ['node_modules', '.git', '.svn', '.hg', '.jj', '.sl', 'dist'] .filter((name) => !pattern.split('/').includes(name)) .map((name) => `**/${name}/**`); type Candidate = { path: string; mtime: number; size: number; discovery: number; }; const candidates: Candidate[] = []; let scanned = 0; let stoppedEarly = false; const effectiveOrder = input.order ?? (sortBy === 'discovery' ? 'asc' : 'desc'); const compare = (a: Candidate, b: Candidate): number => { const value = sortBy === 'path' ? a.path.localeCompare(b.path) : sortBy === 'modified' ? a.mtime - b.mtime : a.discovery - b.discovery; return value * (effectiveOrder === 'desc' ? -1 : 1); }; // 最大堆的根始终是当前保留集合里“最差”的候选,完整扫描只占 O(offset+limit) 内存。 const bubbleUp = (index: number) => { while (index > 0) { const parent = Math.floor((index - 1) / 2); if (compare(candidates[parent]!, candidates[index]!) >= 0) break; [candidates[parent], candidates[index]] = [ candidates[index]!, candidates[parent]!, ]; index = parent; } }; const bubbleDown = (index: number) => { while (true) { const left = index * 2 + 1, right = left + 1; let worst = index; if ( left < candidates.length && compare(candidates[left]!, candidates[worst]!) > 0 ) worst = left; if ( right < candidates.length && compare(candidates[right]!, candidates[worst]!) > 0 ) worst = right; if (worst === index) break; [candidates[index], candidates[worst]] = [ candidates[worst]!, candidates[index]!, ]; index = worst; } }; const retain = (item: Candidate) => { if (limit === 0) { candidates.push(item); return; } if (candidates.length < needed) { candidates.push(item); bubbleUp(candidates.length - 1); } else if (compare(item, candidates[0]!) < 0) { candidates[0] = item; bubbleDown(0); } }; try { const stream = fg.stream(pattern, { cwd, dot: true, onlyFiles: true, followSymbolicLinks: false, ignore, absolute: false, }); for await (const raw of stream) { if (signal?.aborted) { (stream as unknown as { destroy?: () => void }).destroy?.(); throw new Error('aborted'); } const path = Buffer.isBuffer(raw) ? raw.toString('utf8') : String(raw); scanned++; if (strategy === 'fast' && sortBy === 'discovery' && effectiveOrder === 'asc') { candidates.push({ path, mtime: 0, size: 0, discovery: scanned }); if (candidates.length >= needed) { stoppedEarly = true; (stream as unknown as { destroy?: () => void }).destroy?.(); break; } continue; } const info = sortBy === 'modified' ? await stat(resolve(cwd, path)) : { mtimeMs: 0, size: 0 }; const item = { path, mtime: info.mtimeMs, size: info.size, discovery: scanned, }; retain(item); } } catch (e) { return { ok: false, error: `glob 失败:${(e as Error).message}` }; } if (candidates.length === 0) { return { ok: true, content: `(no files matched pattern "${pattern}" in ${cwd})`, }; } // 候选携带稳定元数据。发现候选本身不代表文件已经成为会话上下文。 const withMtime = candidates; withMtime.sort(compare); const selected = limit === 0 ? withMtime.slice(offset) : withMtime.slice(offset, offset + limit); const truncated = stoppedEarly || offset + selected.length < withMtime.length; for (const item of selected) { if (item.size === 0 && item.mtime === 0) { const info = await stat(resolve(cwd, item.path)).catch(() => undefined); if (info) { item.size = info.size; item.mtime = info.mtimeMs; } } } // 输出:每行一个相对路径 let content = selected.map((m) => m.path).join('\n'); // 超条数截断:保留旧文件(头部),丢弃新文件(尾部) if (content.length > DEFAULT_MAX_RESULT_SIZE_CHARS) { content = content.slice(0, DEFAULT_MAX_RESULT_SIZE_CHARS) + `\n\n... (输出超过 ${DEFAULT_MAX_RESULT_SIZE_CHARS} 字符,已截断)`; } const workspaceRoot = resolve(runCwd); return { ok: true, content: `${content}\n\n(${stoppedEarly ? `至少扫描 ${scanned} 个` : `匹配 ${scanned} 个`},返回 ${selected.length} 个,offset=${offset}${truncated ? ',仍有后续结果' : ''},按 ${sortBy} ${effectiveOrder} 排序)`, metadata: { kind: 'file_discovery', files: selected.flatMap((entry) => { const absolute = resolve(cwd, entry.path); const rel = relative(workspaceRoot, absolute); if ( !rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel) ) return []; return [ { relativePath: rel.split(sep).join('/'), size: entry.size, modifiedAt: entry.mtime, }, ]; }), }, }; } // ---------------- 5. 导出 ---------------- export const globTool: Tool = { name: 'Glob', description, inputSchema, parameters, isReadOnly: true, isConcurrencySafe: true, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, interruptBehavior: () => 'cancel', call: (input, signal) => call(input, undefined, signal), callWithContext: (input, signal, context: ToolCallContext) => call(input, context.cwd, signal), };