import { createHash } from 'node:crypto'; import { createReadStream } from 'node:fs'; import { chmod, copyFile, mkdir, readdir, readlink, stat, } from 'node:fs/promises'; import { homedir } from 'node:os'; import { basename, join, resolve } from 'node:path'; import { agentStateDir } from '../../../src/context/agentHome.js'; import type { InvocationResource } from '../../../src/plugin-sdk.js'; import type { InputDef } from './types.js'; const MIME_BY_EXT: Record = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.heic': 'image/heic', '.heif': 'image/heif', '.gif': 'image/gif', '.bmp': 'image/bmp', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword', '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.xls': 'application/vnd.ms-excel', '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.ppt': 'application/vnd.ms-powerpoint', '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', '.zip': 'application/zip', '.txt': 'text/plain', '.md': 'text/markdown', '.csv': 'text/csv', '.json': 'application/json', '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.mkv': 'video/x-matroska', }; function mimeForPath(path: string): string { const match = /\.[^.]+$/.exec(path.toLowerCase()); return (match && MIME_BY_EXT[match[0]]) || 'application/octet-stream'; } function mimeMatches(mime: string, accepted: string): boolean { const a = accepted.toLowerCase(); return a.endsWith('/*') ? mime.toLowerCase().startsWith(a.slice(0, -1)) : mime.toLowerCase() === a; } function compatible(resource: InvocationResource, def: InputDef): boolean { if (resource.kind === 'directory' && def.allowDirectory === false) return false; if (resource.kind === 'file' && def.allowFile === false) return false; if ( def.accepts?.length && resource.kind === 'file' && !def.accepts.some((a) => { const accepted = a.toLowerCase(); const ext = resource.name.toLowerCase().match(/\.[^.]+$/)?.[0]; return mimeMatches(resource.mime, accepted) || accepted === ext; }) ) return false; return true; } function resourceId(path: string): string { return `path-${createHash('sha256').update(resolve(path)).digest('hex').slice(0, 24)}`; } async function contentHash(path: string): Promise { const hash = createHash('sha256'); for await (const chunk of createReadStream(path)) hash.update(chunk); return hash.digest('hex'); } async function directoryContentHash(root: string): Promise { const hash = createHash('sha256'); const visit = async (dir: string, prefix: string): Promise => { const entries = await readdir(dir, { withFileTypes: true }); entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); for (const entry of entries) { const relative = prefix ? `${prefix}/${entry.name}` : entry.name; const fullPath = join(dir, entry.name); if (entry.isDirectory()) { hash.update(`d\0${relative}\0`); await visit(fullPath, relative); } else if (entry.isFile()) { hash.update(`f\0${relative}\0${await contentHash(fullPath)}\0`); } else if (entry.isSymbolicLink()) { hash.update(`l\0${relative}\0${await readlink(fullPath)}\0`); } else { // Keep uncommon filesystem entries deterministic without opening them. const info = await stat(fullPath); hash.update(`o\0${relative}\0${info.mode}\0${info.size}\0`); } } }; await visit(root, ''); return hash.digest('hex'); } function safeSegment(value: string): string { return value.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 120) || 'default'; } function safeFileName(value: string, fallback: string): string { return ( [...basename(value)] .map((ch) => ch.codePointAt(0)! < 32 || '<>:"|?*/\\'.includes(ch) ? '_' : ch, ) .join('') .slice(0, 180) || fallback ); } function stagedFilePath( dir: string, resource: InvocationResource, index: number, ): string { const safe = safeFileName(resource.name, `input-${index + 1}`); return join(dir, `${String(index + 1).padStart(3, '0')}-${safe}`); } function resolveInputPath(value: string, cwd: string): string { if (value === '~') return homedir(); if (value.startsWith('~/') || value.startsWith('~\\')) { return resolve(homedir(), value.slice(2)); } return resolve(cwd, value); } async function resourceFromPath( value: string, cwd: string, ): Promise { const localPath = resolveInputPath(value, cwd); const info = await stat(localPath); const kind = info.isDirectory() ? 'directory' : 'file'; const sha256 = kind === 'file' ? await contentHash(localPath) : await directoryContentHash(localPath); return { id: resourceId(localPath), origin: 'path', name: basename(localPath), mime: kind === 'directory' ? 'inode/directory' : mimeForPath(localPath), size: kind === 'file' ? info.size : undefined, sha256, localPath, kind, }; } /** Stage attachment files in a deterministic, private directory for legacy path APIs. */ export async function materializeResources( workflowName: string, sessionId: string, inputName: string, resources: readonly InvocationResource[], ): Promise { // This staging area contains files only. Never report a successful partial // materialization if a caller passes a directory. if (resources.some(resource => resource.kind !== 'file')) throw new Error('不能将目录附件作为文件物化;请单独绑定目录路径'); const fingerprint = createHash('sha256') .update( resources .map((r) => `${r.sha256 ?? r.id}:${r.name}:${r.size ?? ''}`) .join('|'), ) .digest('hex') .slice(0, 24); const dir = join( agentStateDir(), 'workflow-inputs', safeSegment(workflowName), safeSegment(sessionId), safeSegment(inputName), fingerprint, ); await mkdir(dir, { recursive: true, mode: 0o700 }); for (let i = 0; i < resources.length; i++) { const source = resources[i]; const target = stagedFilePath(dir, source, i); try { await stat(target); continue; } catch { // First materialization for this content fingerprint. } await copyFile(source.localPath, target); await chmod(target, 0o400); } return dir; } export interface BoundResourceInputs { inputs: Record; resourceMap: Record; resourceIdentity: string[]; warnings: string[]; } /** Bind explicit paths first, then compatible current-turn attachments. */ export async function bindResourceInputs(opts: { workflowName: string; sessionId: string; rawInputs: Record; cwd?: string; defs?: InputDef[]; attachments?: readonly InvocationResource[]; }): Promise { const inputs: Record = { ...opts.rawInputs }; const resourceMap: Record = {}; const resourceIdentity: string[] = []; const warnings: string[] = []; for (const def of opts.defs ?? []) { if (def.type !== 'resource') continue; const explicit = opts.rawInputs[def.name]; if (explicit?.trim()) { const resource = await resourceFromPath( explicit, opts.cwd ?? process.cwd(), ); const stageAsDirectory = def.materialize === 'directory' && resource.kind === 'file'; const accepted = stageAsDirectory ? compatible(resource, { ...def, allowFile: true }) : compatible(resource, def); if (!accepted) throw new Error(`input ${def.name} 的路径类型不受支持:${explicit}`); resourceMap[def.name] = [resource]; inputs[def.name] = stageAsDirectory ? await materializeResources( opts.workflowName, opts.sessionId, def.name, [resource], ) : resource.localPath; resourceIdentity.push( def.identity === 'reference' ? `${def.name}:${resource.id}` : `${def.name}:${resource.sha256 ?? resource.id}`, ); continue; } if (!def.attachmentFallback) continue; const matches = (opts.attachments ?? []).filter((resource) => def.materialize === 'directory' && resource.kind === 'file' ? compatible(resource, { ...def, allowFile: true }) : compatible(resource, def), ); if (!matches.length) continue; if (def.maxItems !== undefined && matches.length > def.maxItems) { throw new Error( `input ${def.name} 最多允许 ${def.maxItems} 个附件,但本轮有 ${matches.length} 个兼容附件;请减少附件或调整 maxItems`, ); } if (def.multiple !== true && matches.length > 1) { throw new Error( `input ${def.name} 只允许一个附件,但本轮有 ${matches.length} 个兼容附件;请使用 --input ${def.name}=路径 或声明 multiple: true`, ); } const directory = matches.find(resource => resource.kind === 'directory'); if (directory) { if (matches.length !== 1) throw new Error(`input ${def.name} 不能合并多个目录或混合目录与文件附件;请指定一个目录,或仅附加文件`); const path = resolve(opts.cwd ?? process.cwd(), directory.localPath); if (!(await stat(path)).isDirectory()) throw new Error(`input ${def.name} 的目录附件不是目录:${directory.name}`); const identity = def.identity === 'reference' ? directory.id : directory.sha256 ?? await directoryContentHash(path); resourceMap[def.name] = [directory]; inputs[def.name] = path; // Never replay an older receipt for a silently empty staging directory. resourceIdentity.push(`${def.name}:directory:${identity}`); warnings.push(`已将本轮目录附件绑定到 input ${def.name}`); continue; } resourceMap[def.name] = matches; for (const resource of matches) { resourceIdentity.push( def.identity === 'reference' ? `${def.name}:${resource.id}` : `${def.name}:${resource.sha256 ?? resource.id}`, ); } const staged = await materializeResources( opts.workflowName, opts.sessionId, def.name, matches, ); // Host attachment paths can be temporary (notably team deliveries), so // even a single file must use the stable Runner copy for journal resume. inputs[def.name] = matches.length === 1 && def.materialize !== 'directory' ? stagedFilePath(staged, matches[0], 0) : staged; warnings.push(`已将本轮 ${matches.length} 个附件绑定到 input ${def.name}`); } return { inputs, resourceMap, resourceIdentity, warnings }; }