UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

199 lines • 11 kB
import path from "path"; import { Type } from "typebox"; import { canonicalizeFilesystemPath } from "./filesystem-policy.js"; import { defaultToolMachine } from "./machine.js"; import { modelOnlyText } from "./model-only-text.js"; import { pathExists, resolveToCwd } from "./path-utils.js"; import { findRenderers } from "./renderers/find.js"; import { wrapToolDefinition } from "./tool-definition-wrapper.js"; import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js"; /** Relativize a find result against the search root and normalize it to posix separators. */ export function relativizeFindResultPath(resultPath, searchPath, pathModule = path) { const hadTrailingSeparator = resultPath.endsWith(pathModule.sep) || (pathModule.sep === "\\" && resultPath.endsWith("/")); const relativePath = pathModule.isAbsolute(resultPath) ? pathModule.relative(searchPath, resultPath) : resultPath; const posixPath = relativePath.split(pathModule.sep).join("/"); return hadTrailingSeparator && !posixPath.endsWith("/") ? `${posixPath}/` : posixPath; } const findSchema = Type.Object({ pattern: Type.String({ description: "Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'", }), path: Type.Optional(Type.String({ description: "Directory to search in (default: current directory)" })), limit: Type.Optional(Type.Number({ description: "Maximum number of results (default: 1000)" })), }); export const findToolSystemPromptContribution = { snippet: "Find files by glob pattern (respects .gitignore)", guidelines: [], }; const DEFAULT_LIMIT = 1000; const defaultFindOperations = { exists: pathExists, // This is a placeholder. Actual fd execution happens in execute() when no custom glob is provided. glob: () => [], }; export function createFindToolDefinition(cwd, options) { const customOps = options?.operations; const machine = options?.machine ?? defaultToolMachine(); const filesystemPolicy = options?.filesystemPolicy; return { ...(options?.operations !== undefined || filesystemPolicy !== undefined ? { serverPinned: true } : {}), name: "find", workspaceEffect: "read", label: "find", description: `Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} results or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`, promptSnippet: findToolSystemPromptContribution.snippet, parameters: findSchema, async execute(_toolCallId, { pattern, path: searchDir, limit }, signal, _onUpdate, ctx) { return new Promise((resolve, reject) => { if (signal?.aborted) { reject(new Error("Operation aborted")); return; } let settled = false; const settle = (fn) => { if (settled) return; settled = true; signal?.removeEventListener("abort", onAbort); fn(); }; // files.glob stops its fd child on the same signal. const onAbort = () => { settle(() => reject(new Error("Operation aborted"))); }; signal?.addEventListener("abort", onAbort, { once: true }); (async () => { try { const admitted = machine.begin("files.glob", { pattern, path: searchDir, limit }, signal); if (admitted !== undefined) await admitted; const searchPath = resolveToCwd(searchDir || ".", ctx?.cwd || cwd); const effectiveLimit = limit ?? DEFAULT_LIMIT; const ops = customOps ?? defaultFindOperations; if (filesystemPolicy) { const decision = await filesystemPolicy({ operation: "enumerate", canonicalPath: await canonicalizeFilesystemPath(searchPath), toolName: "find", }); if (!decision.allow) throw new Error(decision.reason); if (signal?.aborted) { settle(() => reject(new Error("Operation aborted"))); return; } } // If custom operations provide glob(), use that instead of fd. if (customOps?.glob) { if (!(await ops.exists(searchPath))) { settle(() => reject(new Error(`Path not found: ${searchPath}`))); return; } if (signal?.aborted) { settle(() => reject(new Error("Operation aborted"))); return; } const results = await ops.glob(pattern, searchPath, { ignore: ["**/node_modules/**", "**/.git/**"], limit: effectiveLimit, }); if (signal?.aborted) { settle(() => reject(new Error("Operation aborted"))); return; } if (results.length === 0) { settle(() => resolve({ content: [{ type: "text", text: "No files found matching pattern" }], details: undefined, })); return; } // Relativize paths against the search root for stable output. const relativized = results.map((p) => relativizeFindResultPath(p, searchPath)); const resultLimitReached = relativized.length >= effectiveLimit; const rawOutput = relativized.join("\n"); const truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER }); const details = {}; const notices = []; if (resultLimitReached) { notices.push(`${effectiveLimit} results limit reached`); details.resultLimitReached = effectiveLimit; } if (truncation.truncated) { notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`); details.truncation = truncation; } const content = [{ type: "text", text: truncation.content }]; if (notices.length > 0) { content[0].text += "\n"; content.push(modelOnlyText(`[${notices.join(". ")}]`)); } settle(() => resolve({ content, details: Object.keys(details).length > 0 ? details : undefined, })); return; } // Default implementation: the shared operation layer's fd search (files.glob). const { entries } = await machine.ops.files.glob({ pattern, cwd: searchPath, limit: effectiveLimit }, machine.context(signal)); if (signal?.aborted) { settle(() => reject(new Error("Operation aborted"))); return; } const lines = entries.map((entry) => entry.path); const output = lines.join("\n"); if (!output) { settle(() => resolve({ content: [{ type: "text", text: "No files found matching pattern" }], details: undefined, })); return; } const relativized = []; for (const rawLine of lines) { const line = rawLine.replace(/\r$/, "").trim(); if (!line) continue; relativized.push(relativizeFindResultPath(line, searchPath)); } const resultLimitReached = relativized.length >= effectiveLimit; const rawOutput = relativized.join("\n"); const truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER }); const details = {}; const notices = []; if (resultLimitReached) { notices.push(`${effectiveLimit} results limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`); details.resultLimitReached = effectiveLimit; } if (truncation.truncated) { notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`); details.truncation = truncation; } const content = [{ type: "text", text: truncation.content }]; if (notices.length > 0) { content[0].text += "\n"; content.push(modelOnlyText(`[${notices.join(". ")}]`)); } settle(() => resolve({ content, details: Object.keys(details).length > 0 ? details : undefined, })); } catch (e) { if (signal?.aborted) { settle(() => reject(new Error("Operation aborted"))); return; } const error = e instanceof Error ? e : new Error(String(e)); settle(() => reject(error)); } })(); }); }, ...findRenderers, }; } export function createFindTool(cwd, options) { return wrapToolDefinition(createFindToolDefinition(cwd, options)); } //# sourceMappingURL=find.js.map