grep.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. export * as GrepTool from "./grep"
  2. import { ToolFailure } from "@opencode-ai/llm"
  3. import { Effect, Layer, Schema } from "effect"
  4. import path from "path"
  5. import { FileSystem } from "../filesystem"
  6. import { FSUtil } from "../fs-util"
  7. import { Location } from "../location"
  8. import { PermissionV2 } from "../permission"
  9. import { Ripgrep } from "../ripgrep"
  10. import { RelativePath } from "../schema"
  11. import { Tool } from "./tool"
  12. import { Tools } from "./tools"
  13. export const name = "grep"
  14. export const Input = Schema.Struct({
  15. pattern: FileSystem.GrepInput.fields.pattern.annotate({
  16. description: "Regex pattern to search for in file contents",
  17. }),
  18. path: RelativePath.pipe(Schema.optional).annotate({
  19. description: "Relative directory to search. Defaults to the active Location.",
  20. }),
  21. include: FileSystem.GrepInput.fields.include.annotate({
  22. description: 'File glob to include in the search (for example, "*.js" or "*.{ts,tsx}")',
  23. }),
  24. limit: FileSystem.GrepInput.fields.limit.annotate({
  25. description: "Maximum matches to return",
  26. }),
  27. })
  28. export const Output = Schema.Array(FileSystem.Match)
  29. type ModelOutput = typeof Output.Encoded
  30. /** Format raw search matches into the familiar concise model output. */
  31. export const toModelOutput = (output: ModelOutput) => {
  32. const lines = output.length === 0 ? ["No files found"] : [`Found ${output.length} matches`]
  33. let current = ""
  34. for (const match of output) {
  35. if (current !== match.entry.path) {
  36. if (current) lines.push("")
  37. current = match.entry.path
  38. lines.push(`${match.entry.path}:`)
  39. }
  40. lines.push(` Line ${match.line}: ${match.text}`)
  41. }
  42. return lines.join("\n")
  43. }
  44. /** Grep leaf that defaults its filesystem root to the active Location. */
  45. export const layer = Layer.effectDiscard(
  46. Effect.gen(function* () {
  47. const tools = yield* Tools.Service
  48. const fs = yield* FSUtil.Service
  49. const ripgrep = yield* Ripgrep.Service
  50. const location = yield* Location.Service
  51. const permission = yield* PermissionV2.Service
  52. yield* tools
  53. .register({
  54. [name]: Tool.make({
  55. description:
  56. "Search file contents by regular expression within the active Location or an absolute managed tool-output file. Use a path to narrow the search, include to filter files by glob, and limit to bound the match count. Returns concise file resources, line numbers, and bounded line previews.",
  57. input: Input,
  58. output: Output,
  59. toModelOutput: ({ output }) => [
  60. {
  61. type: "text",
  62. text: toModelOutput(
  63. output.map((match) => ({
  64. ...match,
  65. entry: { ...match.entry, path: path.resolve(location.directory, match.entry.path) },
  66. })),
  67. ),
  68. },
  69. ],
  70. execute: (input, context) =>
  71. Effect.gen(function* () {
  72. yield* permission.assert({
  73. action: name,
  74. resources: [input.pattern],
  75. save: ["*"],
  76. metadata: {
  77. root: ".",
  78. path: input.path,
  79. include: input.include,
  80. limit: input.limit,
  81. },
  82. sessionID: context.sessionID,
  83. agent: context.agent,
  84. source: { type: "tool", messageID: context.assistantMessageID, callID: context.toolCallID },
  85. })
  86. const target = path.resolve(location.directory, input.path ?? ".")
  87. const info = yield* fs.stat(target).pipe(Effect.catch(() => Effect.succeed(undefined)))
  88. return yield* ripgrep
  89. .grep({
  90. cwd: info?.type === "Directory" ? target : path.dirname(target),
  91. pattern: input.pattern,
  92. file: info?.type === "File" ? path.basename(target) : undefined,
  93. include: input.include,
  94. limit: input.limit ?? Number.MAX_SAFE_INTEGER,
  95. })
  96. .pipe(
  97. Effect.map((result) =>
  98. result.map(
  99. (match) =>
  100. new FileSystem.Match({
  101. ...match,
  102. entry: new FileSystem.Entry({
  103. ...match.entry,
  104. path: RelativePath.make(
  105. path.relative(
  106. location.directory,
  107. path.resolve(
  108. info?.type === "Directory" ? target : path.dirname(target),
  109. match.entry.path,
  110. ),
  111. ),
  112. ),
  113. }),
  114. }),
  115. ),
  116. ),
  117. )
  118. }).pipe(Effect.mapError(() => new ToolFailure({ message: `Unable to grep for ${input.pattern}` }))),
  119. }),
  120. })
  121. .pipe(Effect.orDie)
  122. }),
  123. )