read.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import z from "zod"
  2. import * as fs from "fs"
  3. import * as path from "path"
  4. import { Tool } from "./tool"
  5. import { LSP } from "../lsp"
  6. import { FileTime } from "../file/time"
  7. import DESCRIPTION from "./read.txt"
  8. import { Instance } from "../project/instance"
  9. import { Identifier } from "../id/id"
  10. import { assertExternalDirectory } from "./external-directory"
  11. const DEFAULT_READ_LIMIT = 2000
  12. const MAX_LINE_LENGTH = 2000
  13. const MAX_BYTES = 50 * 1024
  14. export const ReadTool = Tool.define("read", {
  15. description: DESCRIPTION,
  16. parameters: z.object({
  17. filePath: z.string().describe("The path to the file to read"),
  18. offset: z.coerce.number().describe("The line number to start reading from (0-based)").optional(),
  19. limit: z.coerce.number().describe("The number of lines to read (defaults to 2000)").optional(),
  20. }),
  21. async execute(params, ctx) {
  22. let filepath = params.filePath
  23. if (!path.isAbsolute(filepath)) {
  24. filepath = path.join(process.cwd(), filepath)
  25. }
  26. const title = path.relative(Instance.worktree, filepath)
  27. await assertExternalDirectory(ctx, filepath, {
  28. bypass: Boolean(ctx.extra?.["bypassCwdCheck"]),
  29. })
  30. await ctx.ask({
  31. permission: "read",
  32. patterns: [filepath],
  33. always: ["*"],
  34. metadata: {},
  35. })
  36. const file = Bun.file(filepath)
  37. if (!(await file.exists())) {
  38. const dir = path.dirname(filepath)
  39. const base = path.basename(filepath)
  40. const dirEntries = fs.readdirSync(dir)
  41. const suggestions = dirEntries
  42. .filter(
  43. (entry) =>
  44. entry.toLowerCase().includes(base.toLowerCase()) || base.toLowerCase().includes(entry.toLowerCase()),
  45. )
  46. .map((entry) => path.join(dir, entry))
  47. .slice(0, 3)
  48. if (suggestions.length > 0) {
  49. throw new Error(`File not found: ${filepath}\n\nDid you mean one of these?\n${suggestions.join("\n")}`)
  50. }
  51. throw new Error(`File not found: ${filepath}`)
  52. }
  53. // Exclude SVG (XML-based) and vnd.fastbidsheet (.fbs extension, commonly FlatBuffers schema files)
  54. const isImage =
  55. file.type.startsWith("image/") && file.type !== "image/svg+xml" && file.type !== "image/vnd.fastbidsheet"
  56. const isPdf = file.type === "application/pdf"
  57. if (isImage || isPdf) {
  58. const mime = file.type
  59. const msg = `${isImage ? "Image" : "PDF"} read successfully`
  60. return {
  61. title,
  62. output: msg,
  63. metadata: {
  64. preview: msg,
  65. truncated: false,
  66. },
  67. attachments: [
  68. {
  69. id: Identifier.ascending("part"),
  70. sessionID: ctx.sessionID,
  71. messageID: ctx.messageID,
  72. type: "file",
  73. mime,
  74. url: `data:${mime};base64,${Buffer.from(await file.bytes()).toString("base64")}`,
  75. },
  76. ],
  77. }
  78. }
  79. const isBinary = await isBinaryFile(filepath, file)
  80. if (isBinary) throw new Error(`Cannot read binary file: ${filepath}`)
  81. const limit = params.limit ?? DEFAULT_READ_LIMIT
  82. const offset = params.offset || 0
  83. const lines = await file.text().then((text) => text.split("\n"))
  84. const raw: string[] = []
  85. let bytes = 0
  86. let truncatedByBytes = false
  87. for (let i = offset; i < Math.min(lines.length, offset + limit); i++) {
  88. const line = lines[i].length > MAX_LINE_LENGTH ? lines[i].substring(0, MAX_LINE_LENGTH) + "..." : lines[i]
  89. const size = Buffer.byteLength(line, "utf-8") + (raw.length > 0 ? 1 : 0)
  90. if (bytes + size > MAX_BYTES) {
  91. truncatedByBytes = true
  92. break
  93. }
  94. raw.push(line)
  95. bytes += size
  96. }
  97. const content = raw.map((line, index) => {
  98. return `${(index + offset + 1).toString().padStart(5, "0")}| ${line}`
  99. })
  100. const preview = raw.slice(0, 20).join("\n")
  101. let output = "<file>\n"
  102. output += content.join("\n")
  103. const totalLines = lines.length
  104. const lastReadLine = offset + raw.length
  105. const hasMoreLines = totalLines > lastReadLine
  106. const truncated = hasMoreLines || truncatedByBytes
  107. if (truncatedByBytes) {
  108. output += `\n\n(Output truncated at ${MAX_BYTES} bytes. Use 'offset' parameter to read beyond line ${lastReadLine})`
  109. } else if (hasMoreLines) {
  110. output += `\n\n(File has more lines. Use 'offset' parameter to read beyond line ${lastReadLine})`
  111. } else {
  112. output += `\n\n(End of file - total ${totalLines} lines)`
  113. }
  114. output += "\n</file>"
  115. // just warms the lsp client
  116. LSP.touchFile(filepath, false)
  117. FileTime.read(ctx.sessionID, filepath)
  118. return {
  119. title,
  120. output,
  121. metadata: {
  122. preview,
  123. truncated,
  124. },
  125. }
  126. },
  127. })
  128. async function isBinaryFile(filepath: string, file: Bun.BunFile): Promise<boolean> {
  129. const ext = path.extname(filepath).toLowerCase()
  130. // binary check for common non-text extensions
  131. switch (ext) {
  132. case ".zip":
  133. case ".tar":
  134. case ".gz":
  135. case ".exe":
  136. case ".dll":
  137. case ".so":
  138. case ".class":
  139. case ".jar":
  140. case ".war":
  141. case ".7z":
  142. case ".doc":
  143. case ".docx":
  144. case ".xls":
  145. case ".xlsx":
  146. case ".ppt":
  147. case ".pptx":
  148. case ".odt":
  149. case ".ods":
  150. case ".odp":
  151. case ".bin":
  152. case ".dat":
  153. case ".obj":
  154. case ".o":
  155. case ".a":
  156. case ".lib":
  157. case ".wasm":
  158. case ".pyc":
  159. case ".pyo":
  160. return true
  161. default:
  162. break
  163. }
  164. const stat = await file.stat()
  165. const fileSize = stat.size
  166. if (fileSize === 0) return false
  167. const bufferSize = Math.min(4096, fileSize)
  168. const buffer = await file.arrayBuffer()
  169. if (buffer.byteLength === 0) return false
  170. const bytes = new Uint8Array(buffer.slice(0, bufferSize))
  171. let nonPrintableCount = 0
  172. for (let i = 0; i < bytes.length; i++) {
  173. if (bytes[i] === 0) return true
  174. if (bytes[i] < 9 || (bytes[i] > 13 && bytes[i] < 32)) {
  175. nonPrintableCount++
  176. }
  177. }
  178. // If >30% non-printable characters, consider it binary
  179. return nonPrintableCount / bytes.length > 0.3
  180. }