grep.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import z from "zod"
  2. import { Tool } from "./tool"
  3. import { Ripgrep } from "../file/ripgrep"
  4. import DESCRIPTION from "./grep.txt"
  5. import { Instance } from "../project/instance"
  6. import path from "path"
  7. import { assertExternalDirectory } from "./external-directory"
  8. const MAX_LINE_LENGTH = 2000
  9. export const GrepTool = Tool.define("grep", {
  10. description: DESCRIPTION,
  11. parameters: z.object({
  12. pattern: z.string().describe("The regex pattern to search for in file contents"),
  13. path: z.string().optional().describe("The directory to search in. Defaults to the current working directory."),
  14. include: z.string().optional().describe('File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")'),
  15. }),
  16. async execute(params, ctx) {
  17. if (!params.pattern) {
  18. throw new Error("pattern is required")
  19. }
  20. await ctx.ask({
  21. permission: "grep",
  22. patterns: [params.pattern],
  23. always: ["*"],
  24. metadata: {
  25. pattern: params.pattern,
  26. path: params.path,
  27. include: params.include,
  28. },
  29. })
  30. let searchPath = params.path ?? Instance.directory
  31. searchPath = path.isAbsolute(searchPath) ? searchPath : path.resolve(Instance.directory, searchPath)
  32. await assertExternalDirectory(ctx, searchPath, { kind: "directory" })
  33. const rgPath = await Ripgrep.filepath()
  34. const args = ["-nH", "--hidden", "--follow", "--field-match-separator=|", "--regexp", params.pattern]
  35. if (params.include) {
  36. args.push("--glob", params.include)
  37. }
  38. args.push(searchPath)
  39. const proc = Bun.spawn([rgPath, ...args], {
  40. stdout: "pipe",
  41. stderr: "pipe",
  42. })
  43. const output = await new Response(proc.stdout).text()
  44. const errorOutput = await new Response(proc.stderr).text()
  45. const exitCode = await proc.exited
  46. if (exitCode === 1) {
  47. return {
  48. title: params.pattern,
  49. metadata: { matches: 0, truncated: false },
  50. output: "No files found",
  51. }
  52. }
  53. if (exitCode !== 0) {
  54. throw new Error(`ripgrep failed: ${errorOutput}`)
  55. }
  56. // Handle both Unix (\n) and Windows (\r\n) line endings
  57. const lines = output.trim().split(/\r?\n/)
  58. const matches = []
  59. for (const line of lines) {
  60. if (!line) continue
  61. const [filePath, lineNumStr, ...lineTextParts] = line.split("|")
  62. if (!filePath || !lineNumStr || lineTextParts.length === 0) continue
  63. const lineNum = parseInt(lineNumStr, 10)
  64. const lineText = lineTextParts.join("|")
  65. const file = Bun.file(filePath)
  66. const stats = await file.stat().catch(() => null)
  67. if (!stats) continue
  68. matches.push({
  69. path: filePath,
  70. modTime: stats.mtime.getTime(),
  71. lineNum,
  72. lineText,
  73. })
  74. }
  75. matches.sort((a, b) => b.modTime - a.modTime)
  76. const limit = 100
  77. const truncated = matches.length > limit
  78. const finalMatches = truncated ? matches.slice(0, limit) : matches
  79. if (finalMatches.length === 0) {
  80. return {
  81. title: params.pattern,
  82. metadata: { matches: 0, truncated: false },
  83. output: "No files found",
  84. }
  85. }
  86. const outputLines = [`Found ${finalMatches.length} matches`]
  87. let currentFile = ""
  88. for (const match of finalMatches) {
  89. if (currentFile !== match.path) {
  90. if (currentFile !== "") {
  91. outputLines.push("")
  92. }
  93. currentFile = match.path
  94. outputLines.push(`${match.path}:`)
  95. }
  96. const truncatedLineText =
  97. match.lineText.length > MAX_LINE_LENGTH ? match.lineText.substring(0, MAX_LINE_LENGTH) + "..." : match.lineText
  98. outputLines.push(` Line ${match.lineNum}: ${truncatedLineText}`)
  99. }
  100. if (truncated) {
  101. outputLines.push("")
  102. outputLines.push("(Results are truncated. Consider using a more specific path or pattern.)")
  103. }
  104. return {
  105. title: params.pattern,
  106. metadata: {
  107. matches: finalMatches.length,
  108. truncated,
  109. },
  110. output: outputLines.join("\n"),
  111. }
  112. },
  113. })