/** * ============================================================ * plugins/workflow-runner/src/runner.ts —— 一次工作流运行的编排 * ------------------------------------------------------------ * 串起:任务身份判定 → 账本装载 → 目标锚构造 → 组装 WorkflowContext → 执行 ESM → 收尾归档。 * * ⚠️ **为什么需要事件队列**:ESM 的 run(wf) 是一个普通 async 函数,它执行期间 * 没有任何机制能「yield 一个事件出去」;而宿主要的是一条实时事件流(否则 * 整条工作流跑完之前 UI 一片死寂)。所以 `wf` 上下文把事件推进队列,本函数 * 作为 async generator 一边 await 脚本的 promise、一边把队列排空往外 yield。 * ============================================================ */ import { resolve } from 'node:path'; import { randomUUID } from 'node:crypto'; import { isWorkflowMilestone, projectWorkflowProgress, workflowOutcomeLabel } from '../../../src/runtime/workflowPresentation.js'; import type { LoopEvent } from '../../../src/plugin-sdk.js'; import { ExecutionScope, createWorkflowContext } from './runtime/context.js'; import { buildGoalAnchor } from './goalAnchor.js'; import { coerceInputs } from './inputCoercion.js'; import { Journal, fingerprint } from './journal.js'; import { bindResourceInputs } from './resourceInputs.js'; import { WorkflowScriptError, runScript } from './sandbox.js'; import { DEFAULT_SESSION_ID, buildTaskArbitrator, sanitizeWorkflowDirName, } from './taskIdentity.js'; import { authorizeScriptTool, buildWorkflowToolContext, effectiveWorkflowCwd, workflowExecutor } from './toolRuntime.js'; import type { RunContext, WorkflowScript } from './types.js'; import { type WorkflowBundle, resolveWorkflowBundle, } from './workflowDependencies.js'; import { WorkflowState } from './workflowState.js'; const WF_PLUGIN_ID = 'workflow-runner'; /** 事件队列:生产者随时 push,消费者按序 async 迭代,close 后排空即结束。 */ class EventQueue { private items: T[] = []; private waiter: (() => void) | null = null; private closed = false; push(item: T): void { this.items.push(item); this.waiter?.(); this.waiter = null; } close(): void { this.closed = true; this.waiter?.(); this.waiter = null; } async *drain(): AsyncGenerator { while (true) { while (this.items.length > 0) { yield this.items.shift() as T; } if (this.closed) return; await new Promise((resolve) => { this.waiter = resolve; }); } } } export interface RunWorkflowOptions { ctx: RunContext; inputs: Record; sessionId?: string; } export interface WorkflowCallResult { workflow: string; runId: string; result: unknown; artifacts: string[]; } interface ExecutionOptions extends RunWorkflowOptions { bundle: WorkflowBundle; scope: ExecutionScope; parentStateDir?: string; taskId?: string; runId: string; parentRunId?: string; depth: number; } /** 执行一个代码形态工作流,产出 LoopEvent 流。 */ export async function* runWorkflowScript( script: WorkflowScript, opts: RunWorkflowOptions, ): AsyncGenerator { try { const bundle = await resolveWorkflowBundle( script, effectiveWorkflowCwd(opts.ctx), ); opts.ctx.resourceLedger ??= { inputTokens: 0, outputTokens: 0, limit: null, trustworthy: true, }; const scope = new ExecutionScope(); const lease = await scope.scheduler.acquire('root', scope.rootRunId, opts.ctx.signal); try { yield* executeWorkflowScript(script, { ...opts, bundle, scope, runId: scope.rootRunId, depth: 0, }); } finally { lease.release(); } } catch (error) { if ( opts.ctx.signal?.aborted || (error instanceof Error && error.name === 'AbortError') ) yield { type: 'interrupted' }; else yield { type: 'error', error: error instanceof Error ? error.message : String(error), }; } } /** Same executor for roots and children. Only roots emit terminal host events. */ async function* executeWorkflowScript( script: WorkflowScript, opts: ExecutionOptions, ): AsyncGenerator< LoopEvent, (WorkflowCallResult & { reused: boolean }) | undefined, void > { const { ctx, inputs } = opts; ctx.signal?.throwIfAborted(); const sessionId = sanitizeWorkflowDirName( opts.sessionId ?? ctx.runtimeContext?.sessionId ?? DEFAULT_SESSION_ID, ); const scriptHash = opts.bundle.hash; const state = new WorkflowState( effectiveWorkflowCwd(ctx), script.name, sessionId, script.meta.inputs, opts.taskId ?? ctx.managedExecution?.runId ?? ctx.executionId, opts.parentStateDir, ); const arbitrationNotes: string[] = []; const resume = await state.init( inputs, scriptHash, script.meta.artifacts ?? [], ctx.managedExecution || ctx.executionId || opts.parentStateDir ? undefined : buildTaskArbitrator({ provider: ctx.provider, chat: ctx.chat, executeTool: ctx.tools.some(tool => tool.name === 'AskUserQuestion') ? async (name, raw, signal) => { const built = buildWorkflowToolContext(ctx, `wf-arbitrate-${randomUUID()}`, () => undefined); if ('error' in built) throw new Error(built.error); await authorizeScriptTool(ctx, name, raw, built, signal); return workflowExecutor(ctx)(name, raw, signal, built); } : undefined, signal: ctx.signal, notes: arbitrationNotes, }), ); for (const note of arbitrationNotes) { yield { type: 'warning', message: note }; } // 已完成:报实际产物,不重跑。 if (resume.mode === 'completed') { const restoredEvent = { type: 'workflow_progress', workflow: script.name, runId: opts.runId, rootRunId: opts.scope.rootRunId, ...(opts.parentRunId ? { parentRunId: opts.parentRunId } : {}), depth: opts.depth, phase: 'workflow', status: 'complete', message: '恢复已完成结果', } as const; await state.appendEvent(restoredEvent); yield restoredEvent; const list = resume.artifacts?.length ? resume.artifacts.map((a) => ` · ${a}`).join('\n') : ' (本次运行没有声明产物)'; yield { type: 'text', ...(!opts.parentStateDir ? { commandResult: true as const } : {}), delta: `工作流「${script.name}」的这个目标此前已完成,产物:\n${list}\n换个目标即可重新执行。\n`, }; if (!opts.parentStateDir) { if (ctx.presentArtifacts && !ctx.managedBridge) yield* ctx.presentArtifacts((resume.artifacts ?? []).map(p => resolve(state.workingDir, p))); yield { type: 'turn_done' }; } return { workflow: script.name, runId: opts.runId, result: await state.readResult(), artifacts: (resume.artifacts ?? []).map((p) => resolve(state.workingDir, p), ), reused: true, }; } if (resume.scriptChanged) { yield { type: 'warning', message: `⚠ 工作流「${script.name}」的脚本/依赖已改变或产物/返回值缺失 —— 旧断点作废,本次全新开始。`, }; } if (resume.archivedTo) { yield { type: 'warning', message: `旧产物已归档到 ${resume.archivedTo}(不是删除,需要时可取回)。`, }; } // 目标锚:仲裁判定的延续要锚**旧目标**,本次输入降级成补充要求。 ctx.goalAnchor = ctx.managedExecution ? ctx.managedExecution.anchor : resume.prevGoal ? buildGoalAnchor({ goal: resume.prevGoal }, script.meta.inputs) : buildGoalAnchor(inputs, script.meta.inputs); ctx.goalSupplements = await state.readSupplements(); ctx.declaredArtifacts = new Set(script.meta.artifacts ?? []); const journal = new Journal(state.journalPath, { bundleHash: scriptHash, rootRunId: opts.scope.rootRunId, }); await journal.load(script.meta.resumeBackoff ?? 0); if (resume.mode === 'resume') { yield { type: 'warning', message: `↻ 续跑工作流「${script.name}」(上次已完成 ${journal.loadedCount} 次调用` + `${resume.lastError ? `,上次失败于:${resume.lastError}` : ''})。`, }; } const queue = new EventQueue(); const workflowContext = createWorkflowContext({ ctx, state, journal, emit: (ev) => queue.push(ev), args: inputs, workflowName: script.name, runId: opts.runId, parentRunId: opts.parentRunId, depth: opts.depth, session: sessionId, task: state.taskId, workflowDir: script.dir, inputResourceMap: ctx.inputResourceMap, scope: opts.scope, invokeWorkflow: async (name, rawInputs, site, label) => { const bundle = opts.bundle.children.get(name); if (!bundle) throw new Error(`子工作流 ${name} 未声明在 meta.dependencies 中`); const bound = await bindResourceInputs({ workflowName: name, sessionId, cwd: effectiveWorkflowCwd(ctx), rawInputs: rawInputs as Record, defs: bundle.script.meta.inputs, attachments: [], }); const childInputs = coerceInputs( bound.inputs as Record, bundle.script.meta.inputs, ); if (bound.resourceIdentity.length) childInputs.__resource_fingerprint = bound.resourceIdentity.join('|'); const taskId = fingerprint('child-instance-v1', { parent: [script.name, state.taskId], site, name, inputs: childInputs, }); const childRunId = fingerprint('child-run-v2', { rootRunId: opts.scope.rootRunId, parentRunId: opts.runId, site, taskId, }); const childCtx: RunContext = { ...ctx, cwd: effectiveWorkflowCwd(ctx), history: structuredClone( ctx.history.filter((m) => m.role === 'system'), ), sessionState: ctx.sessionState ? structuredClone(ctx.sessionState) : undefined, goal: undefined, goalAnchor: undefined, goalSupplements: undefined, declaredArtifacts: undefined, transientContext: undefined, transientBundle: undefined, managedExecution: undefined, managedBridge: undefined, usageRecorder: ctx.usageRecorder ?? ctx.managedBridge?.recordUsage?.bind(ctx.managedBridge), inputResources: Object.values(bound.resourceMap).flat(), inputResourceMap: bound.resourceMap, }; const prefix = `${script.name} → ${label ?? name}`; await state.appendProgress(`▶ 子流程 ${prefix} (${site}, ${taskId})`); const run = executeWorkflowScript(bundle.script, { ctx: childCtx, inputs: childInputs, sessionId, bundle, scope: opts.scope, parentStateDir: state.dir, taskId, runId: childRunId, parentRunId: opts.runId, depth: opts.depth + 1, }); try { while (true) { const next = await run.next(); if (next.done) { if (!next.value) throw new Error(`子工作流 ${name} 未返回执行结果`); const { reused, ...value } = next.value; await state.appendProgress( `✓ 子流程 ${prefix} (${reused ? '复用' : '执行完成'})`, ); return { value, reused }; } const ev = next.value; if ( ev.type === 'plugin_progress' || ev.type === 'warning' || ev.type === 'text' || ev.type === 'assistant_message' ) { const message = ev.type === 'text' ? ev.delta : ev.type === 'assistant_message' ? typeof ev.message.content === 'string' ? ev.message.content : JSON.stringify(ev.message.content) : ev.message; queue.push({ type: 'plugin_progress', pluginId: WF_PLUGIN_ID, message: `[${prefix}] ${message}`, }); } else if ( ev.type !== 'turn_done' && ev.type !== 'interrupted' && ev.type !== 'error' ) queue.push(ev); } } catch (error) { await state.appendProgress(`✗ 子流程 ${prefix}: ${String(error)}`); throw error; } }, }); if (resume.supplementaryGoal) { await ((workflowContext as any).state.addGoalSupplement as (t: string) => Promise)( resume.supplementaryGoal, ); } const startEvent = { type: 'workflow_progress', workflow: script.name, runId: opts.runId, rootRunId: opts.scope.rootRunId, ...(opts.parentRunId ? { parentRunId: opts.parentRunId } : {}), depth: opts.depth, phase: 'workflow', status: 'start', message: `开始 ${script.name}`, } as const; await state.appendEvent(startEvent); yield startEvent; let presentation = projectWorkflowProgress(null, startEvent); let lastStageKey = ''; const snapshot = (event: Extract): Extract => { presentation = projectWorkflowProgress(presentation, event); const message = { role: 'system' as const, _ephemeral: true as const, _uiProgress: true as const, id: `workflow:${opts.runId}`, timestamp: Date.now(), content: `${script.name} · ${workflowOutcomeLabel(presentation.outcome)}\n${presentation.milestones?.join('\n') ?? ''}`, workflowPresentation: presentation, }; ctx.history.push(message); return { type: 'injected_message', message }; }; let failure: unknown = null; let scriptResult: unknown; const done = runScript(script, workflowContext, scriptHash) .then(async (result) => { ctx.signal?.throwIfAborted(); scriptResult = await state.writeResult(result); }) .catch((e) => { failure = e; }) .finally(() => queue.close()); for await (const ev of queue.drain()) { if (ev.type === 'workflow_progress') presentation = projectWorkflowProgress(presentation, ev); if (ev.type === 'workflow_progress' && ev.runId === opts.runId && isWorkflowMilestone(ev)) { // Child stages are saved in the child's private history, not the host's. yield opts.parentStateDir ? ev : { ...ev, historyOwned: true }; const key = JSON.stringify([ev.phase, ev.message, ev.summary, ev.nextAction, ev.status, ev.current]); if (key !== lastStageKey) { lastStageKey = key; const message = { role: 'system' as const, _ephemeral: true as const, _uiProgress: true as const, // Resume can share runId after model history has been compacted. id: `workflow:${opts.runId}:stage:${randomUUID()}`, timestamp: Date.now(), content: [ev.message ?? ev.phase, ev.summary && `阶段结果:${ev.summary}`, ev.nextAction && `下一步:${ev.nextAction}`].filter(Boolean).join('\n\n'), }; ctx.history.push(message); yield { type: 'injected_message', message }; } } else yield ev; } await done; if (failure) { // 中断(用户 ESC)与脚本出错语义完全不同:前者保留现场可 resume。 if ( ctx.signal?.aborted || (failure instanceof Error && failure.name === 'AbortError') ) { await state.recordFailure('用户中断', [...(ctx.declaredArtifacts ?? [])]); await state.appendProgress('■ 用户中断'); const interruptedEvent = { type: 'workflow_progress', workflow: script.name, runId: opts.runId, rootRunId: opts.scope.rootRunId, depth: opts.depth, phase: 'workflow', status: 'warning', outcome: 'stopped', message: '用户中断,现场已保留', } as const; await state.appendEvent(interruptedEvent); yield opts.parentStateDir ? interruptedEvent : { ...interruptedEvent, historyOwned: true }; if (!opts.parentStateDir) yield snapshot(interruptedEvent); if (opts.parentStateDir) throw Object.assign(new Error('用户中断'), { name: 'AbortError' }); await ctx.managedBridge?.finish({ status: 'stopped', artifacts: [...(ctx.declaredArtifacts ?? [])], blocker: '用户停止,现场已保留', }); yield { type: 'interrupted' }; return; } const message = failure instanceof WorkflowScriptError ? failure.message : `工作流「${script.name}」执行失败:${ failure instanceof Error ? failure.message : String(failure) }`; // 工作流可以在 Error 上附带通用的 workflowOutcome。Runner 只透传这个 // 生命周期标签,不解释其业务含义。 const workflowOutcome = workflowOutcomeFromFailure(failure); await state.recordFailure(message, [...(ctx.declaredArtifacts ?? [])]); await state.appendProgress(`■ 失败:${message}`); const failureEvent = { type: 'workflow_progress', workflow: script.name, runId: opts.runId, rootRunId: opts.scope.rootRunId, ...(opts.parentRunId ? { parentRunId: opts.parentRunId } : {}), depth: opts.depth, phase: 'workflow', status: 'warning', outcome: workflowOutcome === 'budget_limited' || workflowOutcome === 'usage_limited' ? workflowOutcome : 'failed', message, } as const; await state.appendEvent(failureEvent); yield opts.parentStateDir ? failureEvent : { ...failureEvent, historyOwned: true }; if (!opts.parentStateDir) yield snapshot(failureEvent); if (opts.parentStateDir) throw failure; await ctx.managedBridge?.finish({ status: 'failed', artifacts: [...(ctx.declaredArtifacts ?? [])], blocker: message, ...(workflowOutcome ? { outcome: workflowOutcome } : {}), }); yield { type: 'error', error: message }; return; } // 把运行时经 declareArtifact() 登记的产物一并落盘 —— 只写 meta.artifacts // 的话,循环体里的逐迭代产物会静默丢失(见 markDone 的注释)。 await state.markDone([...(ctx.declaredArtifacts ?? [])]); await state.appendProgress( `✓ 完成(重放 ${journal.replayedCount} 次 / 上次账本 ${journal.loadedCount} 条)`, ); const completeEvent = { type: 'workflow_progress', workflow: script.name, runId: opts.runId, rootRunId: opts.scope.rootRunId, ...(opts.parentRunId ? { parentRunId: opts.parentRunId } : {}), depth: opts.depth, phase: 'workflow', status: 'complete', outcome: 'succeeded', message: '执行完成', } as const; await state.appendEvent(completeEvent); yield opts.parentStateDir ? completeEvent : { ...completeEvent, historyOwned: true }; if (!opts.parentStateDir) yield snapshot(completeEvent); await state.archive(); const artifacts = (await state.allArtifacts()).map((p) => resolve(state.workingDir, p), ); if (opts.parentStateDir) return { workflow: script.name, runId: opts.runId, result: scriptResult, artifacts, reused: false, }; const result = scriptResult && typeof scriptResult === 'object' ? (scriptResult as { evidence?: unknown }) : undefined; const evidence = Array.isArray(result?.evidence) ? result.evidence.map((item) => String(item)) : []; const finished = await ctx.managedBridge?.finish({ status: 'verified', artifacts, evidence, }); // ⚠️ 收尾状态必须过进程边界。传进去 'verified' 拿回来的很可能是 // 'ready_for_acceptance' —— 机器自检通过但还没人验收,这两者对宿主是天差地别。 // 就地丢弃会让 `-p --output-format json` 的宿主把「等待验收」读成「办完了」。 if (ctx.presentArtifacts && !ctx.managedBridge) yield* ctx.presentArtifacts(artifacts); yield { type: 'turn_done', ...managedStatusOf(finished) }; return { workflow: script.name, runId: opts.runId, result: scriptResult, artifacts, reused: false, }; } /** * Read the structured outcome after the ESM loader has wrapped a workflow * exception. The wrapper is deliberately treated as an implementation detail: * both its own field and a bounded `cause` chain are accepted so the * workflow → loader → runner path cannot silently downgrade budget_limited to * a generic failed result. */ export function workflowOutcomeFromFailure( failure: unknown, ): string | undefined { let current = failure; 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; } /** 从 bridge.finish 的返回值里取生命周期状态;拿不到就不带这个字段。 */ function managedStatusOf(finished: unknown): { managedStatus?: string } { const status = (finished as { status?: unknown } | undefined)?.status; return typeof status === 'string' ? { managedStatus: status } : {}; }