import { createHash } from 'node:crypto'; import { createRequire } from 'node:module'; import { readFile, readdir, lstat } from 'node:fs/promises'; import type { Dirent } from 'node:fs'; import { dirname, join, relative, resolve, sep } from 'node:path'; import { pathContains } from '../../../src/plugin-sdk.js'; import { moduleImports, packageName, resolveRelativeModule } from './moduleResolution.js'; /** * 宿主引擎自身的 npm 包名(`package.json::name`)。硬编码、人工同步,**不**在 * 这里动态读 `package.json`:这个文件会被绿色版 `bun --compile` 编译进单文件 * exe,届时 `import.meta.url` 变成虚拟路径——用相对路径去定位磁盘上的 * `package.json` 会复现 CLAUDE.md 反复警告过的那类绿色版地雷。改包名时要与 * `scriptGuard.mjs::HOST_PACKAGE_NAME` 一起改。 */ const HOST_PACKAGE_NAME = 'minimal-agent'; async function packageVersion(entry: string, name: string): Promise { let cursor = dirname(entry); for (;;) { const manifest = join(cursor, 'package.json'); try { const value = JSON.parse(await readFile(manifest, 'utf8')) as { name?: string; version?: string; }; if (value.name === name && value.version) return value.version; } catch { // continue upwards } const parent = dirname(cursor); if (parent === cursor) break; cursor = parent; } return 'unknown'; } /** Fingerprint executable ESM graph, prompts/assets, and declared package versions. */ export async function workflowFingerprint( source: string, dir: string, packages: string[] = [], ): Promise { // Older journals may hold truncated human replies or direct tool receipts // obtained without today's host capability checks. Never replay those. const hash = createHash('sha256').update('workflow-bundle-v2-host-catalog-4\0'); const entry = join(dir, 'workflow.mjs'); const seen = new Set(); const importedPackages = new Set(); async function addModule(path: string, knownSource?: string): Promise { const absolute = resolve(path); if (!pathContains(dir, absolute)) { throw new Error(`工作流相对模块越出工作流目录:${absolute}`); } if (seen.has(absolute)) return; seen.add(absolute); const text = knownSource ?? (await readFile(absolute, 'utf8')); const name = relative(dir, absolute).split(sep).join('/'); hash.update(JSON.stringify(['module', name, Buffer.byteLength(text)])).update(text); for (const specifier of moduleImports(text)) { if (specifier.startsWith('.')) { await addModule(await resolveRelativeModule(absolute, specifier)); } else if (specifier.startsWith('node:')) { continue; } else if (specifier.startsWith('/') || specifier.startsWith('file:')) { throw new Error(`工作流 ESM import 不得使用绝对路径:${specifier}`); } else if (packageName(specifier) === HOST_PACKAGE_NAME) { // 第二道闸,对齐 scriptGuard.mjs 的同名检查:包自引用 + // package.json::exports 的 "./src/*"/"./plugins/*" 通配符会让 // `minimal-agent/src/xxx` 解析到真实内核文件,完全绕开 wf 分组能力 // 对象。声明进 meta.packages 也无法绕过这条——即使调用顺序以后变了、 // discovery.ts 没能先跑 scriptGuard 校验,这里仍然拦得住。 throw new Error( `工作流禁止 import 宿主引擎自身(${specifier}):一切对内核的访问必须经 wf 分组能力对象。`, ); } else { importedPackages.add(packageName(specifier)); } } } await addModule(entry, source); async function visit(relativeDir: string): Promise { let entries: Dirent[]; try { if ((await lstat(join(dir, relativeDir))).isSymbolicLink()) throw new Error(`工作流随包资源不能是符号链接:${relativeDir}`); entries = await readdir(join(dir, relativeDir), { withFileTypes: true }); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error; } for (const item of entries.sort((a, b) => a.name.localeCompare(b.name))) { const name = `${relativeDir}/${item.name}`; if (item.isSymbolicLink()) throw new Error(`工作流随包资源不能是符号链接:${name}`); if (item.isDirectory()) await visit(name); else if (item.isFile() && !seen.has(resolve(dir, name))) { const bytes = await readFile(join(dir, name)); hash.update(JSON.stringify(['resource', name, bytes.length])).update(bytes); } } } for (const folder of ['prompts', 'scripts', 'assets']) await visit(folder); const require = createRequire(entry); for (const name of importedPackages) { if (!packages.includes(name)) { throw new Error(`运行时包 ${name} 必须声明在 meta.packages 中。`); } } for (const name of [...packages].sort()) { let resolved: string; try { resolved = require.resolve(name); } catch (error) { throw new Error(`无法解析 meta.packages 中的 ${name}:${error instanceof Error ? error.message : String(error)}`); } hash.update(JSON.stringify(['package', name, await packageVersion(resolved, name)])); } return hash.digest('hex').slice(0, 16); }