/** * tools/invoice-parse.ts — invoice_parse 工具:单张/批量发票解析。 * * 行为(对照功能规格第 1 条): * - path 为文件或目录(目录递归扫描,自动识别 pdf/jpg/png); * - 优先解析 PDF 内嵌结构化 XML(号码/代码/金额/税额/双方/日期),文本层正则兜底; * - 输出结构化 JSON + 会话内"抽取结果核对表"(confidence:XML 直读=高/正则=中/缺失=低并列出); * - 勾稽校验:价税合计 = 金额 + 税额(容差 0.01),不符时在核对表标 ⚠; * - 纯图片无 OCR / 加密 PDF 返回明确"跳过原因",不中断批量。 */ import { defineTool } from '@deepseek-ai/dsh-tools' import type { Context } from '@deepseek-ai/cordis' import { extractPdf, detectFileKind } from '../pdf-extract.ts' import { type InvoiceData, parseInvoiceFromTextLines, parseInvoiceFromXml, validateInvoice, } from '../invoice-model.ts' /** 解析缓存:invoice_summary 缺省 files 时复用上次 parse 结果。 * key 为 `${scope}:${absPath}`,scope 为会话 id(工具执行上下文的 agent.id)——按会话隔离; * 无法取得会话上下文时回退 'global'(进程级缓存,README「安全与隐私」已如实说明)。 */ export const parseCache = new Map() /** 缓存作用域:有会话 id 用会话 id;否则回退 'global'(进程级,见 README)。 */ export function cacheScope(sessionId: string | undefined | null): string { return sessionId && sessionId.length > 0 ? sessionId : 'global' } /** 单文件读取上限(PDF 通常 < 8MB,给 16MB 余量)。 */ const MAX_BYTES = 16 * 1024 * 1024 export interface SkippedFile { path: string file: string reason: 'password-protected' | 'image-without-ocr' | 'unsupported-file-type' | 'unparsable' | 'empty-pdf' detail?: string } export interface InvoiceParseResult { inputCount: number parsed: (InvoiceData & { path: string })[] skipped: SkippedFile[] summary: { parsedCount: number skippedCount: number amount: number tax: number total: number checksFailed: number } } const SUPPORTED_EXT = new Set(['.pdf', '.jpg', '.jpeg', '.png']) function hasSupportedExt(name: string): boolean { const lower = name.toLowerCase() for (const ext of SUPPORTED_EXT) if (lower.endsWith(ext)) return true return false } /** 递归收集发票文件(目录深度上限 3)。 */ async function collectFiles(ctx: Context, target: Awaited>, signal: AbortSignal | undefined, depth: number, acc: { name: string; target: Awaited> }[]): Promise { if (depth > 3) return const info = await ctx.fs.stat(target, signal) if (!info) return if (info.type === 'file') { const abs = ctx.fs.processPath(target) if (hasSupportedExt(abs)) acc.push({ name: abs.split('/').pop() ?? abs, target }) return } if (info.type === 'directory') { const entries = await ctx.fs.listDir(target, signal) for (const entry of entries) { if (entry.type === 'file' && hasSupportedExt(entry.name)) acc.push({ name: entry.name, target: entry.target }) else if (entry.type === 'directory') await collectFiles(ctx, entry.target, signal, depth + 1, acc) } } } /** 解析单文件字节为 InvoiceData 或跳过记录。 */ function parseOne(ctx: Context, path: string, name: string, bytes: Uint8Array): { invoice?: InvoiceData; skipped?: SkippedFile } { const kind = detectFileKind(bytes, name) if (kind === 'png' || kind === 'jpg') { return { skipped: { path, file: name, reason: 'image-without-ocr', detail: '纯图片无 OCR:首版不支持扫描件识别,见 README(后续可对接社区 vision 插件)' } } } if (kind === 'other') { return { skipped: { path, file: name, reason: 'unsupported-file-type', detail: `不支持的文件类型(检测到非 PDF/PNG/JPEG 内容,扩展名 ${name.split('.').pop() ?? ''})` } } } // PDF const extraction = extractPdf(bytes) if (extraction.encrypted) { return { skipped: { path, file: name, reason: 'password-protected', detail: 'PDF 声明 /Encrypt(密码保护或加密),无法解析' } } } const xmlText = extraction.embeddedXml.length > 0 ? extraction.embeddedXml.join('\n') : '' if (xmlText.trim().length > 0) { const invoice = parseInvoiceFromXml(xmlText, name, extraction.text) if (invoice.invoiceNumber === '' && invoice.amount === 0 && invoice.total === 0) { return { skipped: { path, file: name, reason: 'unparsable', detail: '找到 XML 附件但未抽取到有效字段(附件 Schema 不在白名单内)' } } } return { invoice } } if (extraction.text.trim().length > 0) { return { invoice: parseInvoiceFromTextLines(extraction.text, name) } } return { skipped: { path, file: name, reason: 'empty-pdf', detail: 'PDF 无文本层且无 XML 附件(扫描件需 OCR)' } } } /** 执行解析编排(也被工具 execute 与测试复用其纯逻辑核心)。 */ export async function runInvoiceParse( ctx: Context, args: { path: string }, signal?: AbortSignal, sessionId?: string, ): Promise { const target = await ctx.fs.resolve(args.path, { signal }) const info = await ctx.fs.stat(target, signal) if (!info) throw new Error(`路径不存在: ${args.path}`) const files: { name: string; target: Awaited> }[] = [] const pathInfo = ctx.fs.processPath(target) if (info.type === 'file') { if (!hasSupportedExt(pathInfo)) { throw new Error(`不是支持的发票文件(支持 pdf/jpg/png): ${args.path}`) } files.push({ name: pathInfo.split('/').pop() ?? pathInfo, target }) } else { await collectFiles(ctx, target, signal, 0, files) } const parsed: (InvoiceData & { path: string })[] = [] const skipped: SkippedFile[] = [] let checksFailed = 0 const scope = cacheScope(sessionId) for (const file of files) { const absPath = ctx.fs.processPath(file.target) let bytes: Uint8Array try { bytes = await ctx.fs.readBytes(file.target, signal, MAX_BYTES) } catch (error) { skipped.push({ path: absPath, file: file.name, reason: 'unparsable', detail: `读取失败: ${error instanceof Error ? error.message : String(error)}` }) continue } const r = parseOne(ctx, absPath, file.name, bytes) if (r.skipped) { skipped.push(r.skipped) continue } const invoice = r.invoice! invoice.checks = validateInvoice(invoice) if (!invoice.checks.every((c) => c.ok)) checksFailed += 1 parseCache.set(`${scope}:${absPath}`, invoice) parsed.push({ ...invoice, path: absPath }) } const amount = parsed.reduce((acc, p) => acc + p.amount, 0) const tax = parsed.reduce((acc, p) => acc + p.tax, 0) const total = parsed.reduce((acc, p) => acc + p.total, 0) return { inputCount: files.length, parsed, skipped, summary: { parsedCount: parsed.length, skippedCount: skipped.length, amount, tax, total, checksFailed, }, } } /** 核对表渲染(会话内表格)。 */ export function renderParseResult(result: InvoiceParseResult): string { const lines: string[] = [] lines.push('## 发票解析结果核对表') lines.push('') lines.push(`共扫描 **${result.inputCount}** 个文件:解析成功 **${result.summary.parsedCount}**,跳过 **${result.summary.skippedCount}**。`) lines.push('') if (result.parsed.length > 0) { lines.push('| 源文件 | 发票号码 | 发票代码 | 开票日期 | 金额 | 税额 | 价税合计 | 来源 | 置信度 | 勾稽 | 缺失字段 |') lines.push('| --- | --- | --- | --- | ---: | ---: | ---: | --- | --- | --- | --- |') for (const inv of result.parsed) { const missing = inv.source.missing.length > 0 ? inv.source.missing.join('、') : '—' const recon = inv.checks.find((c) => c.label.startsWith('勾稽')) const reconCell = recon === undefined ? '—' : recon.ok ? '✓' : `⚠ ${recon.detail}` const confLabel = inv.source.confidence === 'high' ? '高(XML)' : inv.source.confidence === 'medium' ? '中(正则)' : `低(缺:${missing})` const methodLabel = inv.source.method === 'xml' ? 'XML' : inv.source.method === 'mixed' ? 'XML+文本' : '文本正则' lines.push( `| ${inv.source.file} | ${inv.invoiceNumber} | ${inv.invoiceCode || '—'} | ${inv.issueDate || '—'} | ${inv.amount.toFixed(2)} | ${inv.tax.toFixed(2)} | ${inv.total.toFixed(2)} | ${methodLabel} | ${confLabel} | ${reconCell} | ${missing} |`, ) } lines.push('') lines.push(`本批合计:金额 **¥${result.summary.amount.toFixed(2)}**,税额 **¥${result.summary.tax.toFixed(2)}**,价税合计 **¥${result.summary.total.toFixed(2)}**(勾稽失败 ${result.summary.checksFailed} 张,见上表 ⚠)。`) } if (result.skipped.length > 0) { lines.push('') lines.push('### 跳过清单') lines.push('') lines.push('| 源文件 | 跳过原因 | 说明 |') lines.push('| --- | --- | --- |') for (const s of result.skipped) lines.push(`| ${s.file} | ${s.reason} | ${s.detail ?? ''} |`) } return lines.join('\n') } /** 定义 invoice_parse 工具。 */ export function invoiceParseTool(ctx: Context) { return defineTool({ name: 'invoice_parse', description: '解析工作区内的发票文件(PDF 或目录,自动识别 pdf/jpg/png):优先读取 PDF 内嵌结构化 XML(发票号码/代码、金额、税额、价税合计、购买方、销售方、开票日期),无 XML 时用文本层正则抽取;输出结构化 JSON 并渲染"抽取结果核对表"(含置信度与金额勾稽校验)。纯图片/加密 PDF 返回跳过原因,不中断批量。发票数据仅本地流转,不发起任何查验请求。', parameters: { path: { type: 'string', required: true, description: '发票文件路径或目录(目录将递归扫描 pdf/jpg/png)', }, }, output: { schema: { type: 'object', additionalProperties: false, properties: { inputCount: { type: 'integer' }, parsed: { type: 'array', items: { type: 'json' } }, skipped: { type: 'array', items: { type: 'json' } }, summary: { type: 'object', additionalProperties: true, properties: {} }, }, }, render: (_args, value: any) => [{ type: 'text', text: renderParseResult(value as InvoiceParseResult) }], presentationMeta: (_args, value: any) => ({ kind: 'invoice-parse', title: `解析 ${value.summary.parsedCount} 张发票${value.summary.checksFailed > 0 ? `(⚠${value.summary.checksFailed} 张勾稽失败)` : ''}`, parsedCount: value.summary.parsedCount, skippedCount: value.summary.skippedCount, total: value.summary.total, checksFailed: value.summary.checksFailed, }), }, async execute(args, exec) { // schema 推断出的输出类型与业务类型形状不同,桥接返回(运行时数据本身就是 JSON 可序列化结构) // 会话维度:exec.agent.id 即会话 id(由代理循环设置);拿不到时回退 global(进程级缓存) const sessionId = (exec as unknown as { agent?: { id?: string } } | undefined)?.agent?.id return runInvoiceParse(ctx, args, exec?.signal, sessionId) as any }, }) }