read.ts 5.9 KB

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