import { createHash } from 'node:crypto'; import { createReadStream } from 'node:fs'; import { realpath, stat } from 'node:fs/promises'; import { basename, extname, isAbsolute, relative, resolve, sep } from 'node:path'; import { z } from 'zod'; import { getWorkingDir } from '../../bootstrap/workingDir.js'; import { evaluateDeliveryGate } from '../../runtime/deliveryGate.js'; import type { DeliverableManifest, Tool, ToolCallContext, ToolResult } from '../../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; const MIME_BY_EXT: Record = { '.csv': 'text/csv', '.css': 'text/css', '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.gif': 'image/gif', '.html': 'text/html', '.js': 'text/javascript', '.jpeg': 'image/jpeg', '.jpg': 'image/jpeg', '.json': 'application/json', '.md': 'text/markdown', '.mp4': 'video/mp4', '.pdf': 'application/pdf', '.png': 'image/png', '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', '.py': 'text/x-python', '.svg': 'image/svg+xml', '.ts': 'text/typescript', '.tsx': 'text/typescript', '.txt': 'text/plain', '.webp': 'image/webp', '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.zip': 'application/zip', }; const verificationSchema = z.enum(['passed', 'failed', 'not_run']).default('not_run'); const inputSchema = z.object({ summary: z.string().max(2_000).optional().describe('交付结果的简短说明'), files: z.array(z.object({ path: z.string().min(1).describe('当前工作目录内要交付的原文件路径'), label: z.string().max(200).optional().describe('面向用户的显示名称'), verification: verificationSchema.optional(), })).max(50).optional(), links: z.array(z.object({ url: z.string().url().regex(/^https?:\/\//i).describe('HTTP(S) web URL'), title: z.string().max(300).optional(), })).max(20).optional(), }).refine((value) => (value.files?.length ?? 0) + (value.links?.length ?? 0) > 0, { message: '至少提交一个文件或网页链接', }); type PresentResultInput = z.infer; function isWithin(root: string, candidate: string): boolean { const rel = relative(root, candidate); return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)); } async function hashFile(path: string): Promise { const hash = createHash('sha256'); for await (const chunk of createReadStream(path)) hash.update(chunk); return hash.digest('hex'); } async function resolveDeliverable( root: string, entry: NonNullable[number], ): Promise { const lexical = resolve(root, entry.path); const real = await realpath(lexical); if (!isWithin(root, real)) throw new Error(`文件超出当前工作目录:${entry.path}`); const info = await stat(real); if (!info.isFile()) throw new Error(`交付目标不是文件:${entry.path}`); const relativePath = relative(root, real).split(sep).join('/'); const sha256 = await hashFile(real); const mime = MIME_BY_EXT[extname(relativePath).toLowerCase()] ?? 'application/octet-stream'; return { relativePath, sha256, mime, ...(entry.label ? { label: entry.label } : {}), size: info.size, modifiedAt: info.mtimeMs, verification: entry.verification ?? 'not_run', purpose: 'deliverable', }; } async function call(input: PresentResultInput, cwd = getWorkingDir(), ctx?: ToolCallContext): Promise { if (!input.files?.length && !input.links?.length) return { ok: false, error: '至少提交一个文件或网页链接' }; // Formal results use the same gate as the final text: while required // responsibility is open — or the ledger cannot be read reliably — nothing // is registered as a delivered result. Ordinary downloads and file writes are // still working steps and are not gated here. const deliveryId = ctx?.deliveryId ?? ctx?.userMessageId; if (ctx && deliveryId && !ctx.agentHandoff) { const gate = await evaluateDeliveryGate(ctx, deliveryId); if (gate.kind === 'pending') return { ok: false, error: `正式成果尚未提交:必要子任务尚未收口(${gate.tasks.map((task) => task.id).join('、')})。先等待或读取交接、接管并在 AgentResolve 收口,或如实报告缺口,之后再重新调用 PresentResult。`, }; if (gate.kind === 'unknown') return { ok: false, error: `正式成果尚未提交:无法确认子任务账本(${gate.reason})。先恢复账本可读性,不能声称结果已交付。`, }; } const lexicalRoot = resolve(cwd); const root = await realpath(lexicalRoot).catch(() => lexicalRoot); let files: DeliverableManifest['files']; try { files = await Promise.all((input.files ?? []).map((entry) => resolveDeliverable(root, entry))); } catch (error) { return { ok: false, error: `无法提交结果:${(error as Error).message}` }; } const links = (input.links ?? []).filter((link) => /^https?:\/\//i.test(link.url)); if (links.length !== (input.links ?? []).length) { return { ok: false, error: '网页结果只支持 http 或 https 链接' }; } const hasFailedFile = files.some((file) => file.verification === 'failed'); // `not_run` means no *additional* format/content validator was available. It // is not a failed delivery: this tool has already verified that the file exists, // is inside the workspace, and captured its size and SHA-256. Only an explicit // failed validator should turn an otherwise usable result into a warning. const status = hasFailedFile ? 'draft' : 'final'; const warnings = hasFailedFile ? ['至少一个文件未通过结构化验证。'] : []; const manifest: DeliverableManifest = { status, summary: input.summary?.trim() || (files.length ? `已提交 ${files.length} 个文件` : `已提交 ${links.length} 个网页结果`), files, ...(links.length ? { links } : {}), warnings, }; const names = files.map((file) => file.label || basename(file.relativePath)); return { ok: true, content: [ manifest.summary, ...names.map((name) => `- 文件:${name}`), ...links.map((link) => `- 网页:${link.title || link.url}`), '已生成结构化结果清单,交由宿主展示;这不是用户接收或独立验证的证明。', ].join('\n'), metadata: { kind: 'result_manifest', manifest }, }; } export const presentResultTool: Tool = { name: 'PresentResult', description: '交付真实文件或 HTTP(S) 链接;文件须在当前工作区。返回清单供宿主登记展示,不表示内容已独立验证;verification 只能按实际检查填写。', inputSchema, parameters: toToolParameters(inputSchema), isReadOnly: true, isConcurrencySafe: false, interruptBehavior: () => 'block', call: (input) => call(input), callWithContext: (input, _signal, context) => call(input, context.cwd, context), };