read.ts 5.7 KB

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