readFileTool.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import path from "path"
  2. import { isBinaryFile } from "isbinaryfile"
  3. import { Task } from "../task/Task"
  4. import { ClineSayTool } from "../../shared/ExtensionMessage"
  5. import { formatResponse } from "../prompts/responses"
  6. import { t } from "../../i18n"
  7. import { ToolUse, AskApproval, HandleError, PushToolResult, RemoveClosingTag } from "../../shared/tools"
  8. import { RecordSource } from "../context-tracking/FileContextTrackerTypes"
  9. import { isPathOutsideWorkspace } from "../../utils/pathUtils"
  10. import { getReadablePath } from "../../utils/path"
  11. import { countFileLines } from "../../integrations/misc/line-counter"
  12. import { readLines } from "../../integrations/misc/read-lines"
  13. import { extractTextFromFile, addLineNumbers } from "../../integrations/misc/extract-text"
  14. import { parseSourceCodeDefinitionsForFile } from "../../services/tree-sitter"
  15. export async function readFileTool(
  16. cline: Task,
  17. block: ToolUse,
  18. askApproval: AskApproval,
  19. handleError: HandleError,
  20. pushToolResult: PushToolResult,
  21. removeClosingTag: RemoveClosingTag,
  22. ) {
  23. const relPath: string | undefined = block.params.path
  24. const startLineStr: string | undefined = block.params.start_line
  25. const endLineStr: string | undefined = block.params.end_line
  26. // Get the full path and determine if it's outside the workspace
  27. const fullPath = relPath ? path.resolve(cline.cwd, removeClosingTag("path", relPath)) : ""
  28. const isOutsideWorkspace = isPathOutsideWorkspace(fullPath)
  29. const sharedMessageProps: ClineSayTool = {
  30. tool: "readFile",
  31. path: getReadablePath(cline.cwd, removeClosingTag("path", relPath)),
  32. isOutsideWorkspace,
  33. }
  34. try {
  35. if (block.partial) {
  36. const partialMessage = JSON.stringify({ ...sharedMessageProps, content: undefined } satisfies ClineSayTool)
  37. await cline.ask("tool", partialMessage, block.partial).catch(() => {})
  38. return
  39. } else {
  40. if (!relPath) {
  41. cline.consecutiveMistakeCount++
  42. cline.recordToolError("read_file")
  43. const errorMsg = await cline.sayAndCreateMissingParamError("read_file", "path")
  44. pushToolResult(`<file><path></path><error>${errorMsg}</error></file>`)
  45. return
  46. }
  47. const { maxReadFileLine = 500 } = (await cline.providerRef.deref()?.getState()) ?? {}
  48. const isFullRead = maxReadFileLine === -1
  49. // Check if we're doing a line range read
  50. let isRangeRead = false
  51. let startLine: number | undefined = undefined
  52. let endLine: number | undefined = undefined
  53. // Check if we have either range parameter and we're not doing a full read
  54. if (!isFullRead && (startLineStr || endLineStr)) {
  55. isRangeRead = true
  56. }
  57. // Parse start_line if provided
  58. if (startLineStr) {
  59. startLine = parseInt(startLineStr)
  60. if (isNaN(startLine)) {
  61. // Invalid start_line
  62. cline.consecutiveMistakeCount++
  63. cline.recordToolError("read_file")
  64. await cline.say("error", `Failed to parse start_line: ${startLineStr}`)
  65. pushToolResult(`<file><path>${relPath}</path><error>Invalid start_line value</error></file>`)
  66. return
  67. }
  68. startLine -= 1 // Convert to 0-based index
  69. }
  70. // Parse end_line if provided
  71. if (endLineStr) {
  72. endLine = parseInt(endLineStr)
  73. if (isNaN(endLine)) {
  74. // Invalid end_line
  75. cline.consecutiveMistakeCount++
  76. cline.recordToolError("read_file")
  77. await cline.say("error", `Failed to parse end_line: ${endLineStr}`)
  78. pushToolResult(`<file><path>${relPath}</path><error>Invalid end_line value</error></file>`)
  79. return
  80. }
  81. // Convert to 0-based index
  82. endLine -= 1
  83. }
  84. const accessAllowed = cline.rooIgnoreController?.validateAccess(relPath)
  85. if (!accessAllowed) {
  86. await cline.say("rooignore_error", relPath)
  87. const errorMsg = formatResponse.rooIgnoreError(relPath)
  88. pushToolResult(`<file><path>${relPath}</path><error>${errorMsg}</error></file>`)
  89. return
  90. }
  91. // Create line snippet description for approval message
  92. let lineSnippet = ""
  93. if (isFullRead) {
  94. // No snippet for full read
  95. } else if (startLine !== undefined && endLine !== undefined) {
  96. lineSnippet = t("tools:readFile.linesRange", { start: startLine + 1, end: endLine + 1 })
  97. } else if (startLine !== undefined) {
  98. lineSnippet = t("tools:readFile.linesFromToEnd", { start: startLine + 1 })
  99. } else if (endLine !== undefined) {
  100. lineSnippet = t("tools:readFile.linesFromStartTo", { end: endLine + 1 })
  101. } else if (maxReadFileLine === 0) {
  102. lineSnippet = t("tools:readFile.definitionsOnly")
  103. } else if (maxReadFileLine > 0) {
  104. lineSnippet = t("tools:readFile.maxLines", { max: maxReadFileLine })
  105. }
  106. cline.consecutiveMistakeCount = 0
  107. const absolutePath = path.resolve(cline.cwd, relPath)
  108. const completeMessage = JSON.stringify({
  109. ...sharedMessageProps,
  110. content: absolutePath,
  111. reason: lineSnippet,
  112. } satisfies ClineSayTool)
  113. const didApprove = await askApproval("tool", completeMessage)
  114. if (!didApprove) {
  115. return
  116. }
  117. // Count total lines in the file
  118. let totalLines = 0
  119. try {
  120. totalLines = await countFileLines(absolutePath)
  121. } catch (error) {
  122. console.error(`Error counting lines in file ${absolutePath}:`, error)
  123. }
  124. // now execute the tool like normal
  125. let content: string
  126. let isFileTruncated = false
  127. let sourceCodeDef = ""
  128. const isBinary = await isBinaryFile(absolutePath).catch(() => false)
  129. if (isRangeRead) {
  130. if (startLine === undefined) {
  131. content = addLineNumbers(await readLines(absolutePath, endLine, startLine))
  132. } else {
  133. content = addLineNumbers(await readLines(absolutePath, endLine, startLine), startLine + 1)
  134. }
  135. } else if (!isBinary && maxReadFileLine >= 0 && totalLines > maxReadFileLine) {
  136. // If file is too large, only read the first maxReadFileLine lines
  137. isFileTruncated = true
  138. const res = await Promise.all([
  139. maxReadFileLine > 0 ? readLines(absolutePath, maxReadFileLine - 1, 0) : "",
  140. (async () => {
  141. try {
  142. return await parseSourceCodeDefinitionsForFile(absolutePath, cline.rooIgnoreController)
  143. } catch (error) {
  144. if (error instanceof Error && error.message.startsWith("Unsupported language:")) {
  145. console.warn(`[read_file] Warning: ${error.message}`)
  146. return undefined
  147. } else {
  148. console.error(
  149. `[read_file] Unhandled error: ${error instanceof Error ? error.message : String(error)}`,
  150. )
  151. return undefined
  152. }
  153. }
  154. })(),
  155. ])
  156. content = res[0].length > 0 ? addLineNumbers(res[0]) : ""
  157. const result = res[1]
  158. if (result) {
  159. sourceCodeDef = `${result}`
  160. }
  161. } else {
  162. // Read entire file
  163. content = await extractTextFromFile(absolutePath)
  164. }
  165. // Create variables to store XML components
  166. let xmlInfo = ""
  167. let contentTag = ""
  168. // Add truncation notice if applicable
  169. if (isFileTruncated) {
  170. xmlInfo += `<notice>Showing only ${maxReadFileLine} of ${totalLines} total lines. Use start_line and end_line if you need to read more</notice>\n`
  171. // Add source code definitions if available
  172. if (sourceCodeDef) {
  173. xmlInfo += `<list_code_definition_names>${sourceCodeDef}</list_code_definition_names>\n`
  174. }
  175. }
  176. // Empty files (zero lines)
  177. if (content === "" && totalLines === 0) {
  178. // Always add self-closing content tag and notice for empty files
  179. contentTag = `<content/>`
  180. xmlInfo += `<notice>File is empty</notice>\n`
  181. }
  182. // Range reads should always show content regardless of maxReadFileLine
  183. else if (isRangeRead) {
  184. // Create content tag with line range information
  185. let lineRangeAttr = ""
  186. const displayStartLine = startLine !== undefined ? startLine + 1 : 1
  187. const displayEndLine = endLine !== undefined ? endLine + 1 : totalLines
  188. lineRangeAttr = ` lines="${displayStartLine}-${displayEndLine}"`
  189. // Maintain exact format expected by tests
  190. contentTag = `<content${lineRangeAttr}>\n${content}</content>\n`
  191. }
  192. // maxReadFileLine=0 for non-range reads
  193. else if (maxReadFileLine === 0) {
  194. // Skip content tag for maxReadFileLine=0 (definitions only mode)
  195. contentTag = ""
  196. }
  197. // Normal case: non-empty files with content (non-range reads)
  198. else {
  199. // For non-range reads, always show line range
  200. let lines = totalLines
  201. if (maxReadFileLine >= 0 && totalLines > maxReadFileLine) {
  202. lines = maxReadFileLine
  203. }
  204. const lineRangeAttr = ` lines="1-${lines}"`
  205. // Maintain exact format expected by tests
  206. contentTag = `<content${lineRangeAttr}>\n${content}</content>\n`
  207. }
  208. // Track file read operation
  209. if (relPath) {
  210. await cline.getFileContextTracker().trackFileContext(relPath, "read_tool" as RecordSource)
  211. }
  212. // Format the result into the required XML structure
  213. const xmlResult = `<file><path>${relPath}</path>\n${contentTag}${xmlInfo}</file>`
  214. pushToolResult(xmlResult)
  215. }
  216. } catch (error) {
  217. const errorMsg = error instanceof Error ? error.message : String(error)
  218. pushToolResult(`<file><path>${relPath || ""}</path><error>Error reading file: ${errorMsg}</error></file>`)
  219. await handleError("reading file", error)
  220. }
  221. }