@@ -0,0 +1,100 @@
1+import { Buffer } from "node:buffer";
2+import { extname, isAbsolute, join } from "node:path";
3+import { type Tool, Type } from "@mariozechner/pi-ai";
4+import type { ToolRunnerEvent } from "./types";
5+
6+const imageMimeTypes: Record<string, string> = {
7+ ".bmp": "image/bmp",
8+ ".gif": "image/gif",
9+ ".jpeg": "image/jpeg",
10+ ".jpg": "image/jpeg",
11+ ".png": "image/png",
12+ ".svg": "image/svg+xml",
13+ ".webp": "image/webp",
14+};
15+
16+const description = `## Read tool
17+
18+Read a file by path.
19+
20+For text files, returns line-numbered text. Use \`offset\` and \`limit\` to read a specific range.
21+You can also read images files.
22+`;
23+
24+export const read: Tool = {
25+ name: "read",
26+ description,
27+ parameters: Type.Object({
28+ path: Type.String({
29+ description:
30+ "File path. Absolute or relative to the current working directory.",
31+ }),
32+ offset: Type.Optional(
33+ Type.Number({
34+ description:
35+ "Optional 1-based line number to start reading from. Text files only.",
36+ }),
37+ ),
38+ limit: Type.Optional(
39+ Type.Number({
40+ description:
41+ "Optional maximum number of lines to read. Text files only.",
42+ }),
43+ ),
44+ }),
45+};
46+
47+export async function* runReadTool(
48+ args: Record<string, any>,
49+ signal?: AbortSignal,
50+): AsyncGenerator<ToolRunnerEvent> {
51+ const filePath = isAbsolute(args.path)
52+ ? args.path
53+ : join(process.cwd(), args.path);
54+ const file = Bun.file(filePath);
55+ const exists = await file.exists();
56+
57+ if (!exists) {
58+ yield { type: "result", text: `File not found: ${filePath}` };
59+ return;
60+ }
61+
62+ if (signal?.aborted) {
63+ yield { type: "result", text: "Aborted before read." };
64+ return;
65+ }
66+
67+ const mimeType = imageMimeTypes[extname(filePath).toLowerCase()] ?? file.type;
68+ if (mimeType.startsWith("image/")) {
69+ const data = Buffer.from(await file.arrayBuffer()).toString("base64");
70+ const text = `Image read: ${filePath}\nMIME type: ${mimeType}\nSize: ${file.size} bytes`;
71+ yield {
72+ type: "result",
73+ text,
74+ image: { data, mimeType },
75+ };
76+ return;
77+ }
78+
79+ const content = await file.text();
80+ const lines = content.split(/\r?\n/);
81+ if (content.endsWith("\n")) lines.pop();
82+
83+ const offset = args.offset ?? 1;
84+ const startIndex = offset - 1;
85+ const endIndex = args.limit
86+ ? Math.min(lines.length, startIndex + args.limit)
87+ : lines.length;
88+ const width = String(endIndex).length;
89+ const body = lines
90+ .slice(startIndex, endIndex)
91+ .map((line, idx) => `${String(offset + idx).padStart(width)} | ${line}`)
92+ .join("\n");
93+
94+ let text = `File: ${filePath}\nLines: ${offset}-${endIndex} of ${lines.length}\n\n${body}`;
95+ if (endIndex < lines.length) {
96+ text += `\n\nMore lines available. Use offset ${endIndex + 1} to continue.`;
97+ }
98+
99+ yield { type: "result", text };
100+}