64875
Mc
mini-coder / files
mini-coder / src / tools / read.ts
2.0 KB
1import { readFileSync } from "node:fs"; 2import { extname } from "node:path"; 3import { Type, type Static } from "@earendil-works/pi-ai"; 4import type { ToolContext, ToolResult } from "./common.ts"; 5 6export const READ_PARAMS = Type.Object( 7 { path: Type.String({ description: "File path" }) }, 8 { additionalProperties: false }, 9); 10export type ReadArgs = Static<typeof READ_PARAMS>; 11 12const IMAGE_MIME: Record<string, string> = { 13 png: "image/png", 14 jpg: "image/jpeg", 15 jpeg: "image/jpeg", 16 webp: "image/webp", 17}; 18 19const MAX_TEXT_CHARS = 100_000; 20/** Cap on the base64 payload sent to the provider, where the file inflates by 4/3. */ 21const MAX_IMAGE_BASE64_BYTES = 5 * 1024 * 1024; 22 23export function read(args: ReadArgs, ctx: ToolContext): ToolResult { 24 const { path } = args; 25 26 let data: Buffer; 27 try { 28 data = readFileSync(path); 29 } catch (error) { 30 return { text: `read failed: ${(error as Error).message}`, isError: true }; 31 } 32 33 const mime = IMAGE_MIME[extname(path).slice(1).toLowerCase()]; 34 if (mime !== undefined) { 35 if (!ctx.supportsImages) { 36 return { text: `read failed: ${path} is an image and the current model does not accept image input`, isError: true }; 37 } 38 const base64 = data.toString("base64"); 39 if (base64.length > MAX_IMAGE_BASE64_BYTES) { 40 return { 41 text: `read failed: ${path} encodes to ${base64.length} bytes, over the ${MAX_IMAGE_BASE64_BYTES} byte image limit`, 42 isError: true, 43 }; 44 } 45 return { 46 text: `read ${path} (${mime}, ${data.length} bytes)`, 47 isError: false, 48 images: [{ type: "image", data: base64, mimeType: mime }], 49 }; 50 } 51 52 if (data.subarray(0, 8000).includes(0)) { 53 return { text: `read failed: ${path} is binary; use bash (file, xxd)`, isError: true }; 54 } 55 56 const text = data.toString("utf8"); 57 if (text.length > MAX_TEXT_CHARS) { 58 return { 59 text: text.slice(0, MAX_TEXT_CHARS) + `\n\n... truncated ... ${path} is ${text.length} characters\n`, 60 isError: false, 61 }; 62 } 63 return { text, isError: false }; 64}