/** * ============================================================ * plugins/workflow-runner/src/index.ts —— /workflow 与 /workflows 的命令胶水 * ------------------------------------------------------------ * 工作流只有一种形态:`workflows//workflow.mjs`。 * * 这里曾有一段「找不到就回落到 legacy yaml 引擎」的迁移期分支,随 yaml 引擎 * 一起删除了 —— 现在找不到就是找不到,直接报错并让用户看 /workflows。 * ============================================================ */ import { existsSync } from 'node:fs'; import { resolve } from 'node:path'; import { managedCommandController } from '../../../src/managedExecution/registry.js'; import type { AgentRuntimeContext, ContextBundle, LoopEvent, Message, PluginContext, PromptCacheContext, Provider, SessionState, Tool, } from '../../../src/plugin-sdk.js'; import { refreshStableSystemPrompt } from '../../../src/plugin-sdk.js'; import { parseWorkflowArgs } from './commandArgs.js'; export { parseWorkflowArgs } from './commandArgs.js'; import { discoverWorkflows, lookupWorkflow } from './discovery.js'; import { coerceInputs } from './inputCoercion.js'; import { bindResourceInputs } from './resourceInputs.js'; import { runWorkflowScript } from './runner.js'; import { abandonWorkflowTask } from './workflowState.js'; import type { InputDef, RunContext } from './types.js'; export interface RunWorkflowFromCommandOptions { presentArtifacts?: PluginContext['presentArtifacts']; provider: Provider; runtimeContext?: AgentRuntimeContext; history: Message[]; signal?: AbortSignal; sessionState?: SessionState; cwd?: string; tools?: Tool[]; transientContext?: string; transientBundle?: ContextBundle; promptCache?: PromptCacheContext; executeTool?: PluginContext['executeTool']; toolContext?: RunContext['toolContext']; host?: PluginContext['host']; inputResources?: PluginContext['inputResources']; executionId?: PluginContext['executionId']; /** 传给外层控制器的不透明上下文;Workflow Runner 不解释。 */ managedContext?: unknown; } /** * 位置参数 → inputs 映射。 * **贪婪首参**(`inputs[0].greedy`):名后全部位置参数空格 join 进首参,不逐位拆。 * 存在理由是真实事故:不贪婪时用户打一句自然语言会被空格拆碎,第二段撞上 * number 类型的输入报「必须是数字」。 */ function mapPositional( rawInputs: Record, positional: string[], defs: InputDef[] | undefined, cwd = process.cwd(), ): string[] { const warnings: string[] = []; if (!defs || positional.length === 0) return warnings; if (defs[0]?.greedy === true) { const name = defs[0].name; if (defs[0].type === 'resource' && !(name in rawInputs)) { // A Desktop invocation commonly has a natural-language tail after the // command and no textual path. Do not mistake that tail for a file. const first = positional[0] ?? ''; const looksLikePath = existsSync(resolve(cwd, first)) || first.startsWith('/') || first.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(first) || first.startsWith('~/') || first.startsWith('~\\') || first.startsWith('./') || first.startsWith('.\\') || first.startsWith('../') || first.startsWith('..\\') || /\.[A-Za-z0-9]{1,16}$/.test(first); if (!looksLikePath) { if (positional.length) rawInputs.requestText = positional.join(' '); return warnings; } rawInputs[name] = first; if (positional.length > 1) rawInputs.requestText = positional.slice(1).join(' '); return warnings; } if (defs[0]?.type === 'resource' && name in rawInputs) { if (positional.length) rawInputs.requestText = positional.join(' '); return warnings; } if (name in rawInputs) { // 含空格的值没加引号会被 shell 拆开(只有第一段进 KV,其余散落成位置参数)。 // 静默丢弃曾把整段中文主题截成半句,连锁触发仲裁误判。这里拼回去并告警。 rawInputs[name] = [rawInputs[name], ...positional].join(' '); warnings.push( `${name}:--input 值未加引号被拆成 ${positional.length} 段,已自动拼回(下次请写 --input "${name}=完整值")`, ); } else { rawInputs[name] = positional.join(' '); } return warnings; } const max = Math.min(positional.length, defs.length); for (let i = 0; i < max; i++) { const def = defs[i]; if (def.name in rawInputs) { if (rawInputs[def.name] !== positional[i]) { warnings.push( `--input 优先级高于位置参数:${def.name} 取 ${JSON.stringify(rawInputs[def.name])},位置参数 ${JSON.stringify(positional[i])} 被忽略`, ); } } else { rawInputs[def.name] = positional[i]; } } if (positional.length > defs.length) { const dropped = positional.slice(defs.length); warnings.push( `忽略了 ${dropped.length} 个多余位置参数:${dropped.map((d) => JSON.stringify(d)).join(' ')}`, ); } return warnings; } /** `/workflow …` 主入口。 */ export async function* runWorkflowFromCommand( rawArgs: string, opts: RunWorkflowFromCommandOptions, ): AsyncGenerator { const { name, inputs: rawInputs, positional } = parseWorkflowArgs(rawArgs); if (!name) { yield { type: 'error', error: '/workflow 用法:/workflow [值 ...] [--input key=值 ...]\n输入 /workflows 查看可用工作流。', }; return; } const cwd = opts.cwd ?? process.cwd(); // 生命周期破坏性操作是 Runner 的命令,不加载/执行任何 workflow 脚本。 // `/workflow abandon ` 删除断点状态,并把已登记产物移入 sibling .trash; // ESC、pause 和 goal cancel 都不会走这条路径,仍然保留现场可恢复。 if (name === 'abandon' || name === 'discard') { const workflowName = positional[0] ?? rawInputs.workflow ?? ''; if (!workflowName) { yield { type: 'error', error: '/workflow abandon <工作流名> [--input task_id=任务ID](不指定 task_id 时只能有一个活动任务)', }; return; } try { const result = await abandonWorkflowTask({ workingDir: cwd, workflowName, sessionId: opts.runtimeContext?.sessionId ?? 'default', ...(rawInputs.task_id ? { taskId: rawInputs.task_id } : {}), }); yield { type: 'text', delta: `工作流「${result.workflowName}」已彻底放弃。\n` + `已删除断点、进度和执行账本;${result.archivedTo ? `中间产物已移入回收目录:${result.archivedTo}` : '没有发现已登记的中间产物'}。\n`, }; } catch (error) { yield { type: 'error', error: (error as Error).message }; } yield { type: 'turn_done' }; return; } const tools = opts.tools ?? []; const { script, errors } = await lookupWorkflow(name, cwd); if (!script) { if (errors) { // 「有但写错了」与「没有」必须区分开 —— 否则用户会去找一个并不存在的拼写问题。 yield { type: 'error', error: `工作流「${name}」存在但写错了:\n${errors.map((e) => ` · ${e}`).join('\n')}`, }; return; } yield { type: 'error', error: `未找到工作流「${name}」。输入 /workflows 查看可用列表。`, }; return; } for (const w of mapPositional( rawInputs, positional, script.meta.inputs, cwd, )) { yield { type: 'warning', message: `⚠ ${w}` }; } const sessionId = opts.runtimeContext?.sessionId ?? 'default'; let inputs: Record; let inputResourceMap: Record< string, import('../../../src/plugin-sdk.js').InvocationResource[] > = {}; let resourceFingerprint = ''; try { const bound = await bindResourceInputs({ workflowName: script.name, sessionId, cwd, rawInputs, defs: script.meta.inputs, attachments: opts.inputResources, }); for (const warning of bound.warnings) yield { type: 'plugin_progress', pluginId: 'workflow-runner', message: warning, }; inputResourceMap = bound.resourceMap as typeof inputResourceMap; resourceFingerprint = bound.resourceIdentity.join('|'); if (resourceFingerprint) bound.inputs.__resource_fingerprint = resourceFingerprint; inputs = coerceInputs( bound.inputs as Record, script.meta.inputs, ); } catch (e) { yield { type: 'error', error: (e as Error).message }; return; } let preparedManaged: | import('../../../src/managedExecution/types.js').PreparedManagedCommand | undefined; if (script.meta.managedRuntime) { const controller = managedCommandController(script.meta.managedRuntime); if (!controller) { yield { type: 'error', error: `未知 managedRuntime:${script.meta.managedRuntime}`, }; return; } preparedManaged = await controller(inputs, { cwd, runtimeContext: opts.runtimeContext, context: opts.managedContext, }); for (const event of preparedManaged.events) yield event; if (preparedManaged.handled) return; inputs = preparedManaged.inputs; // A managed controller may normalize/replace public inputs, but it must not // erase the resource component of task identity. if (resourceFingerprint && !inputs.__resource_fingerprint) inputs.__resource_fingerprint = resourceFingerprint; } await refreshStableSystemPrompt(opts.history, cwd, tools); const ctx: RunContext = { presentArtifacts: opts.presentArtifacts, executionId: opts.executionId, provider: opts.provider, runtimeContext: opts.runtimeContext, signal: opts.signal, history: opts.history, sessionState: opts.sessionState, cwd, tools, host: opts.host, transientContext: opts.transientContext, transientBundle: opts.transientBundle, promptCache: opts.promptCache, executeTool: opts.executeTool, toolContext: opts.toolContext, managedExecution: preparedManaged?.execution, managedBridge: preparedManaged?.bridge, inputResources: opts.inputResources, inputResourceMap, }; yield* runWorkflowScript(script, { ctx, inputs }); } /** `/workflows` —— 列出可用工作流,并如实报出写错的那些。 */ export async function* runWorkflowsList( cwd?: string, ): AsyncGenerator { const { workflows, failures } = await discoverWorkflows(cwd); const lines: string[] = []; if (workflows.length > 0) { lines.push('可用工作流:'); for (const w of workflows) { lines.push( ` /workflow ${w.name} — ${w.meta.description.split('\n')[0].trim()}`, ); } } if (workflows.length === 0) { lines.push( '当前没有可用工作流。在 workflows/<名字>/workflow.mjs 放一个脚本即可(`/skill workflow-creator` 会带你写)。', ); } // 写错的工作流必须报出来 —— 静默消失会让用户以为「我的工作流不见了」。 if (failures.length > 0) { lines.push(''); lines.push(`⚠ 有 ${failures.length} 个工作流写错了,未能载入:`); for (const f of failures) { lines.push(` · ${f.name}:${f.errors[0]}`); } } lines.push(''); lines.push('运行示例:'); lines.push(' /workflow <值> 位置参数(按 inputs 声明顺序)'); lines.push(' /workflow --input k=v 显式 KV'); lines.push(' /workflow abandon 彻底放弃并清理活动任务(产物移入 .trash)'); yield { type: 'text', delta: `${lines.join('\n')}\n` }; yield { type: 'turn_done' }; }