read.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 { Provider } from "../provider/provider"
  11. import { Identifier } from "../id/id"
  12. import { Permission } from "../permission"
  13. import { Agent } from "@/agent/agent"
  14. const DEFAULT_READ_LIMIT = 2000
  15. const MAX_LINE_LENGTH = 2000
  16. export const ReadTool = Tool.define("read", {
  17. description: DESCRIPTION,
  18. parameters: z.object({
  19. filePath: z.string().describe("The path to the file to read"),
  20. offset: z.coerce.number().describe("The line number to start reading from (0-based)").optional(),
  21. limit: z.coerce.number().describe("The number of lines to read (defaults to 2000)").optional(),
  22. }),
  23. async execute(params, ctx) {
  24. let filepath = params.filePath
  25. if (!path.isAbsolute(filepath)) {
  26. filepath = path.join(process.cwd(), filepath)
  27. }
  28. const title = path.relative(Instance.worktree, filepath)
  29. const agent = await Agent.get(ctx.agent)
  30. if (!ctx.extra?.["bypassCwdCheck"] && !Filesystem.contains(Instance.directory, filepath)) {
  31. const parentDir = path.dirname(filepath)
  32. if (agent.permission.external_directory === "ask") {
  33. await Permission.ask({
  34. type: "external_directory",
  35. pattern: parentDir,
  36. sessionID: ctx.sessionID,
  37. messageID: ctx.messageID,
  38. callID: ctx.callID,
  39. title: `Access file outside working directory: ${filepath}`,
  40. metadata: {
  41. filepath,
  42. parentDir,
  43. },
  44. })
  45. }
  46. }
  47. const file = Bun.file(filepath)
  48. if (!(await file.exists())) {
  49. const dir = path.dirname(filepath)
  50. const base = path.basename(filepath)
  51. const dirEntries = fs.readdirSync(dir)
  52. const suggestions = dirEntries
  53. .filter(
  54. (entry) =>
  55. entry.toLowerCase().includes(base.toLowerCase()) || base.toLowerCase().includes(entry.toLowerCase()),
  56. )
  57. .map((entry) => path.join(dir, entry))
  58. .slice(0, 3)
  59. if (suggestions.length > 0) {
  60. throw new Error(`File not found: ${filepath}\n\nDid you mean one of these?\n${suggestions.join("\n")}`)
  61. }
  62. throw new Error(`File not found: ${filepath}`)
  63. }
  64. const isImage = isImageFile(filepath)
  65. const supportsImages = await (async () => {
  66. if (!ctx.extra?.["providerID"] || !ctx.extra?.["modelID"]) return false
  67. const providerID = ctx.extra["providerID"] as string
  68. const modelID = ctx.extra["modelID"] as string
  69. const model = await Provider.getModel(providerID, modelID).catch(() => undefined)
  70. if (!model) return false
  71. return model.info.modalities?.input?.includes("image") ?? false
  72. })()
  73. if (isImage) {
  74. if (!supportsImages) {
  75. throw new Error(`Failed to read image: ${filepath}, model may not be able to read images`)
  76. }
  77. const mime = file.type
  78. const msg = "Image read successfully"
  79. return {
  80. title,
  81. output: msg,
  82. metadata: {
  83. preview: msg,
  84. },
  85. attachments: [
  86. {
  87. id: Identifier.ascending("part"),
  88. sessionID: ctx.sessionID,
  89. messageID: ctx.messageID,
  90. type: "file",
  91. mime,
  92. url: `data:${mime};base64,${Buffer.from(await file.bytes()).toString("base64")}`,
  93. },
  94. ],
  95. }
  96. }
  97. const isBinary = await isBinaryFile(filepath, file)
  98. if (isBinary) throw new Error(`Cannot read binary file: ${filepath}`)
  99. const limit = params.limit ?? DEFAULT_READ_LIMIT
  100. const offset = params.offset || 0
  101. const lines = await file.text().then((text) => text.split("\n"))
  102. const raw = lines.slice(offset, offset + limit).map((line) => {
  103. return line.length > MAX_LINE_LENGTH ? line.substring(0, MAX_LINE_LENGTH) + "..." : line
  104. })
  105. const content = raw.map((line, index) => {
  106. return `${(index + offset + 1).toString().padStart(5, "0")}| ${line}`
  107. })
  108. const preview = raw.slice(0, 20).join("\n")
  109. let output = "<file>\n"
  110. output += content.join("\n")
  111. if (lines.length > offset + content.length) {
  112. output += `\n\n(File has more lines. Use 'offset' parameter to read beyond line ${offset + content.length})`
  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. },
  124. }
  125. },
  126. })
  127. function isImageFile(filePath: string): string | false {
  128. const ext = path.extname(filePath).toLowerCase()
  129. switch (ext) {
  130. case ".jpg":
  131. case ".jpeg":
  132. return "JPEG"
  133. case ".png":
  134. return "PNG"
  135. case ".gif":
  136. return "GIF"
  137. case ".bmp":
  138. return "BMP"
  139. case ".webp":
  140. return "WebP"
  141. default:
  142. return false
  143. }
  144. }
  145. async function isBinaryFile(filepath: string, file: Bun.BunFile): Promise<boolean> {
  146. const ext = path.extname(filepath).toLowerCase()
  147. // binary check for common non-text extensions
  148. switch (ext) {
  149. case ".zip":
  150. case ".tar":
  151. case ".gz":
  152. case ".exe":
  153. case ".dll":
  154. case ".so":
  155. case ".class":
  156. case ".jar":
  157. case ".war":
  158. case ".7z":
  159. case ".doc":
  160. case ".docx":
  161. case ".xls":
  162. case ".xlsx":
  163. case ".ppt":
  164. case ".pptx":
  165. case ".odt":
  166. case ".ods":
  167. case ".odp":
  168. case ".bin":
  169. case ".dat":
  170. case ".obj":
  171. case ".o":
  172. case ".a":
  173. case ".lib":
  174. case ".wasm":
  175. case ".pyc":
  176. case ".pyo":
  177. return true
  178. default:
  179. break
  180. }
  181. const stat = await file.stat()
  182. const fileSize = stat.size
  183. if (fileSize === 0) return false
  184. const bufferSize = Math.min(4096, fileSize)
  185. const buffer = await file.arrayBuffer()
  186. if (buffer.byteLength === 0) return false
  187. const bytes = new Uint8Array(buffer.slice(0, bufferSize))
  188. let nonPrintableCount = 0
  189. for (let i = 0; i < bytes.length; i++) {
  190. if (bytes[i] === 0) return true
  191. if (bytes[i] < 9 || (bytes[i] > 13 && bytes[i] < 32)) {
  192. nonPrintableCount++
  193. }
  194. }
  195. // If >30% non-printable characters, consider it binary
  196. return nonPrintableCount / bytes.length > 0.3
  197. }