import { createReadStream } from 'node:fs'; import { open, readFile, stat, writeFile } from 'node:fs/promises'; import { extname } from 'node:path'; import { runBoundedProcess } from '../../runtime/boundedProcess.js'; import { mkdir } from 'node:fs/promises'; import { join } from 'node:path'; import { randomUUID } from 'node:crypto'; import { z } from 'zod'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { dlog } from '../../utils/debugLog.js'; import { safeSlice } from '../../utils/safeText.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS, MAX_FILE_SIZE_BYTES, MAX_LINES_TO_READ, } from '../types.js'; import { fileActivityMetadata } from '../shared/fileActivity.js'; import { hashFileBytes, recordRead, type FileReadState, } from '../shared/fileState.js'; import { hasBinaryExtension, isBlockedDevicePath, readTextFile, resolveToolPath, } from '../shared/fileUtils.js'; import { filePathField } from '../shared/schemas.js'; import { pruneRuntimeOutputs, sessionRuntimeDir, type RuntimeIdentity, } from '../../session/runtimeStore.js'; import { detectImageMime, resolveLocalImage, } from '../../images/imageResolver.js'; const PDF_PAGE_LIMIT = 20; const inputSchema = z.object({ file_path: filePathField('读取'), column: z.number().int().positive().optional().describe('超长行续读:起始行内的 1-based UTF-16 字符位置;普通阅读省略。'), max_chars: z.number().int().min(1000).max(1_000_000).optional().describe('期望正文字符预算,最多 100 万;Runtime 会按剩余上下文与并发读取预算收紧。'), offset: z .number() .int() .positive() .optional() .describe( '文本文件为 1-indexed 起始行;Jupyter Notebook 为 1-indexed 起始 cell', ), limit: z .number() .int() .positive() .optional() .describe(`最多读取的文本行或 Notebook cells;默认 ${MAX_LINES_TO_READ}`), pages: z .string() .regex(/^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/) .optional() .describe(`PDF 页码,例如 "1-5,8";每次最多 ${PDF_PAGE_LIMIT} 页`), pdf_mode: z .enum(['auto', 'text', 'visual', 'both']) .default('auto') .optional(), }); type ReadInput = z.infer; const IMAGE_EXTENSIONS = new Set([ '.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.tif', '.tiff', '.avif', '.heic', '.heif', '.svg', ]); const MAX_IMAGE_BYTES = 25 * 1024 * 1024; const MAX_NOTEBOOK_BYTES = 32 * 1024 * 1024; const description = `读取文本、图片、Notebook 或 PDF。offset 从 1 开始;大范围阅读可提高 limit/max_chars,实际预算由 Runtime 分配。按回执 offset/column 续读,不能跳过截断行。PDF 用 pages,一次最多 ${PDF_PAGE_LIMIT} 页。`; function notebookSource(value: unknown): string { if (Array.isArray(value)) return value .filter((item): item is string => typeof item === 'string') .join(''); return typeof value === 'string' ? value : ''; } function renderNotebook( raw: string, offset: number, limit: number, ): { content: string; total: number; selectedCount: number; partial: boolean; } { const parsed = JSON.parse(raw) as { cells?: unknown[]; metadata?: Record; }; if (!Array.isArray(parsed.cells)) throw new Error('Notebook 缺少 cells 数组'); const start = offset - 1; const cells = parsed.cells.slice(start, start + limit); const parts = cells.map((value, index) => { const cell = value && typeof value === 'object' ? (value as Record) : {}; const outputs = Array.isArray(cell.outputs) ? cell.outputs : []; const renderedOutputs = outputs .slice(0, 8) .map((output) => { if (!output || typeof output !== 'object') return String(output ?? ''); const item = output as Record; const text = item.text ?? (item.data && typeof item.data === 'object' ? (item.data as Record)['text/plain'] : undefined); return notebookSource(text).slice(0, 2_000); }) .filter(Boolean) .join('\n'); return [ `## Cell ${start + index + 1} [selector=cell-${start + index + 1}${typeof cell.id === 'string' ? `; id=${cell.id}` : ''}; type=${String(cell.cell_type ?? 'unknown')}]`, notebookSource(cell.source), ...(renderedOutputs ? [`\nOutput:\n${renderedOutputs}`] : []), ].join('\n'); }); const end = start + cells.length; if (end < parsed.cells.length) parts.push( `... (${parsed.cells.length - end} cells remain; continue with offset=${end + 1})`, ); return { content: parts.join('\n\n'), total: parsed.cells.length, selectedCount: cells.length, partial: start > 0 || end < parsed.cells.length, }; } export async function readStreamedText( filePath: string, offset: number, limit: number, signal?: AbortSignal, maxChars = DEFAULT_MAX_RESULT_SIZE_CHARS, column = 1, ): Promise<{ numbered: string; totalKnown: number; selectedCount: number; hasMore: boolean; clippedLine?: number; }> { const handle = await open(filePath, 'r'); const prefix = Buffer.alloc(3); const { bytesRead } = await handle.read(prefix, 0, 3, 0); await handle.close(); const utf16 = bytesRead >= 2 && prefix[0] === 0xff && prefix[1] === 0xfe; const stream = createReadStream(filePath, { signal, encoding: utf16 ? 'utf16le' : 'utf8', start: utf16 ? 2 : bytesRead >= 3 && prefix[0] === 0xef && prefix[1] === 0xbb && prefix[2] === 0xbf ? 3 : 0, }); const lines: string[] = []; let line = 1; let hasMore = false; let chars = 0; let clippedLine: number | undefined; let pending = ''; let skip = column - 1; let sawData = false; const append = (part: string, end: boolean): boolean => { if (line < offset) { if (end) line++; return true; } if (line === offset && skip) { const consumed = Math.min(skip, part.length); part = part.slice(consumed); skip -= consumed; } if (lines.length >= limit) { hasMore = true; return false; } const allowance = maxChars - chars - String(line).length - 1; if (pending.length + part.length > allowance) { if (!lines.length) { const preview = (pending + part).slice(0, Math.max(0, allowance)).replace(/[\uD800-\uDBFF]$/, ''); lines.push(`${line}\t${preview}`); clippedLine = line; } hasMore = true; return false; } pending += part; if (end) { const numbered = `${line}\t${pending.replace(/\r$/, '')}`; lines.push(numbered); chars += numbered.length + 1; pending = ''; line++; } return true; }; try { outer: for await (const chunk of stream) { sawData = true; const text = String(chunk); let start = 0; for (let end = text.indexOf('\n'); end !== -1; end = text.indexOf('\n', start)) { if (!append(text.slice(start, end), true)) break outer; start = end + 1; } if (start < text.length && !append(text.slice(start), false)) break; } if (!hasMore && sawData) append('', true); } finally { stream.destroy(); } return { numbered: lines.join('\n'), totalKnown: hasMore ? line : sawData ? line - 1 : 0, selectedCount: lines.length, hasMore, clippedLine, }; } async function call( input: ReadInput, state?: FileReadState, cwd?: string, runtimeIdentity?: RuntimeIdentity, signal?: AbortSignal, maxChars = DEFAULT_MAX_RESULT_SIZE_CHARS, ): Promise { if (signal?.aborted) return { ok: false, error: 'aborted' }; if (maxChars < 1000) return { ok: false, error: '本批读取上下文预算已用完;请先处理已有结果或压缩上下文,再继续读取。' }; const offset = input.offset ?? 1; const limit = input.limit ?? MAX_LINES_TO_READ; const resolved = resolveToolPath(input.file_path, cwd); if (!resolved.ok) return resolved; const filePath = resolved.resolvedPath; if (isBlockedDevicePath(filePath)) return { ok: false, error: `不允许读取设备文件:${filePath}` }; const info = await stat(filePath).catch((error: Error) => ({ error })); if ('error' in info) return { ok: false, error: `文件不存在或无法读取:${filePath}(${info.error.message})`, }; if (!info.isFile()) return { ok: false, error: `${filePath} 不是文件;目录请用 Glob。` }; const ext = extname(filePath).toLowerCase(); if (ext === '.pdf') { try { const bytes = await readFile(filePath); if (bytes.subarray(0, 5).toString() !== '%PDF-') { return { ok: false, error: '文件扩展名是 PDF,但缺少有效 %PDF- 文件头', }; } const pdfjs = await import('pdfjs-dist/legacy/build/pdf.mjs'); // ⚠️ 释放要调**加载任务**的 destroy,不是文档代理的:pdfjs v6 的 // PDFDocumentProxy 上没有 destroy(只有 cleanup),写成 document.destroy() // 会在 finally 里抛 TypeError,被外层 catch 成「PDF 解析失败」—— // 于是每一次 PDF 读取都失败,且错误文案完全指不向真因。 const loadingTask = pdfjs.getDocument({ data: new Uint8Array(bytes), useSystemFonts: true, }); const document = await loadingTask.promise; try { const requested = parsePdfPages(input.pages, document.numPages); const chunks: string[] = []; for (const pageNumber of requested) { const page = await document.getPage(pageNumber); const text = await page.getTextContent(); chunks.push( `## Page ${pageNumber}\n${text.items .map((item) => 'str' in item && typeof item.str === 'string' ? item.str : '', ) .filter(Boolean) .join(' ')}`, ); } const mode = input.pdf_mode ?? 'auto'; const sparse = chunks.join('').replace(/\s/g, '').length < requested.length * 80; const wantVisual = mode === 'visual' || mode === 'both' || (mode === 'auto' && sparse); const images = wantVisual ? await renderPdfPages( document, filePath, requested, runtimeIdentity, signal, ) : []; if (wantVisual && images.length !== requested.length) { return { ok: false, error: `PDF 视觉渲染不完整:请求 ${requested.length} 页,成功 ${images.length} 页;请缩小页码范围或检查 Canvas/Poppler。不得将缺页当作已读取。` }; } recordRead(filePath, { partial: true }, state); const rawText = mode === 'visual' ? '[visual-only mode]' : chunks.join('\n\n'); const text = rawText.length > DEFAULT_MAX_RESULT_SIZE_CHARS ? `${rawText.slice(0, DEFAULT_MAX_RESULT_SIZE_CHARS)}\n... (PDF 文本输出已截断;请缩小 pages 范围继续读取)` : rawText; return { ok: true, content: `PDF ${document.numPages} pages; selected ${requested.join(', ')}.\n\n${text}${wantVisual && !images.length ? '\n\n视觉渲染不可用(Canvas 与 pdftoppm 均不可用);文本提取结果仍可用。' : ''}`, metadata: await fileActivityMetadata( filePath, 'read', 'not_run', 'source', cwd, ), ...(images.length ? { visionImages: images.map((source) => ({ source })), visionNote: '这是所选 PDF 页面的视觉渲染,请检查版式、图表和扫描内容。', } : {}), }; } finally { await loadingTask.destroy().catch(() => undefined); } } catch (error) { const message = (error as Error).message; return { ok: false, error: `PDF 解析失败${/password/i.test(message) ? '(文件可能已加密)' : ''}:${message}`, }; } } // Sniff the header rather than reading every text file twice. let detectedImage; try { const probe = await open(filePath, 'r'); try { const header = Buffer.alloc(64); const { bytesRead } = await probe.read(header, 0, header.length, 0); detectedImage = detectImageMime(header.subarray(0, bytesRead)); } finally { await probe.close(); } } catch (error) { return { ok: false, error: `文件读取失败:${(error as Error).message}` }; } if (IMAGE_EXTENSIONS.has(ext) || detectedImage) { if (info.size > MAX_IMAGE_BYTES) return { ok: false, error: `图片超过 ${MAX_IMAGE_BYTES} 字节上限` }; let resolvedImage; try { resolvedImage = await resolveLocalImage(filePath, { maxInputBytes: MAX_IMAGE_BYTES, }); } catch (error) { return { ok: false, error: `图片读取失败:${(error as Error).message}` }; } let bytes: Buffer; try { bytes = await readFile(filePath, { signal }); } catch (error) { return { ok: false, error: `图片读取失败:${(error as Error).message}` }; } recordRead(filePath, { contentHash: hashFileBytes(bytes) }, state); return { ok: true, content: `已读取图片:${filePath}(${info.size} 字节,实际格式 ${resolvedImage.originalMime})${resolvedImage.transformed ? `;已规范化为 ${resolvedImage.mime}` : ''}。图像已附加供视觉模型直接检查。`, metadata: await fileActivityMetadata( filePath, 'read', 'not_run', 'source', cwd, ), visionImages: [{ source: resolvedImage.path }], visionNote: '这是 Read 工具读取的本地图片,请直接检查图像内容。', }; } if (ext === '.ipynb') { if (info.size > MAX_NOTEBOOK_BYTES) return { ok: false, error: `Notebook 超过 ${MAX_NOTEBOOK_BYTES} 字节上限`, }; try { const snapshot = await readTextFile(filePath); const rendered = renderNotebook( snapshot.content, offset, Math.min(limit, 200), ); let content = rendered.content; let truncated = false; if (content.length > DEFAULT_MAX_RESULT_SIZE_CHARS) { content = `${content.slice(0, DEFAULT_MAX_RESULT_SIZE_CHARS)}\n\n... (Notebook 输出已截断)`; truncated = true; } recordRead( filePath, { offset, limit, partial: rendered.partial, truncated, range: rendered.selectedCount > 0 ? { start: offset, end: Math.min( rendered.total, offset + rendered.selectedCount - 1, ), } : undefined, totalUnits: rendered.total, ...(!rendered.partial && !truncated ? { contentHash: hashFileBytes(snapshot.bytes) } : {}), }, state, ); return { ok: true, content, metadata: await fileActivityMetadata( filePath, 'read', 'not_run', 'source', cwd, ), }; } catch (error) { return { ok: false, error: `Notebook 解析失败:${(error as Error).message}`, }; } } if (hasBinaryExtension(filePath)) { return { ok: false, error: `不支持直接读取 ${ext || '该二进制格式'};PDF/Office 文件请使用对应 Skill。`, }; } if (info.size > MAX_FILE_SIZE_BYTES) { return { ok: false, error: `文件超过 ${MAX_FILE_SIZE_BYTES} 字节硬上限。请用 Grep 定位,或用 Bash 做流式处理。`, }; } try { let content: string; let totalLines: number; let selectedCount: number; let hasMore: boolean; let completeBytes: Buffer | undefined; let totalUnits: number | undefined; let clippedLine: number | undefined; const streamed = await readStreamedText(filePath, offset, limit, signal, maxChars, input.column); content = streamed.numbered; totalLines = streamed.totalKnown; selectedCount = streamed.selectedCount; hasMore = streamed.hasMore; clippedLine = streamed.clippedLine; totalUnits = hasMore ? undefined : totalLines; if (!hasMore && offset === 1 && (input.column ?? 1) === 1) completeBytes = await readFile(filePath, { signal }); const afterRead = await stat(filePath); if (afterRead.mtimeMs !== info.mtimeMs || afterRead.size !== info.size || afterRead.ino !== info.ino) return { ok: false, error: '读取期间文件发生变化,请重新读取;本次不登记读取覆盖范围。' }; if (!content) content = totalLines === 0 ? '' : ``; let truncated = false; if (content.length > maxChars || clippedLine !== undefined) { const nextColumn = (input.column ?? 1) + Math.max(0, content.length - String(offset).length - 1); content = `${safeSlice(content, 0, maxChars)}\n\n⚠️ 重要:Read 输出已截断;截断范围外仍有内容。超长行请提高 max_chars 或使用流式处理,不能跳过未显示内容。`; if (clippedLine !== undefined) content += `\n继续读取 offset=${clippedLine} column=${nextColumn}`; truncated = true; } const partial = offset !== 1 || hasMore || (input.column ?? 1) > 1; if (hasMore && !truncated) content += `\n\n... (还有更多内容;继续使用 offset=${offset + selectedCount})`; const reads = recordRead( filePath, { offset, column: input.column, limit, partial, truncated, range: selectedCount > 0 && (input.column ?? 1) === 1 ? { start: offset, end: offset + selectedCount - 1, } : undefined, totalUnits, ...(!partial && !truncated && completeBytes ? { contentHash: hashFileBytes(completeBytes) } : {}), }, state, ); if (info.size > 100 * 1024 && offset === 1) { content = `⚠️ 大文件:结果受行数和输出字符上限约束,请按需分段读取。\n\n${content}`; } if (reads >= 2) content = `⚠️ 重复读取空转:该区间未变化,前一次 Read 结果仍然有效。\n\n${content}`; return { ok: true, content, observation: { path: filePath, unit: 'line', // A truncated response does not establish coverage of its full range. ...(!truncated && selectedCount > 0 && (input.column ?? 1) === 1 ? { start: offset, end: offset + selectedCount - 1 } : {}), truncated, partial: partial || truncated, ...(completeBytes ? { sha256: hashFileBytes(completeBytes) } : {}), observedAt: Date.now(), }, metadata: await fileActivityMetadata( filePath, 'read', 'not_run', 'source', cwd, ), }; } catch (error) { return { ok: false, error: `读取失败:${(error as Error).message}` }; } } async function renderPdfPages( document: Awaited< ReturnType< (typeof import('pdfjs-dist/legacy/build/pdf.mjs'))['getDocument'] > >['promise'] extends Promise ? T : never, filePath: string, pages: number[], identity?: RuntimeIdentity, signal?: AbortSignal, ): Promise { const outputDir = join(sessionRuntimeDir(identity ?? {}), 'outputs'); const outputPrefix = `pdf_${randomUUID()}`; await mkdir(outputDir, { recursive: true, mode: 0o700 }); const images: string[] = []; const dynamicImport = new Function( 'specifier', 'return import(specifier)', ) as (specifier: string) => Promise<{ createCanvas?: ( width: number, height: number, ) => { getContext(type: '2d'): unknown; toBuffer(type: 'image/png'): Buffer; }; }>; let createCanvas: Awaited>['createCanvas']; try { const napi = await dynamicImport('@napi-rs/canvas'); createCanvas = napi.createCanvas; // ⚠️ **必须在 pdfjs 之前把这几个全局占住**,否则 PDF 转图 100% 失败。 // // pdfjs 的 legacy 构建在 Node 环境下自己往 globalThis 装一套 Path2D / // DOMMatrix / ImageData polyfill。渲染时它 `new Path2D()` 拿到的是**它自己那份**, // 转手调 `ctx.fill(path, 'evenodd')` 交给 @napi-rs/canvas —— 而 napi 的原生绑定 // 只认自己的 `Path`,于是每一页都抛 // `Value is none of these types \`String\`, \`Path\`` // 两份 polyfill 撞车,谁都没错,就是不是同一个对象。 // // 实测:五种 render 参数组合(canvas / canvasContext / canvas:null / 带不带 // standardFontDataUrl)全部同样失败 —— 也就是说 `canvas` 那个类型错**不是**病因, // 修类型并不能让它跑起来。把全局换成 napi 的实现之后第 1 页立刻渲染出 137KB PNG。 for (const name of ['Path2D', 'DOMMatrix', 'ImageData'] as const) { const impl = (napi as Record)[name]; if (impl) (globalThis as Record)[name] = impl; } } catch (e) { // optional adapter:没装 @napi-rs/canvas 就回落 pdftoppm。 // 但「没装」和「装了却加载失败」对用户是两件事,别都吞成前者。 dlog('read:pdf', `@napi-rs/canvas 不可用:${e instanceof Error ? e.message : e}`); } if (createCanvas) { try { for (const pageNumber of pages) { signal?.throwIfAborted(); const page = await document.getPage(pageNumber); const viewport = page.getViewport({ scale: 2 }); const canvas = createCanvas( Math.ceil(viewport.width), Math.ceil(viewport.height), ); // ⚠️ pdfjs v6 的 RenderParameters 里 `canvas` 是**必填**、`canvasContext` // 反而降级为可选且不推荐;文档明说「若必须用 context,canvas 必须为 null」。 // 只给 canvasContext 会类型不过(`bun run typecheck` 唯一的红)。 // 运行时它有默认值 `canvas = canvasContext.canvas` 所以不炸 —— 但类型要对。 await page.render({ canvasContext: canvas.getContext('2d') as never, canvas: null, viewport, }).promise; const target = join( outputDir, `${outputPrefix}-page-${pageNumber}.png`, ); await writeFile(target, canvas.toBuffer('image/png'), { mode: 0o600 }); images.push(target); } void pruneRuntimeOutputs(); return images; } catch (e) { // ⚠️ 别把这里改回裸 catch。上面那个 Path2D 冲突就是被它藏住的: // Canvas 每页都抛 → images 清空 → 回落 pdftoppm。装了 poppler 的机器照样 // 出图(只是分辨率更低、多一次进程),**完全看不出来**;没装 poppler 的机器 // (多数 Windows、绿色版 U 盘)则返回 `ok:true` + 0 张图 + 一句 // 「视觉渲染不可用(Canvas 与 pdftoppm 均不可用)」——而 Canvas 明明可用, // 只是抛了。错误文案把人指向「装依赖」,真因一个字都查不到。 dlog('read:pdf', `Canvas 渲染失败:${e instanceof Error ? e.message : e}`); images.length = 0; } } for (const pageNumber of pages) { signal?.throwIfAborted(); const prefix = join(outputDir, `${outputPrefix}-page-${pageNumber}`); try { const result = await runBoundedProcess( 'pdftoppm', [ '-f', String(pageNumber), '-l', String(pageNumber), '-singlefile', '-png', '-r', '144', filePath, prefix, ], { timeoutMs: 120_000, signal }, ); if (result.exitCode !== 0) throw new Error(result.stderr); images.push(`${prefix}.png`); } catch { break; } } void pruneRuntimeOutputs(); return images; } function parsePdfPages(spec: string | undefined, total: number): number[] { if (!spec) return Array.from({ length: Math.min(total, PDF_PAGE_LIMIT) }, (_, index) => index + 1); const pages = new Set(); for (const part of spec.split(',')) { const [first, last] = part.split('-').map(Number); if (!Number.isSafeInteger(first) || !Number.isSafeInteger(last ?? first) || (last ?? first!) < first!) throw new Error(`无效 PDF 页码范围:${part}`); for (let page = first!; page <= (last ?? first!); page += 1) { if (page < 1 || page > total) throw new Error(`PDF 页码超出范围:${page}(共 ${total} 页)`); pages.add(page); if (pages.size > PDF_PAGE_LIMIT) throw new Error(`一次最多读取 ${PDF_PAGE_LIMIT} 个 PDF 页面`); } } return [...pages].sort((left, right) => left - right); } export const readTool: Tool = { name: 'Read', description, inputSchema, parameters: toToolParameters(inputSchema), isReadOnly: true, isConcurrencySafe: true, maxResultSizeChars: 1_010_000, interruptBehavior: () => 'cancel', call: (input, signal) => call(input, undefined, undefined, undefined, signal, input.max_chars ?? DEFAULT_MAX_RESULT_SIZE_CHARS), callWithContext: (input, signal, context: ToolCallContext) => call(input, context.sessionState?.fileReads, context.cwd, context, signal, context.reserveReadChars?.(input.max_chars) ?? input.max_chars ?? DEFAULT_MAX_RESULT_SIZE_CHARS), };