/** Trusted ESM workflow module loader. This is an execution environment, not a security sandbox. */ import { createHash, randomUUID } from 'node:crypto'; import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'; import { createRequire } from 'node:module'; import { tmpdir } from 'node:os'; import { dirname, extname, join, relative, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { pathContains } from '../../../src/plugin-sdk.js'; import { STATIC_IMPORT, resolveRelativeModule } from './moduleResolution.js'; import type { WorkflowScript } from './types.js'; export class WorkflowScriptError extends Error { readonly workflowOutcome?: string; constructor( message: string, readonly workflowName: string, readonly scriptPath: string, readonly cause?: unknown, workflowOutcome?: string, ) { super(message); this.name = 'WorkflowScriptError'; this.workflowOutcome = workflowOutcome ?? readWorkflowOutcome(cause); } } function readWorkflowOutcome(value: unknown): string | undefined { let current = value; for (let depth = 0; depth < 8 && current && typeof current === 'object'; depth++) { const outcome = (current as { workflowOutcome?: unknown }).workflowOutcome; if (typeof outcome === 'string' && outcome.trim()) return outcome.trim(); current = (current as { cause?: unknown }).cause; } return undefined; } interface WorkflowModule { default?: (context: unknown) => unknown | Promise; meta?: unknown; } /** * Bun deliberately caches file modules by physical path and ignores URL query strings. * Materialize the executable graph at a content-addressed physical path so changing a * workflow cannot execute a stale module. Bare packages are resolved from the original * workflow location and rewritten to file URLs; relative modules remain a native ESM graph. * * ⚠️ 裸包名是否声明在 `meta.packages` 里,这里**不重复校验**——那是 * `workflowFingerprint.ts` 的职责,`workflowDependencies.ts::resolveWorkflowBundle` * 保证指纹计算总是先于本函数执行,所以未声明的包在到达这里之前就已经被拒绝。 * 这个调用顺序一旦改变,要在这里补上同样的校验,不要假设它仍然成立。 */ async function materializeModuleGraph( script: WorkflowScript, bundleHash: string, ): Promise { const sourceIdentity = createHash('sha256') .update(resolve(script.dir)) .digest('hex') .slice(0, 16); const cacheRoot = join( tmpdir(), 'minimal-agent-workflow-esm-v2', sourceIdentity, bundleHash, ); const entry = resolve(script.scriptPath); const seen = new Set(); const requireFromEntry = createRequire(entry); async function copyModule(path: string, knownSource?: string): Promise { const absolute = resolve(path); if (!pathContains(script.dir, absolute)) { throw new Error(`工作流相对模块越出工作流目录:${absolute}`); } if (seen.has(absolute)) return; seen.add(absolute); const destination = join(cacheRoot, relative(script.dir, absolute)); await mkdir(dirname(destination), { recursive: true }); const original = knownSource ?? (await readFile(absolute, 'utf8')); if (extname(absolute).toLowerCase() === '.json') { const temporary = `${destination}.tmp-${process.pid}-${randomUUID()}`; try { await writeFile(temporary, original, 'utf8'); await rename(temporary, destination).catch(async (error) => { const code = (error as NodeJS.ErrnoException).code; // 内容寻址:目标一旦存在必然与本次要写的字节相同(同一份 knownSource/hash)。 // POSIX 覆盖式 rename 是原子操作,只会报 EEXIST;Windows 上并发 rename 到 // 同一目标可能因瞬时占用报 EPERM/EBUSY 而不是 EEXIST——都容忍,重新 // stat 一次确认目标确实已由并发的另一次调用写入,不是的话照原样抛出。 if (code !== 'EEXIST' && code !== 'EPERM' && code !== 'EBUSY') throw error; await stat(destination); }); } finally { await rm(temporary, { force: true }).catch(() => undefined); } return; } const dependencies: Promise[] = []; const rewritten = original.replace( STATIC_IMPORT, (whole, prefix: string, specifier: string, suffix: string) => { if (specifier.startsWith('node:')) return whole; if (specifier.startsWith('.')) { dependencies.push( resolveRelativeModule(absolute, specifier).then((dependency) => copyModule(dependency), ), ); return whole; } const resolvedPackage = requireFromEntry.resolve(specifier); return `${prefix}${pathToFileURL(resolvedPackage).href}${suffix}`; }, ); await Promise.all(dependencies); const temporary = `${destination}.tmp-${process.pid}-${randomUUID()}`; try { await writeFile(temporary, rewritten, 'utf8'); await rename(temporary, destination).catch(async (error) => { // 同上:内容寻址下并发 rename 到同一目标是无害的,只是容错码在 Windows 上 // 不是 EEXIST。re-stat 确认目标真的已经落地,不是的话照原样抛出。 const code = (error as NodeJS.ErrnoException).code; if (code !== 'EEXIST' && code !== 'EPERM' && code !== 'EBUSY') throw error; await stat(destination); }); } finally { await rm(temporary, { force: true }).catch(() => undefined); } } await copyModule(entry, script.source); return join(cacheRoot, relative(script.dir, entry)); } export async function loadWorkflowModule( script: WorkflowScript, bundleHash: string, ): Promise { const materializedEntry = await materializeModuleGraph(script, bundleHash); const url = pathToFileURL(materializedEntry); let loaded: WorkflowModule; try { loaded = (await import(url.href)) as WorkflowModule; } catch (error) { throw new WorkflowScriptError( `工作流模块加载失败:${error instanceof Error ? error.message : String(error)}`, script.name, script.scriptPath, error, ); } if (typeof loaded.default !== 'function') { throw new WorkflowScriptError( '工作流必须 `export default async function run(wf) { ... }`', script.name, script.scriptPath, ); } return loaded; } export async function runScript( script: WorkflowScript, context: unknown, bundleHash: string, ): Promise { const module = await loadWorkflowModule(script, bundleHash); try { return await module.default!(context); } catch (error) { if (error instanceof Error && error.name === 'AbortError') throw error; throw new WorkflowScriptError( `工作流 "${script.name}" 执行失败:${error instanceof Error ? error.message : String(error)}`, script.name, script.scriptPath, error, ); } }