read-filesystem.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. export * as ReadToolFileSystem from "./read-filesystem"
  2. import path from "path"
  3. import { pathToFileURL } from "url"
  4. import { Context, Effect, Layer, Option, Schema } from "effect"
  5. import { FileSystem } from "../filesystem"
  6. import { FSUtil } from "../fs-util"
  7. import { makeLocationNode } from "../effect/app-node"
  8. import { AbsolutePath, PositiveInt, RelativePath } from "../schema"
  9. export const MAX_READ_LINES = 2_000
  10. export const MAX_READ_BYTES = 50 * 1024
  11. export const MAX_MEDIA_INGEST_BYTES = 20 * 1024 * 1024
  12. const MAX_LINE_LENGTH = 2_000
  13. const MAX_LINE_SUFFIX = `... (line truncated to ${MAX_LINE_LENGTH} chars)`
  14. export class BinaryFileError extends Schema.TaggedErrorClass<BinaryFileError>()("ReadTool.BinaryFileError", {
  15. resource: Schema.String,
  16. }) {
  17. override get message() {
  18. return `Cannot read binary file: ${this.resource}`
  19. }
  20. }
  21. export class MediaIngestLimitError extends Schema.TaggedErrorClass<MediaIngestLimitError>()(
  22. "ReadTool.MediaIngestLimitError",
  23. {
  24. resource: Schema.String,
  25. maximumBytes: Schema.Number,
  26. },
  27. ) {
  28. override get message() {
  29. return `Media exceeds ${this.maximumBytes} byte ingestion limit: ${this.resource}`
  30. }
  31. }
  32. export class MalformedUtf8Error extends Schema.TaggedErrorClass<MalformedUtf8Error>()("ReadTool.MalformedUtf8Error", {
  33. resource: Schema.String,
  34. }) {
  35. override get message() {
  36. return `File is not valid UTF-8: ${this.resource}`
  37. }
  38. }
  39. export class OffsetOutOfRangeError extends Schema.TaggedErrorClass<OffsetOutOfRangeError>()(
  40. "ReadTool.OffsetOutOfRangeError",
  41. { offset: Schema.Number },
  42. ) {
  43. override get message() {
  44. return `Offset ${this.offset} is out of range`
  45. }
  46. }
  47. export class PathKindError extends Schema.TaggedErrorClass<PathKindError>()("ReadTool.PathKindError", {
  48. resource: Schema.String,
  49. expected: Schema.Literals(["a file", "a file or directory"]),
  50. }) {
  51. override get message() {
  52. return `Path is not ${this.expected}: ${this.resource}`
  53. }
  54. }
  55. export type InspectError = FSUtil.Error | PathKindError
  56. export type ReadError =
  57. | FSUtil.Error
  58. | BinaryFileError
  59. | MediaIngestLimitError
  60. | MalformedUtf8Error
  61. | OffsetOutOfRangeError
  62. | PathKindError
  63. export const PageInput = Schema.Struct({
  64. offset: PositiveInt.pipe(Schema.optional),
  65. limit: PositiveInt.check(Schema.isLessThanOrEqualTo(MAX_READ_LINES)).pipe(Schema.optional),
  66. })
  67. export type PageInput = typeof PageInput.Type
  68. export class TextPage extends Schema.Class<TextPage>("ReadTool.TextPage")({
  69. type: Schema.Literal("text-page"),
  70. content: Schema.String,
  71. mime: Schema.String,
  72. offset: PositiveInt,
  73. truncated: Schema.Boolean,
  74. next: PositiveInt.pipe(Schema.optional),
  75. }) {}
  76. export class ListPage extends Schema.Class<ListPage>("ReadTool.ListPage")({
  77. entries: Schema.Array(FileSystem.Entry),
  78. truncated: Schema.Boolean,
  79. next: PositiveInt.pipe(Schema.optional),
  80. }) {}
  81. export interface Interface {
  82. readonly inspect: (path: AbsolutePath) => Effect.Effect<"file" | "directory", InspectError>
  83. readonly read: (
  84. path: AbsolutePath,
  85. resource: string,
  86. page?: PageInput,
  87. ) => Effect.Effect<FileSystem.Content | TextPage, ReadError>
  88. readonly list: (path: AbsolutePath, page?: PageInput) => Effect.Effect<ListPage, FSUtil.Error>
  89. }
  90. export class Service extends Context.Service<Service, Interface>()("@opencode/ReadToolFileSystem") {}
  91. const extensions = new Set([
  92. ".zip",
  93. ".tar",
  94. ".gz",
  95. ".exe",
  96. ".dll",
  97. ".so",
  98. ".class",
  99. ".jar",
  100. ".war",
  101. ".7z",
  102. ".doc",
  103. ".docx",
  104. ".xls",
  105. ".xlsx",
  106. ".ppt",
  107. ".pptx",
  108. ".odt",
  109. ".ods",
  110. ".odp",
  111. ".bin",
  112. ".dat",
  113. ".obj",
  114. ".o",
  115. ".a",
  116. ".lib",
  117. ".wasm",
  118. ".pyc",
  119. ".pyo",
  120. ])
  121. const startsWith = (bytes: Uint8Array, prefix: number[]) => prefix.every((value, index) => bytes[index] === value)
  122. const imageMime = (bytes: Uint8Array) => {
  123. if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "image/png"
  124. if (startsWith(bytes, [0xff, 0xd8, 0xff])) return "image/jpeg"
  125. if (startsWith(bytes, [0x47, 0x49, 0x46, 0x38])) return "image/gif"
  126. if (startsWith(bytes, [0x52, 0x49, 0x46, 0x46]) && startsWith(bytes.subarray(8), [0x57, 0x45, 0x42, 0x50]))
  127. return "image/webp"
  128. }
  129. const binary = (resource: string, bytes: Uint8Array) => {
  130. if (extensions.has(path.extname(resource).toLowerCase())) return true
  131. if (bytes.length === 0) return false
  132. let nonPrintable = 0
  133. for (const byte of bytes) {
  134. if (byte === 0) return true
  135. if (byte < 9 || (byte > 13 && byte < 32)) nonPrintable++
  136. }
  137. return nonPrintable / bytes.length > 0.3
  138. }
  139. const decodeUtf8 = (resource: string, decoder: TextDecoder, bytes?: Uint8Array) =>
  140. Effect.try({
  141. try: () => decoder.decode(bytes, { stream: bytes !== undefined }),
  142. catch: (error) => {
  143. if (error instanceof TypeError) return new MalformedUtf8Error({ resource })
  144. throw error
  145. },
  146. })
  147. const decodeChunk = (resource: string, decoder: TextDecoder, bytes: Uint8Array) =>
  148. bytes.includes(0) ? Effect.fail(new BinaryFileError({ resource })) : decodeUtf8(resource, decoder, bytes)
  149. export const inspect = Effect.fn("ReadTool.inspect")(function* (fs: FSUtil.Interface, input: string) {
  150. const info = yield* fs.stat(input)
  151. const type = info.type === "File" ? "file" : info.type === "Directory" ? "directory" : undefined
  152. if (!type) return yield* Effect.fail(new PathKindError({ resource: input, expected: "a file or directory" }))
  153. return type
  154. })
  155. export const read = Effect.fn("ReadTool.read")(function* (
  156. fs: FSUtil.Interface,
  157. input: string,
  158. resource: string,
  159. page: PageInput = {},
  160. ) {
  161. const real = yield* fs.realPath(input)
  162. return yield* Effect.scoped(
  163. Effect.gen(function* () {
  164. const file = yield* fs.open(real, { flag: "r" })
  165. const info = yield* file.stat
  166. if (info.type !== "File") return yield* Effect.fail(new PathKindError({ resource, expected: "a file" }))
  167. const first = Option.getOrElse(
  168. yield* file.readAlloc(Math.min(64 * 1024, Number(info.size) || 4 * 1024)),
  169. () => new Uint8Array(),
  170. )
  171. const mime = imageMime(first)
  172. if (mime) {
  173. if (info.size > MAX_MEDIA_INGEST_BYTES)
  174. return yield* Effect.fail(new MediaIngestLimitError({ resource, maximumBytes: MAX_MEDIA_INGEST_BYTES }))
  175. const chunks = [first]
  176. let total = first.length
  177. while (total <= MAX_MEDIA_INGEST_BYTES) {
  178. const chunk = yield* file.readAlloc(Math.min(64 * 1024, MAX_MEDIA_INGEST_BYTES + 1 - total))
  179. if (Option.isNone(chunk)) break
  180. chunks.push(chunk.value)
  181. total += chunk.value.length
  182. }
  183. if (total > MAX_MEDIA_INGEST_BYTES)
  184. return yield* Effect.fail(new MediaIngestLimitError({ resource, maximumBytes: MAX_MEDIA_INGEST_BYTES }))
  185. return {
  186. uri: pathToFileURL(real).href,
  187. name: path.basename(real),
  188. content: Buffer.concat(
  189. chunks.map((chunk) => Buffer.from(chunk)),
  190. total,
  191. ).toString("base64"),
  192. encoding: "base64" as const,
  193. mime,
  194. }
  195. }
  196. if (startsWith(first, [0x25, 0x50, 0x44, 0x46]) || extensions.has(path.extname(resource).toLowerCase()))
  197. return yield* Effect.fail(new BinaryFileError({ resource }))
  198. const paged = info.size > MAX_READ_BYTES || page.offset !== undefined || page.limit !== undefined
  199. if (!paged) {
  200. if (binary(resource, first)) return yield* Effect.fail(new BinaryFileError({ resource }))
  201. const decoder = new TextDecoder("utf-8", { fatal: true })
  202. const text = [yield* decodeUtf8(resource, decoder, first)]
  203. while (true) {
  204. const chunk = yield* file.readAlloc(64 * 1024)
  205. if (Option.isNone(chunk)) break
  206. text.push(yield* decodeChunk(resource, decoder, chunk.value))
  207. }
  208. text.push(yield* decodeUtf8(resource, decoder))
  209. return {
  210. uri: pathToFileURL(real).href,
  211. name: path.basename(real),
  212. content: text.join(""),
  213. encoding: "utf8" as const,
  214. mime: FSUtil.mimeType(real),
  215. }
  216. }
  217. const offset = page.offset ?? 1
  218. const limit = Math.min(page.limit ?? MAX_READ_LINES, MAX_READ_LINES)
  219. const lines: string[] = []
  220. const decoder = new TextDecoder("utf-8", { fatal: true })
  221. let pending = ""
  222. let discard = false
  223. let line = 1
  224. let bytes = 0
  225. let next: number | undefined
  226. const append = (input: string) => {
  227. if (line < offset) {
  228. line++
  229. return true
  230. }
  231. if (lines.length >= limit || bytes >= MAX_READ_BYTES) {
  232. next = line
  233. return false
  234. }
  235. const text = input.length > MAX_LINE_LENGTH ? input.slice(0, MAX_LINE_LENGTH) + MAX_LINE_SUFFIX : input
  236. const size = Buffer.byteLength(text, "utf-8") + (lines.length > 0 ? 1 : 0)
  237. if (bytes + size > MAX_READ_BYTES) {
  238. next = line
  239. return false
  240. }
  241. lines.push(text)
  242. bytes += size
  243. line++
  244. return true
  245. }
  246. const consume = (input: string) => {
  247. let text = input
  248. while (true) {
  249. const index = text.indexOf("\n")
  250. if (index === -1) {
  251. if (!discard) {
  252. pending += text
  253. if (pending.length > MAX_LINE_LENGTH) {
  254. pending = pending.slice(0, MAX_LINE_LENGTH + 1)
  255. discard = true
  256. }
  257. }
  258. break
  259. }
  260. const current = pending + (discard ? "" : text.slice(0, index))
  261. pending = ""
  262. discard = false
  263. text = text.slice(index + 1)
  264. if (!append(current.endsWith("\r") ? current.slice(0, -1) : current)) return false
  265. }
  266. return true
  267. }
  268. const consumeChunk = Effect.fnUntraced(function* (chunk: Uint8Array) {
  269. let start = 0
  270. while (start < chunk.length) {
  271. if (lines.length >= limit || bytes >= MAX_READ_BYTES) {
  272. next = line
  273. return false
  274. }
  275. const newline = chunk.indexOf(10, start)
  276. const end = newline === -1 ? chunk.length : newline + 1
  277. const segment = chunk.subarray(start, end)
  278. if (binary(resource, segment)) return yield* Effect.fail(new BinaryFileError({ resource }))
  279. if (!consume(yield* decodeUtf8(resource, decoder, segment))) return false
  280. start = end
  281. }
  282. return true
  283. })
  284. let done = !(yield* consumeChunk(first))
  285. while (!done) {
  286. const chunk = yield* file.readAlloc(64 * 1024)
  287. if (Option.isNone(chunk)) break
  288. done = !(yield* consumeChunk(chunk.value))
  289. }
  290. if (!done) {
  291. const tail = yield* decodeUtf8(resource, decoder)
  292. if (!discard) pending += tail
  293. if (pending) append(pending.endsWith("\r") ? pending.slice(0, -1) : pending)
  294. }
  295. if (lines.length === 0 && offset !== 1) return yield* Effect.fail(new OffsetOutOfRangeError({ offset }))
  296. return new TextPage({
  297. type: "text-page",
  298. content: lines.join("\n"),
  299. mime: FSUtil.mimeType(real),
  300. offset,
  301. truncated: next !== undefined,
  302. ...(next === undefined ? {} : { next }),
  303. })
  304. }),
  305. )
  306. })
  307. export const list = Effect.fn("ReadTool.list")(function* (fs: FSUtil.Interface, input: string, page: PageInput = {}) {
  308. const real = yield* fs.realPath(input)
  309. const items = yield* fs.readDirectoryEntries(real)
  310. const offset = page.offset ?? 1
  311. const limit = Math.min(page.limit ?? MAX_READ_LINES, MAX_READ_LINES)
  312. const entries = yield* Effect.forEach(
  313. items,
  314. (item) =>
  315. Effect.gen(function* () {
  316. const absolute = path.join(real, item.name)
  317. const target = yield* fs.realPath(absolute).pipe(Effect.catch(() => Effect.void))
  318. if (!target || !FSUtil.contains(real, target)) return
  319. const info = yield* fs.stat(target).pipe(Effect.catch(() => Effect.void))
  320. const type = info?.type === "Directory" ? "directory" : info?.type === "File" ? "file" : undefined
  321. if (!type) return
  322. return FileSystem.Entry.make({
  323. path: RelativePath.make(item.name + (type === "directory" ? path.sep : "")),
  324. type,
  325. })
  326. }),
  327. { concurrency: 16 },
  328. )
  329. const visible = entries
  330. .filter((item): item is FileSystem.Entry => item !== undefined)
  331. .sort((a, b) => (a.type === b.type ? a.path.localeCompare(b.path) : a.type === "directory" ? -1 : 1))
  332. const selected = visible.slice(offset - 1, offset - 1 + limit)
  333. const truncated = offset - 1 + selected.length < visible.length
  334. return new ListPage({ entries: selected, truncated, ...(truncated ? { next: offset + selected.length } : {}) })
  335. })
  336. const layer = Layer.effect(
  337. Service,
  338. Effect.gen(function* () {
  339. const fs = yield* FSUtil.Service
  340. return Service.of({
  341. inspect: (path) => inspect(fs, path),
  342. read: (path, resource, page) => read(fs, path, resource, page),
  343. list: (path, page) => list(fs, path, page),
  344. })
  345. }),
  346. )
  347. export const node = makeLocationNode({ service: Service, layer, deps: [FSUtil.node] })