import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { Type } from "typebox"; import { Text, makeOutputText } from "../ui/tui_utils"; import * as path from "node:path"; import * as fs from "node:fs"; import { computeLineHash } from "../editing/smart_anchor"; import { globalEpistemicGuard, resolveUserPath, } from "../safety/epistemic_guard"; import { markReturnedErrors, type SessionDeps } from "./context"; import { isSpilloverFilePath, DEFAULT_SPILL_BYTES } from "../safety/output_clamper"; import { readStreamLineRangeFromFd } from "./stream_reader"; const MAX_READ_LINES = 2_000; const MAX_READ_BYTES = 50 * 1024; const MAX_READ_FILE_BYTES = 5 * 1024 * 1024; const MAX_STREAM_FILE_BYTES = DEFAULT_SPILL_BYTES; const DEFAULT_UNCONSTRAINED_LINES = 250; function validateReadableFile(filePath: string, isStreamable = false): string | null { try { const stat = fs.statSync(filePath); if (!stat.isFile()) return "Path is not a regular file"; const maxAllowed = isStreamable ? MAX_STREAM_FILE_BYTES : MAX_READ_FILE_BYTES; if (stat.size > maxAllowed) { return `File is ${stat.size} bytes; maximum ${isStreamable ? "streamable" : "in-memory source"} size is ${maxAllowed} bytes`; } return null; } catch (error: any) { return error?.code === "ENOENT" ? "File not found" : error?.message || String(error); } } function shouldUseAnchors( params: any, benchmarkMethod: string | undefined, readMode: string | undefined, defaultAnchors: boolean, targeted: boolean, ): boolean { if (params.anchors === true) return true; if (params.raw === true || params.anchors === false) return false; if (readMode === "plain") return false; if (readMode === "anchored") return true; if (benchmarkMethod === "hash-anchor") return true; if (benchmarkMethod === "line-range" || benchmarkMethod === "search-replace" || benchmarkMethod === "adaptive") return false; if (targeted) return defaultAnchors === true; return false; } function formatReadLine( lines: readonly string[], index: number, useAnchors: boolean, numberWidth: number, benchmarkMethod: string | undefined, ): string { const line = lines[index] ?? ""; if (useAnchors) { return `${String(index + 1).padStart(numberWidth, " ")}#${computeLineHash(lines, index)}│${line}`; } if (benchmarkMethod === "line-range" || benchmarkMethod === "adaptive") { return `${String(index + 1).padStart(numberWidth, " ")}│${line}`; } return line; } function selectReadLineIndexes( _lines: readonly string[], startIdx: number, endIdx: number, formatLine: (index: number) => string, ): number[] { const indexes = Array.from({ length: endIdx - startIdx }, (_, index) => startIdx + index); const fits = (candidate: readonly number[]) => candidate.length <= MAX_READ_LINES && Buffer.byteLength(candidate.map(formatLine).join("\n"), "utf8") <= MAX_READ_BYTES; if (indexes.length <= MAX_READ_LINES && fits(indexes)) return indexes; const first = indexes[0]; if (first !== undefined && Buffer.byteLength(formatLine(first), "utf8") > MAX_READ_BYTES) return []; let headCount = Math.min(MAX_READ_LINES, indexes.length); while (headCount > 0 && !fits(indexes.slice(0, headCount))) headCount--; return indexes.slice(0, headCount); } function lineRanges(indexes: readonly number[]): Array<{ startLine: number; endLine: number }> { const ranges: Array<{ startLine: number; endLine: number }> = []; for (const index of indexes) { const line = index + 1; const previous = ranges[ranges.length - 1]; if (previous && previous.endLine === line - 1) previous.endLine = line; else ranges.push({ startLine: line, endLine: line }); } return ranges; } /** Extracted from index.ts — registers the `read` tool. */ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void { // 6. Tool: `read` (Bounded File Reader with Line-Windowing - Replaces stock read tool) const editMethod = process.env.PI_EDIT_METHOD?.toLowerCase(); const benchmarkMethod = ["line-range", "search-replace", "hash-anchor", "adaptive"].includes(editMethod || "") ? editMethod : undefined; const readMode = process.env.PI_READ_MODE?.toLowerCase(); let readToolDescription = "Read file contents with 50KB / 2,000-line caps. Use when inspecting code around known line coordinates, reviewing exact file contents, or reading multiple files via 'paths'. Defaults to 250 lines when limit is omitted. Do NOT use read for finding files or symbols; use code_search (when enabled) or bash (rg, find) instead."; switch (benchmarkMethod) { case "line-range": readToolDescription = "Read source with line numbers for numeric line-range edits."; break; case "search-replace": readToolDescription = "Read source text for exact search/replace edits."; break; case "adaptive": readToolDescription = "Read source with line numbers. Prefer unique search/replace; use line ranges when needed."; break; default: break; } const readToolDefinition: any = { name: "read", label: "Read File", description: readToolDescription, promptSnippet: "Read file contents, inspect line ranges, or read multiple files via 'paths'", renderShell: "default", parameters: Type.Object({ path: Type.Optional( Type.String({ description: "Workspace-relative or absolute file path to inspect. For multiple files, use 'paths'", }), ), paths: Type.Optional( Type.Array(Type.String(), { description: "Array of file paths to read in a single batch (plain text only, bounded per file)", }), ), offset: Type.Optional( Type.Number({ minimum: 1, description: "1-based starting line number for windowed reads (best when examining code around an exact line coordinate from grep or test failures)", }), ), limit: Type.Optional( Type.Number({ minimum: 1, description: "Maximum number of lines to read starting from 'offset' (default: 250 for unconstrained reads; keep <= 60 for narrow inspection)", }), ), anchors: Type.Optional( Type.Boolean({ description: "Emit LINE#HASH│ prefixes on narrow ranges (<100 lines) for positional line disambiguation (default: false, plain text)", }), ), raw: Type.Optional( Type.Boolean({ description: "Clean raw text without line numbers or anchors", }), ), }), async execute( _toolCallId: string, params: any, _signal: any, _onUpdate: any, ctx: any, ) { let targetPaths: string[] = []; if (params && typeof params === "object") { if (Array.isArray(params.paths)) { targetPaths = params.paths.filter((p: any) => typeof p === "string" && p.trim().length > 0); } else if (typeof params.paths === "string" && params.paths.trim().length > 0) { targetPaths = [params.paths.trim()]; } else if (Array.isArray(params.path)) { targetPaths = params.path.filter((p: any) => typeof p === "string" && p.trim().length > 0); } else if (typeof params.path === "string" && params.path.trim().length > 0) { targetPaths = [params.path.trim()]; } } // Detect tool confusion (caller passed shell command to read tool) if (params && typeof params === "object" && typeof params.command === "string" && params.command.trim().length > 0) { if (targetPaths.length > 0) { return { content: [ { type: "text", text: `[READ ERROR] Ambiguous parameters: received both shell 'command' and file 'path'/'paths'. To execute commands, use 'bash'. To read files, use 'read' without 'command'.`, }, ], details: { error: "ambiguous_parameters", command: params.command.trim(), paths: targetPaths }, isError: true, }; } return { content: [ { type: "text", text: `[READ ERROR] Received shell command in 'read' tool. To execute shell commands, invoke the 'bash' tool instead with { command: ${JSON.stringify(params.command.trim())} }. The 'read' tool is for inspecting file contents and requires { path: "path/to/file" }.`, }, ], details: { error: "tool_confusion_command", command: params.command.trim() }, isError: true, }; } if (targetPaths.length === 0) { return { content: [ { type: "text", text: "[READ ERROR] Missing required 'path' or 'paths' parameter." }, ], isError: true, }; } // Batch mode: multiple files in one turn if (targetPaths.length > 1) { const MAX_BATCH_PATHS = 20; const MAX_BATCH_BYTES = 24 * 1024; // 24KB aggregate ceiling across batch const MAX_BATCH_FILE_LINES = 150; // max 150 lines per file in batch mode const pathsToRead = targetPaths.slice(0, MAX_BATCH_PATHS); const results: string[] = []; const detailsList: any[] = []; let hasAnySuccess = false; let cumulativeBytes = 0; for (let i = 0; i < pathsToRead.length; i++) { const filePath = pathsToRead[i]; if (cumulativeBytes >= MAX_BATCH_BYTES) { results.push(`[...] Remaining ${pathsToRead.length - i} file(s) skipped: batch byte limit reached (24KB) [...]`); break; } const resolvedPath = resolveUserPath(filePath, ctx.cwd); const relPath = (path.relative(ctx.cwd, resolvedPath) || filePath).replace(/\\/g, "/"); if (!fs.existsSync(resolvedPath)) { results.push(`=== file: ${relPath} ===\nFile not found: ${filePath}`); continue; } try { const isSpill = isSpilloverFilePath(resolvedPath, ctx.cwd); const isWindowed = params?.offset !== undefined || params?.limit !== undefined; const isStreamable = isSpill || isWindowed; const readLimitError = validateReadableFile(resolvedPath, isStreamable); if (readLimitError) { results.push(`=== file: ${relPath} ===\nRead rejected: ${readLimitError}`); continue; } const stat = fs.statSync(resolvedPath); const needsStreaming = isSpill || stat.size > MAX_READ_FILE_BYTES; const fileOffset = params.offset && params.offset > 0 ? params.offset : 1; const fileLimit = params.limit ? Math.min(params.limit, MAX_BATCH_FILE_LINES) : MAX_BATCH_FILE_LINES; let outputLines: string[]; let totalLines: number; let shownCount: number; let isTruncated: boolean; if (needsStreaming) { const fd = fs.openSync(resolvedPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0)); let streamRes: ReturnType; try { streamRes = readStreamLineRangeFromFd(fd, { offset: fileOffset, limit: fileLimit, maxBytes: Math.min(MAX_READ_BYTES, Math.max(1024, MAX_BATCH_BYTES - cumulativeBytes)), }); } finally { fs.closeSync(fd); } if (streamRes.isBinary) { results.push(`=== file: ${relPath} ===\nRead rejected: Binary file cannot be displayed as text`); continue; } outputLines = streamRes.lines; totalLines = streamRes.endLine; shownCount = streamRes.totalLinesRead; isTruncated = streamRes.hasMore || streamRes.startLine > 1; if (isTruncated) { outputLines.push(`[truncated: ${relPath}, returned lines ${streamRes.startLine}-${streamRes.endLine}. Continue with read(path, offset=${streamRes.endLine + 1})]`); } globalEpistemicGuard.recordFileRead( resolvedPath, deps.getSessionId(ctx), ctx.cwd, streamRes.lines.join("\n"), { coverage: { complete: !streamRes.hasMore && streamRes.startLine === 1, ranges: [{ startLine: streamRes.startLine, endLine: streamRes.endLine }], totalLines, }, provenance: "read", }, ); } else { const content = fs.readFileSync(resolvedPath, "utf-8"); const lines = content.split("\n"); totalLines = lines.length; const startIdx = Math.max(0, fileOffset - 1); const endIdx = Math.min(totalLines, startIdx + fileLimit); const numberWidth = String(totalLines).length; // Batch reads are always plain text to protect token budgets const formatLine = (index: number) => formatReadLine(lines, index, false, numberWidth, benchmarkMethod); const visibleIndexes = selectReadLineIndexes(lines, startIdx, endIdx, formatLine); outputLines = visibleIndexes.map(formatLine); shownCount = visibleIndexes.length; isTruncated = (startIdx + visibleIndexes.length) < totalLines || startIdx > 0; if (isTruncated) { outputLines.push(`[truncated: ${relPath}, returned lines ${startIdx + 1}-${startIdx + visibleIndexes.length} of ${totalLines}. Continue with read(path, offset=${startIdx + visibleIndexes.length + 1})]`); } globalEpistemicGuard.recordFileRead( resolvedPath, deps.getSessionId(ctx), ctx.cwd, content, { coverage: { complete: !isTruncated && startIdx === 0 && endIdx === totalLines, ranges: lineRanges(visibleIndexes), totalLines, }, provenance: "read", }, ); } const formattedOutput = `=== file: ${relPath} (${totalLines} lines) ===\n${outputLines.join("\n")}`; cumulativeBytes += Buffer.byteLength(formattedOutput, "utf8"); results.push(formattedOutput); detailsList.push({ path: filePath, totalLines, shownLines: shownCount, truncated: isTruncated }); hasAnySuccess = true; if (cumulativeBytes >= MAX_BATCH_BYTES && i < pathsToRead.length - 1) { results.push(`[...] Remaining ${pathsToRead.length - 1 - i} file(s) skipped: batch byte limit reached (24KB) [...]`); break; } } catch (err: any) { results.push(`=== file: ${relPath} ===\nError reading file: ${err.message}`); } } if (targetPaths.length > MAX_BATCH_PATHS) { results.push(`[...] Note: Truncated to first ${MAX_BATCH_PATHS} files (${targetPaths.length - MAX_BATCH_PATHS} omitted).`); } return { content: [{ type: "text", text: results.join("\n\n") }], details: { batch: true, count: pathsToRead.length, files: detailsList }, isError: !hasAnySuccess, }; } // Single file read params.path = targetPaths[0]; const resolvedPath = resolveUserPath(params.path, ctx.cwd); if (!fs.existsSync(resolvedPath)) { return { content: [{ type: "text", text: `File not found: ${params.path}` }], isError: true, }; } // Single file read try { const isSpill = isSpilloverFilePath(resolvedPath, ctx.cwd); const isWindowed = params?.offset !== undefined || params?.limit !== undefined; const isStreamable = isSpill || isWindowed; const readLimitError = validateReadableFile(resolvedPath, isStreamable); if (readLimitError) { return { content: [{ type: "text", text: `[READ ERROR] ${readLimitError}: ${params.path}` }], details: { error: "read_limit", maxBytes: isStreamable ? MAX_STREAM_FILE_BYTES : MAX_READ_FILE_BYTES }, isError: true, }; } const ext = path.extname(resolvedPath).toLowerCase(); const isImage = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"].includes( ext, ); if (isImage) { const maxImageBytes = deps.getConfig?.(ctx.cwd).safety.max_total_bytes ?? 20 * 1024; const imageSize = fs.statSync(resolvedPath).size; if (imageSize > maxImageBytes) { return { content: [ { type: "text", text: `[READ ERROR] Image is ${imageSize} bytes; maximum allowed is ${maxImageBytes} bytes.`, }, ], details: { isImage: true, sizeBytes: imageSize, maxImageBytes }, isError: true, }; } const mimeMap: Record = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".bmp": "image/bmp", }; const buffer = fs.readFileSync(resolvedPath); globalEpistemicGuard.recordFileRead( resolvedPath, deps.getSessionId(ctx), ctx.cwd, buffer, { coverage: { complete: true, ranges: [] }, provenance: "read", }, ); const base64 = buffer.toString("base64"); const mimeType = mimeMap[ext] || "image/png"; return { content: [ { type: "text", text: `Read image file [${mimeType}] (${(buffer.length / 1024).toFixed(1)} KB)`, }, { type: "image", data: base64, mimeType }, ], details: { isImage: true, sizeBytes: buffer.length }, }; } // Validate pagination parameters explicitly before I/O if ( params.offset !== undefined && (!Number.isFinite(params.offset) || params.offset < 1) ) { return { content: [ { type: "text", text: `[READ ERROR] Invalid offset=${params.offset}. 'offset' must be a number >= 1 (1-based line number).`, }, ], details: { offset: params.offset }, isError: true, }; } if ( params.limit !== undefined && (!Number.isFinite(params.limit) || params.limit < 1) ) { return { content: [ { type: "text", text: `[READ ERROR] Invalid limit=${params.limit}. 'limit' must be a number >= 1.`, }, ], details: { limit: params.limit }, isError: true, }; } const stat = fs.statSync(resolvedPath); const needsStreaming = isSpill || stat.size > MAX_READ_FILE_BYTES; if (needsStreaming) { let fd: number; try { fd = fs.openSync(resolvedPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0)); } catch (openErr: any) { return { content: [{ type: "text", text: `[READ ERROR] Failed opening ${params.path}: ${openErr?.message || String(openErr)}` }], isError: true, }; } let streamRes: ReturnType; try { const fstat = fs.fstatSync(fd); if (!fstat.isFile()) { return { content: [{ type: "text", text: `[READ ERROR] Path is not a regular file: ${params.path}` }], isError: true }; } if (fstat.size > MAX_STREAM_FILE_BYTES) { return { content: [{ type: "text", text: `[READ ERROR] File is ${fstat.size} bytes; maximum streamable size is ${MAX_STREAM_FILE_BYTES} bytes: ${params.path}` }], isError: true }; } const offset = params.offset && params.offset > 0 ? params.offset : 1; const limit = params.limit ? Math.min(params.limit, MAX_READ_LINES) : DEFAULT_UNCONSTRAINED_LINES; streamRes = readStreamLineRangeFromFd(fd, { offset, limit, maxBytes: MAX_READ_BYTES }); } finally { fs.closeSync(fd); } if (streamRes.isBinary) { return { content: [{ type: "text", text: `[READ ERROR] Binary file cannot be displayed as text: ${params.path}` }], isError: true, }; } const relPath = (path.relative(ctx.cwd, resolvedPath) || params.path).replace(/\\/g, "/"); const numberWidth = String(streamRes.endLine || 1).length; const config = deps.getConfig?.(ctx.cwd); const defaultAnchors = config?.editing?.default_anchors ?? true; const configuredReadMode = readMode ?? config?.editing?.read_mode ?? "auto"; const useAnchors = shouldUseAnchors(params, benchmarkMethod, configuredReadMode, defaultAnchors, false); const formattedLines = streamRes.lines.map((line, idx) => { const lineNum = streamRes.startLine + idx; if (useAnchors) { return `${String(lineNum).padStart(numberWidth, " ")}#${computeLineHash(streamRes.lines, idx)}│${line}`; } if (benchmarkMethod === "line-range" || benchmarkMethod === "adaptive") { return `${String(lineNum).padStart(numberWidth, " ")}│${line}`; } return line; }); if (streamRes.singleLineTruncated) { formattedLines.push("[Line 1 truncated at 50 KB: no newline found in the initial 50 KB of text. File is a single continuous line.]"); } else if (streamRes.hasMore) { formattedLines.push(`[truncated: ${relPath}, returned lines ${streamRes.startLine}-${streamRes.endLine}. Continue with read(path, offset=${streamRes.endLine + 1})]`); } globalEpistemicGuard.recordFileRead( resolvedPath, deps.getSessionId(ctx), ctx.cwd, streamRes.lines.join("\n"), { coverage: { complete: !streamRes.hasMore && streamRes.startLine === 1, ranges: [{ startLine: streamRes.startLine, endLine: streamRes.endLine }], }, provenance: "read", }, ); return { content: [{ type: "text", text: formattedLines.join("\n") }], details: { offset: streamRes.startLine, limit: streamRes.totalLinesRead, hasMore: streamRes.hasMore, streamed: true, singleLineTruncated: streamRes.singleLineTruncated, }, }; } const content = fs.readFileSync(resolvedPath, "utf-8"); const lines = content.split("\n"); const totalLines = lines.length; // Validate pagination params explicitly. The previous truthiness // check silently coerced offset=0 -> 1, clamped negatives, and // treated limit=0 as "use the default 2000" — surprising behavior // for an out-of-range request. if ( params.offset !== undefined && (!Number.isFinite(params.offset) || params.offset < 1) ) { return { content: [ { type: "text", text: `[READ ERROR] Invalid offset=${params.offset}. 'offset' must be a number >= 1 (1-based line number).`, }, ], details: { offset: params.offset }, isError: true, }; } if ( params.limit !== undefined && (!Number.isFinite(params.limit) || params.limit < 1) ) { return { content: [ { type: "text", text: `[READ ERROR] Invalid limit=${params.limit}. 'limit' must be a number >= 1.`, }, ], details: { limit: params.limit }, isError: true, }; } const offset = params.offset ?? 1; const hasExplicitLimit = typeof params.limit === "number"; const limit = hasExplicitLimit ? params.limit : Math.min(totalLines, DEFAULT_UNCONSTRAINED_LINES); const startIdx = offset - 1; // Offset past the end of file: return a clean error instead of an // empty slice with an inverted header and bogus continuation hint. if (startIdx >= totalLines) { return { content: [ { type: "text", text: `[READ ERROR] offset=${offset} is beyond the end of the file (${totalLines} line${totalLines === 1 ? "" : "s"}). Re-read without 'offset' to see the whole file.`, }, ], details: { totalLines, offset }, isError: true, }; } const config = deps.getConfig?.(ctx.cwd); const defaultAnchors = config?.editing?.default_anchors ?? true; const configuredReadMode = readMode ?? config?.editing?.read_mode ?? "auto"; const useAnchors = shouldUseAnchors(params, benchmarkMethod, configuredReadMode, defaultAnchors, false); // Guardrail against excessive anchored line bloat const MAX_ANCHOR_LINES = 100; let effectiveLimit = limit; let anchorNotice = ""; if (useAnchors && effectiveLimit > MAX_ANCHOR_LINES) { effectiveLimit = MAX_ANCHOR_LINES; anchorNotice = `\n[Notice: Anchored read capped to 100 lines to prevent token bloat. For broader inspection, use plain read without 'anchors'.]`; } const endIdx = Math.min(totalLines, startIdx + effectiveLimit); const numberWidth = String(totalLines).length; const formatLine = (index: number) => formatReadLine(lines, index, useAnchors, numberWidth, benchmarkMethod); const firstLineBytes = Buffer.byteLength(formatLine(startIdx), "utf8"); const oversizedFirstLine = firstLineBytes > MAX_READ_BYTES; const visibleIndexes = oversizedFirstLine ? [] : selectReadLineIndexes(lines, startIdx, endIdx, formatLine); const hiddenLines = endIdx - startIdx - visibleIndexes.length; const hasMore = hiddenLines > 0 || endIdx < totalLines; const outputLines = oversizedFirstLine ? [`[Line ${startIdx + 1} is ${firstLineBytes} bytes, exceeds ${MAX_READ_BYTES} byte limit. Use bash to inspect this line in chunks.]`] : visibleIndexes.map(formatLine); if (hiddenLines > 0 && !oversizedFirstLine) { outputLines.push(`[...] ${hiddenLines} lines omitted [...]. Use offset=${startIdx + visibleIndexes.length + 1} to continue.`); } if (anchorNotice) { outputLines.push(anchorNotice); } const isTruncated = oversizedFirstLine || hasMore || startIdx > 0; if (isTruncated && hasMore && !oversizedFirstLine && hiddenLines === 0) { const lastIdx = visibleIndexes[visibleIndexes.length - 1]; if (lastIdx !== undefined) { const lastShown = lastIdx + 1; outputLines.push(`\n[Showing ${visibleIndexes.length} of ${totalLines} lines. Use offset=${lastShown + 1} to continue.]`); } } const coverageRanges = lineRanges(visibleIndexes); // Record only the lines actually exposed to the model. The full content // still supplies the freshness fingerprint without authorizing hidden lines. globalEpistemicGuard.recordFileRead( resolvedPath, deps.getSessionId(ctx), ctx.cwd, content, { coverage: { complete: !isTruncated && startIdx === 0 && endIdx === totalLines, ranges: coverageRanges, totalLines, }, provenance: "read", }, ); return { content: [{ type: "text", text: outputLines.join("\n") }], details: { totalLines, offset, limit, shownLines: visibleIndexes.length, truncated: isTruncated }, }; } catch (err: any) { return { content: [{ type: "text", text: `Failed to read file: ${err.message}` }], isError: true, }; } }, renderCall(args: any, theme: any, context: any) { const targetPaths = Array.isArray(args?.paths) ? args.paths : (Array.isArray(args?.path) ? args.path : []); if (targetPaths.length > 1) { const pathsSummary = targetPaths.map((p: string) => (path.relative(context.cwd, p) || p).replace(/\\/g, "/")).join(", "); return makeOutputText( `${theme.fg("toolTitle", theme.bold("read"))} [${theme.fg("accent", pathsSummary)}]`, ); } const path0 = Array.isArray(args?.paths) ? args.paths[0] : ""; const rawPath = args?.path || path0 || ""; const relPath = rawPath ? (path.relative(context.cwd, rawPath) || rawPath).replace(/\\/g, "/") : ""; let range = ""; if (args?.offset || args?.limit) { const off = args.offset ?? 1; const lim = args.limit ? `-${off + args.limit - 1}` : ""; range = `:${off}${lim}`; } return makeOutputText( `${theme.fg("toolTitle", theme.bold("read"))} ${theme.fg("accent", relPath)}${theme.fg("warning", range)}`, ); }, renderResult(result: any, options: any, theme: any, context: any) { if (context.isError) { const errMsg = result.content?.find((c: any) => c.type === "text")?.text || "Read failed"; return makeOutputText(`\n${theme.fg("error", errMsg)}`); } if (!options.expanded) { return new Text("", 0, 0); } const output = result.content?.find((c: any) => c.type === "text")?.text || ""; return makeOutputText(`\n${theme.fg("toolOutput", output)}`); }, }; pi.registerTool(markReturnedErrors(readToolDefinition)); }