harness.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. /**
  2. * 父进程 harness(Boundary A 的宿主侧 + 沙箱进程编排)。
  3. *
  4. * 职责:把一份 workflow 脚本(或已 lowered 的函数体)在受控子进程里跑起来,用 NDJSON 桥接
  5. * 子进程的 `__host.*` 调用到一个 {@link WorkflowEngine} 实例,最终返回引擎的 {@link RunSettlement}。
  6. * 本包**只**依赖 `@zcode/dynamic-workflow` 与 node 内建——证明整条管线 app-free 可跑,
  7. * 绝不 import `@zcode/core`/`@zcode/contracts`/`@zcode/bootstrap`/`@zcode/adapters`。
  8. *
  9. * 时序(happy path):
  10. *
  11. * parent child(vm)
  12. * │ write <cwd>/.zcode/workflow-runs/<runId>.mjs(payload: lowered+args 内嵌)
  13. * │ spawn(node <entry>)
  14. * │──────────────────────────▶│ build __host in context
  15. * │◀── create-actor(local#1) ──│ createActor 同步返回 local#1
  16. * │ map local#1 → ActorId │
  17. * │◀── request ask(local#1) ───│ await __host.ask(...)
  18. * │ engine.ask → driver.startAsk … settle
  19. * │── response(value) ────────▶│ resolve
  20. * │◀────── complete(ok,value) ──│ 脚本 return
  21. * │ engine.complete(value) → settled=completed
  22. *
  23. * 失败/取消:run 的裁决归引擎所有。终结失败(脚本抛错 error-complete、子进程崩溃/非零退出、
  24. * 墙钟超时、子进程行 JSON 解析失败)都调 `engine.fail(error)`(结算 failed + journal failure_json);
  25. * abort 信号是唯一的"真取消",调 `engine.stop(initiator)`(结算 stopped;`signal.reason` 为
  26. * `"model"` 即主代理 TaskStop,`"interrupted"` 即宿主 App 关闭时停下自己拥有的 run,否则算用户)。引擎自身的 run 级失败
  27. * (reportCap/inputHash/unknownActor)同样经 engine.settled 冒出。harness 侧的 first-wins
  28. * finalize 只管子进程清理(清 timer、关 stdin、kill child),不自造结算。
  29. */
  30. import { spawn, type ChildProcess } from "node:child_process";
  31. import { createInterface, type Interface } from "node:readline";
  32. import {
  33. lowerWorkflowScript,
  34. WorkflowEngine,
  35. WorkflowError,
  36. type ActorId,
  37. type AskSpec,
  38. type Caps,
  39. type ImportedRunCache,
  40. type RunSettlement,
  41. type ValidateFn,
  42. type WorkflowDriver,
  43. type WorkflowReportSink,
  44. } from "@zcode/dynamic-workflow";
  45. import { type ChildMessage, type ChildPayload, type ResponseMessage } from "./protocol.js";
  46. import { renderChildEntry } from "./child-source.js";
  47. import { writeChildEntryFile, type HarnessWarning } from "./child-entry-file.js";
  48. /** driver 工厂:harness 先建 sink(引擎的向上回报面),交给工厂造 driver,再以该 driver 建引擎。 */
  49. export type DriverFactory = (sink: WorkflowReportSink) => WorkflowDriver;
  50. /**
  51. * run 的**活体控制面**:harness 在引擎构造好之后把这一世的引擎交给它,于是持有句柄的那一侧
  52. * (run service)能够到活着的引擎。两条命令——就地改本 run 的并发上界
  53. * (docs/dynamic-workflow/concurrency.md「Two bounds on a run」)与补全一处留白
  54. * (docs/execution-engine.md「Holes」)。
  55. *
  56. * 外加两个只读面 `openHoles` / `filledHoles`:run 快照里 `holes[].state === "waiting"` 必须从引擎的
  57. * 停驻表投影(docs/execution-engine.md「The run snapshot」——进程死过之后没有 promise 在等,光看
  58. * 事件会把没人问的留白报成在等),而这条绑定是 run service 够到活引擎的唯一接缝。
  59. *
  60. * 收窄成 `Pick<…>` 而不是整个引擎:控制面是一条**命令**通道,不是让
  61. * 宿主绕过 harness 去驱动 run 生命周期的后门(结算仍然只经 complete/stop/fail 那三条路)。
  62. *
  63. * 与 `signal` 同规:harness 只做接线,不解释、不校验、不兜底;命令的存活判定与 no-op 语义
  64. * 全在引擎里(`setMaxConcurrency` 返回 false 即这次什么也没发生)。
  65. */
  66. export interface RunControlBinding {
  67. bind(
  68. engine: Pick<WorkflowEngine, "setMaxConcurrency" | "fillHole" | "openHoles" | "filledHoles">,
  69. ): void;
  70. }
  71. /**
  72. * {@link runWorkflowScript} 的入参。执行体来自 `scriptText` 或 `lowered`(后者优先);
  73. * 两者同时给出正是「编译一次」的形态——调用方自己编译得到 `lowered`,同时把作者写的
  74. * `scriptText` 交下来落库。
  75. *
  76. * **harness 绝不校验这一对是否自洽**:它无法校验(判断 `lowered` 是否真由 `scriptText`
  77. * 降级而来,等于把编译再跑一遍,而那正是「编译一次」要省掉的那次)。递进来一份对不上的
  78. * 组合,落库的 `script_text` 就会与实际执行的代码不符,resume 的比对基准随之失真——
  79. * 这份自洽性归调用方所有。
  80. */
  81. export interface RunWorkflowOptions {
  82. /**
  83. * 作者写的 workflow 脚本源码,两个用途:
  84. * 1. `lowered` 缺省时由 harness lower 它得到执行体;
  85. * 2. **始终**作为 run 元数据落 `dwf_run.script_text`(resume 的比对基准是作者原文,
  86. * 不是 lowered 函数体)。
  87. */
  88. scriptText?: string;
  89. /**
  90. * 已 lowered 的 async 函数体(自由标识符仅 `__host`)。绕过编译器,直接喂沙箱——
  91. * 安全测试用它投喂手写 lowered 体(vm 契约本身才是被测对象),编译一次的路径用它
  92. * 交出自己那一次编译的产物。给出时优先于 `scriptText` 作为执行体。
  93. */
  94. lowered?: string;
  95. runId?: string;
  96. /** driver 工厂(见 {@link DriverFactory})。driver 自带 journal 与 emit。 */
  97. makeDriver: DriverFactory;
  98. caps: Caps;
  99. /** 每 ask 站点的静态规格。**必须覆盖脚本里的每个 ask 站点**——引擎把缺席当接线错误硬失败。 */
  100. askSpecs: ReadonlyMap<string, AskSpec>;
  101. /**
  102. * 站点 → 词法出生阶段名(`collectSitePhases`);verbatim 转交 `EngineConfig.sitePhases`。
  103. * 缺席即空表:引擎对每个站点都退回动态当前阶段(老编译产物、snippet、直接投喂 lowered 体)。
  104. */
  105. sitePhases?: ReadonlyMap<string, string>;
  106. /** 注入的 schema 校验器(引擎不 import schema 实现)。 */
  107. validate: ValidateFn;
  108. /** 外部取消信号:中止在飞 ask 并 kill 子进程,run 结算 cancelled。 */
  109. signal?: AbortSignal;
  110. /**
  111. * 活体控制面的绑定口(见 {@link RunControlBinding})。与 `signal` 同一条缝递进来:
  112. * 那个是「停下这个 run」的通道,这个是「改这个 run 的一项设置」的通道。缺席即本次启动
  113. * 没有控制面(集成测试、snippet 执行)。
  114. */
  115. control?: RunControlBinding;
  116. /** 墙钟超时(ms):到点 kill 子进程,run 结算 failed。缺省不限。 */
  117. timeoutMs?: number;
  118. /** 子进程堆上限(MB),映射为 `--max-old-space-size`。缺省 256。 */
  119. maxOldSpaceSizeMb?: number;
  120. /**
  121. * 子进程 spawn 策略的替代形态:给出时 spawn `process.execPath [...argsPrefix, <entry path>]`,
  122. * **不带任何 Node CLI 旗标**。
  123. *
  124. * 存在理由:SEA 单文件二进制不解释 Node CLI 旗标,缺省路径的 `--max-old-space-size` 会作为
  125. * 普通 token 落进 CLI 的严格 parseArgs 而必然报错退出(每个 workflow run 在 SEA 下都失败)。SEA 下
  126. * 由 bootstrap 传入隐藏子命令名作为 argsPrefix,子进程自 re-exec 本二进制并在 parseArgs 之前
  127. * `import()` 入口文件、调它的 `start`。
  128. *
  129. * 代价:堆上限只能由入口文件自己 `v8.setFlagsFromString` best-effort。
  130. */
  131. childSpawn?: { argsPrefix: readonly string[] };
  132. /**
  133. * 非致命状况的上报口(今日只有一种:入口文件写不进项目 `.zcode/`,回落到了 OS 临时目录)。
  134. * harness 是 app-free 的,没有 logger;bootstrap 把它接到自己的 warn 日志。
  135. */
  136. onWarning?: (warning: HarnessWarning) => void;
  137. /** 子进程工作目录,缺省 process.cwd();同时作为 run 元数据落 dwf_run.cwd。 */
  138. cwd?: string;
  139. /**
  140. * run 元数据,**原样**转交 `EngineConfig`(createRun 落 dwf_run)。全可选,harness
  141. * 不加工也不推断:`scriptHash` **由调用方计算**。harness 若哈希"它看到的文本",在
  142. * lowered 路径上落库的就是 lowered 函数体的哈希——resume 校验会拿到一个静默错误的
  143. * 比对对象。脚本原文走上面的 `scriptText`。
  144. */
  145. scriptHash?: string;
  146. parentSessionId?: string;
  147. /** run 的展示名(宿主枚举面的标签来源)。与 `scriptText` 同路,harness 只转交。 */
  148. name?: string;
  149. /**
  150. * 本次 run 的实参(saved workflow 的声明式参数,已由调用方校验并回填默认值)。
  151. *
  152. * **两个去处**,这是它与其余元数据的不同之处:既随 `EngineConfig` 落 `dwf_run.args_json`
  153. * (resume 从那里读回重放),也进 spawn payload 注入沙箱成为冻结的 `args` 全局。harness
  154. * 不校验、不加工——声明与校验都在调用方(工具侧)。缺席即 `{}`。
  155. */
  156. args?: Record<string, unknown>;
  157. /** 发起 run 的 CreateWorkflow 工具调用 id(重启后 join/通知锚点);verbatim 转交 EngineConfig。 */
  158. toolCallId?: string;
  159. /**
  160. * 修订续跑(amend-resume)的一对入参,与其余元数据同规:**verbatim 转交 EngineConfig**,
  161. * harness 不读、不加工、不推断。`resumedFrom` 是落 `dwf_run.resumed_from` 的 lineage 指针,
  162. * 同时作为脚本可见的 `run.resumedFrom` 进 spawn payload(resume 时调用方应传 journal 里的值,
  163. * 引擎命中既有行时不再落库,传它无害);`importedCache` 是注入引擎的纯数据缓存表。
  164. *
  165. * 与 `scriptText`/`lowered` 那一对同样的分工:**两者的一致性归调用方所有**。harness 无从判断
  166. * 这张表是否真由那个前驱 run 构建而来(那要求它自己去读 journal,而本包连存储都不认识)。
  167. * 递进来一张对不上的表,得到的就是一个把别人的答案当成自己缓存的 run。构建与门都在 run
  168. * service(bootstrap 的 dynamic-workflow-import.ts)。
  169. */
  170. resumedFrom?: string;
  171. /**
  172. * 发起 run 那一轮的锚点;verbatim 转交 EngineConfig。
  173. * `subagentModel` 与锚点、阶段表同车:本 run 子代理的规范 picker 串
  174. * (`providerId/modelId[$reasoningLevel]`),harness 同样不读、不解析、不加工——它零 SQL 地
  175. * 活在 `run-launched` 事件里,解析与优先级都在宿主侧(bootstrap 的 workflow-actor-model.ts)。
  176. * `phaseAlongside` 与 `phaseNames` 按位置对齐(下标指向同一张表),同车同规。
  177. */
  178. launch?: {
  179. inputId: string;
  180. phaseNames?: string[];
  181. subagentModel?: string;
  182. /** 脚本点名的模型 → 规范串(docs/dynamic-workflow/launch.md「Models the script names」),同车同规。 */
  183. modelBindings?: Record<string, string>;
  184. phaseAlongside?: number[][];
  185. /** `phaseNames` 里未补全留白的下标(docs/execution-engine.md「Holes」),同车同规。 */
  186. holes?: number[];
  187. };
  188. importedCache?: ImportedRunCache;
  189. /**
  190. * 建 run 时的用量起点(前驱 run 的 `spentTokens`);与其余元数据同规:**verbatim 转交
  191. * EngineConfig**,harness 不读、不加工。读前驱的行发生在 run service。
  192. */
  193. inheritedTokens?: number;
  194. }
  195. const DEFAULT_MAX_OLD_SPACE_MB = 256;
  196. const STDERR_LIMIT = 64 * 1024;
  197. /**
  198. * 跑一份 workflow 脚本至结算。返回引擎的 {@link RunSettlement}。
  199. * 失败一等公民,但分两类:脚本抛错是脚本之错,
  200. * 归一成 `{status:"errored", error}`;子进程无法启动 / 崩溃 / 墙钟超时 / 协议损坏是宿主侧故障,
  201. * 重跑很可能就好,归一成 `{status:"stopped", reason:"interrupted", error}`(可 resume)。
  202. * 两者都绝不静默吞掉。
  203. */
  204. export async function runWorkflowScript(options: RunWorkflowOptions): Promise<RunSettlement> {
  205. const lowered = resolveLowered(options);
  206. const runId = options.runId ?? "run";
  207. // sink 晚绑定:引擎在 driver 之后构造,但 driver 需要 sink 回报——用转发代理打破环依赖。
  208. let engine!: WorkflowEngine;
  209. const sink: WorkflowReportSink = {
  210. askSubmitAttempted: (instance, payload) => engine.askSubmitAttempted(instance, payload),
  211. askTurnEnded: (instance, finalText) => engine.askTurnEnded(instance, finalText),
  212. askProgress: (instance, progress) => engine.askProgress(instance, progress),
  213. askStats: (instance, stats) => engine.askStats(instance, stats),
  214. askFailed: (instance, error) => engine.askFailed(instance, error),
  215. // 确定性模型侧错误 → 整个 run 停下,同样只是转发。
  216. stopRun: (error) => engine.stopRun(error),
  217. // 自适应并发的三个纯观察与 run 级停滞观察,同样只是转发。
  218. askWaiting: (instance, info) => engine.askWaiting(instance, info),
  219. askExecuting: (instance) => engine.askExecuting(instance),
  220. // 唯一会让引擎做决策的观察(关导入缓存),同样只是转发。
  221. askMutating: (instance) => engine.askMutating(instance),
  222. concurrencyChanged: (change) => engine.concurrencyChanged(change),
  223. runStalled: (info) => engine.runStalled(info),
  224. };
  225. const driver = options.makeDriver(sink);
  226. engine = new WorkflowEngine({
  227. runId,
  228. driver,
  229. caps: options.caps,
  230. askSpecs: options.askSpecs,
  231. validate: options.validate,
  232. ...(options.sitePhases === undefined ? {} : { sitePhases: options.sitePhases }),
  233. // 元数据 verbatim 转交,缺省保持缺席(不落成 undefined 键)。cwd 与子进程实际使用的
  234. // 是同一个值,所以这里也记 process.cwd() 的兜底——落库的 cwd 就是 run 真正跑的目录。
  235. ...(options.scriptText === undefined ? {} : { scriptText: options.scriptText }),
  236. ...(options.name === undefined ? {} : { name: options.name }),
  237. ...(options.args === undefined ? {} : { args: options.args }),
  238. ...(options.scriptHash === undefined ? {} : { scriptHash: options.scriptHash }),
  239. ...(options.parentSessionId === undefined ? {} : { parentSessionId: options.parentSessionId }),
  240. ...(options.toolCallId === undefined ? {} : { toolCallId: options.toolCallId }),
  241. ...(options.resumedFrom === undefined ? {} : { resumedFrom: options.resumedFrom }),
  242. ...(options.launch === undefined ? {} : { launch: options.launch }),
  243. ...(options.importedCache === undefined ? {} : { importedCache: options.importedCache }),
  244. ...(options.inheritedTokens === undefined ? {} : { inheritedTokens: options.inheritedTokens }),
  245. cwd: options.cwd ?? process.cwd(),
  246. });
  247. // 控制面一构造好就绑:run 从第一条事件起就可被改设置,而**不必**等子进程起来——下面那条
  248. // spawn 失败路径也经引擎结算,句柄在那之后照样安全(命令自己的 settled 判定负责收口)。
  249. options.control?.bind(engine);
  250. const maxOldSpaceSizeMb = options.maxOldSpaceSizeMb ?? DEFAULT_MAX_OLD_SPACE_MB;
  251. const cwd = options.cwd ?? process.cwd();
  252. const payload: ChildPayload = {
  253. lowered,
  254. // 实参只在启动时过界一次(run 生命周期内是常量)。
  255. ...(options.args === undefined ? {} : { args: options.args }),
  256. // run 身份与实参同车。前驱 id 用的就是落库的那个 lineage 指针(resume 时调用方从 journal
  257. // 读回再递进来),所以脚本在建 run 与续跑两世读到同一个值。
  258. run: {
  259. id: runId,
  260. ...(options.resumedFrom === undefined ? {} : { resumedFrom: options.resumedFrom }),
  261. },
  262. // 堆上限随 payload 进入口文件,只为 argsPrefix 路径服务:那条路上没有 Node 旗标可传,
  263. // 入口文件只能自己 best-effort 设。缺省路径由真旗标生效,入口文件看到旗标就跳过。
  264. maxOldSpaceSizeMb,
  265. };
  266. // payload 不过命令行:Windows 的命令行上限 32,767 字符,整份 lowered 脚本放上去一过约 18 KB
  267. // 就 `spawn ENAMETOOLONG`。写成入口文件,
  268. // argv 只剩一条路径,长度与脚本大小无关。
  269. let child: ChildProcess;
  270. try {
  271. const entry = writeChildEntryFile({
  272. cwd,
  273. runId,
  274. source: renderChildEntry(payload, { runId }),
  275. ...(options.onWarning === undefined ? {} : { onWarning: options.onWarning }),
  276. });
  277. child = spawn(
  278. process.execPath,
  279. options.childSpawn === undefined
  280. ? [`--max-old-space-size=${maxOldSpaceSizeMb}`, entry.path]
  281. : [...options.childSpawn.argsPrefix, entry.path],
  282. {
  283. cwd,
  284. stdio: ["pipe", "pipe", "pipe"],
  285. // 桌面端 agent 由 Electron Helper 运行(process.execPath 指向 Helper),而 CLI
  286. // 启动时会把 ELECTRON_RUN_AS_NODE 从自身 env sanitize 掉。不显式带上它,子进程会按完整
  287. // Electron/Chromium 应用启动并卡在 GPU 初始化——永远沉默也不退出,run 卡死在 run-started。
  288. // 纯 Node 的 execPath 下该变量无效,无副作用(同 official-plugin-runtime.ts 的处理)。
  289. // 两条 spawn 策略都要带:桌面打包态同样可能走 argsPrefix 路径。
  290. env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
  291. },
  292. );
  293. } catch (cause) {
  294. // Node 只把 EACCES/EAGAIN/EMFILE/ENFILE/ENOENT 转成 error
  295. // 事件,其余 spawn 失败(ENAMETOOLONG、E2BIG…)**同步抛**。此时引擎已构造、journal 行已以
  296. // running 落库;让异常直接冒出去会绕过引擎结算——注册表记成终态,journal 行却永远
  297. // running,随后的 resume_from 被「has not settled yet」拒绝。入口文件写不下(两个目录都
  298. // 失败)同理。一律经引擎结算 stopped(interrupted):宿主侧故障,可 resume。
  299. const message = cause instanceof Error ? cause.message : String(cause);
  300. engine.stop(
  301. "interrupted",
  302. new WorkflowError("Interrupted", `Could not start the workflow sandbox process: ${message}`, {
  303. cause,
  304. }),
  305. );
  306. return engine.settled;
  307. }
  308. return bridge({ child, engine, runId, signal: options.signal, timeoutMs: options.timeoutMs });
  309. }
  310. /** 解析 lowered 体:优先 `lowered`,否则 lower `scriptText`(脏脚本抛错,不启动子进程)。 */
  311. function resolveLowered(options: RunWorkflowOptions): string {
  312. if (options.lowered !== undefined) return options.lowered;
  313. if (options.scriptText === undefined) {
  314. throw new Error("runWorkflowScript: pass either scriptText or lowered");
  315. }
  316. const result = lowerWorkflowScript(options.scriptText);
  317. if (!result.ok || result.lowered === undefined) {
  318. const detail = result.diagnostics.map((d) => `${d.line}:${d.column} ${d.message}`).join("; ");
  319. throw new Error(
  320. `runWorkflowScript: the script failed compilation/analysis and is not run degraded: ${detail}`,
  321. );
  322. }
  323. return result.lowered.code;
  324. }
  325. interface BridgeDeps {
  326. child: ChildProcess;
  327. engine: WorkflowEngine;
  328. /** 只用于 abort 归一里的错误文本("interrupted" 那一支要指名是哪个 run 被关掉的)。 */
  329. runId: string;
  330. signal?: AbortSignal;
  331. timeoutMs?: number;
  332. }
  333. /**
  334. * NDJSON 桥接 + 生命周期收敛。single-writer finalize:无论从引擎结算、子进程退出、超时还是
  335. * abort 触达,第一个到达者胜出,随后 kill 子进程并兑现结果。
  336. */
  337. function bridge(deps: BridgeDeps): Promise<RunSettlement> {
  338. const { child, engine, runId, signal, timeoutMs } = deps;
  339. // local#N(child-local 句柄)→ engine ActorId 的映射;stdio FIFO + 同步 create-actor 处理保证
  340. // 任何引用某句柄的 ask 到达前,该映射已就绪。
  341. const actorMap = new Map<string, ActorId>();
  342. let stderr = "";
  343. let finalized = false;
  344. let timer: ReturnType<typeof setTimeout> | undefined;
  345. let reader: Interface | undefined;
  346. return new Promise<RunSettlement>((resolve) => {
  347. const finalize = (settlement: RunSettlement): void => {
  348. if (finalized) return;
  349. finalized = true;
  350. if (timer !== undefined) clearTimeout(timer);
  351. if (signal !== undefined) signal.removeEventListener("abort", onAbort);
  352. reader?.close();
  353. if (child.exitCode === null && child.signalCode === null) child.kill();
  354. resolve(settlement);
  355. };
  356. // 终结失败(脚本抛错 / 子进程崩溃 / 超时 / 协议损坏)都是 run 失败:交给引擎的公有 fail(),
  357. // 由它 first-wins 结算、driver 侧取消在飞 ask、journal 记 failed + failure_json——run 的裁决
  358. // 归引擎所有,journal 与调用方看到的结果不分叉。子进程清理由 finalize(经 engine.settled)负责。
  359. const failRun = (error: WorkflowError): void => {
  360. if (finalized) return;
  361. engine.fail(error);
  362. };
  363. // 宿主侧故障(沙箱崩溃 / 超时 / 协议损坏):stopped(interrupted),可 resume。
  364. const interruptRun = (message: string, cause?: unknown): void => {
  365. if (finalized) return;
  366. engine.stop(
  367. "interrupted",
  368. new WorkflowError("Interrupted", message, cause === undefined ? undefined : { cause }),
  369. );
  370. };
  371. // abort 是唯一的"真取消":走 engine.stop(initiator),结算 stopped。initiator 经
  372. // `AbortController.abort(reason)` 过来:字面 "model"、amend 路径的
  373. // `{ superseded: newRunId }`(后继 id 随原因同一笔落库)、字面 "interrupted"(宿主 App
  374. // 关闭,见下),其余一律 "user"。
  375. function onAbort(): void {
  376. if (finalized) return;
  377. const reason: unknown = signal?.reason;
  378. const supersededBy = readSupersededBy(reason);
  379. if (supersededBy !== undefined) {
  380. engine.stop("superseded", undefined, supersededBy);
  381. return;
  382. }
  383. // 宿主主动停下自己拥有的 run(run service 的 close())。它不是用户取消:带 Interrupted 失败编码落库,与超时 /
  384. // 沙箱崩溃同一族——stopped(interrupted) 可 resume,而 stopped(user) 在 UI 上读作
  385. // 「用户按了停止」。错误文本指名 run 与成因,下一次激活时详情页据它解释这一行。
  386. if (reason === "interrupted") {
  387. engine.stop(
  388. "interrupted",
  389. new WorkflowError(
  390. "Interrupted",
  391. `dynamic workflow run ${runId} was interrupted: the owning session closed before the run settled`,
  392. ),
  393. );
  394. return;
  395. }
  396. engine.stop(reason === "model" ? "model" : "user");
  397. }
  398. // 一切结算(complete / fail / stop / 引擎内部 cap 失败)都经 engine.settled 冒出到 finalize。
  399. void engine.settled.then(finalize);
  400. if (signal !== undefined) {
  401. if (signal.aborted) {
  402. onAbort();
  403. return;
  404. }
  405. signal.addEventListener("abort", onAbort, { once: true });
  406. }
  407. if (timeoutMs !== undefined) {
  408. timer = setTimeout(() => {
  409. interruptRun(
  410. `The workflow sandbox process exceeded its wall-clock timeout of ${timeoutMs}ms`,
  411. );
  412. }, timeoutMs);
  413. timer.unref?.();
  414. }
  415. child.stderr?.on("data", (chunk: Buffer) => {
  416. stderr = trimTail(stderr + chunk.toString("utf8"), STDERR_LIMIT);
  417. });
  418. // 子进程退出后仍可能有 response 待写:给 stdin 挂 error 监听,避免 EPIPE 冒成未捕获异常。
  419. child.stdin?.on("error", () => undefined);
  420. reader = createInterface({ input: child.stdout! });
  421. reader.on("line", (line) => {
  422. if (line.trim().length === 0) return;
  423. let message: ChildMessage;
  424. try {
  425. message = JSON.parse(line) as ChildMessage;
  426. } catch (cause) {
  427. // 子进程行 JSON 损坏:暴露而非吞掉。
  428. interruptRun(
  429. `The workflow sandbox process emitted a line that is not valid NDJSON: ${line}`,
  430. cause,
  431. );
  432. return;
  433. }
  434. handleChildMessage(message, { engine, actorMap, child, failRun });
  435. });
  436. child.on("error", (error) => {
  437. interruptRun(`Could not start the workflow sandbox process: ${error.message}`, error);
  438. });
  439. child.on("close", (code, sig) => {
  440. if (finalized) return;
  441. // 子进程退出但引擎未结算:崩溃/被杀而无 complete。以 stderr 归因。
  442. const reason =
  443. stderr.trim().length > 0
  444. ? stderr.trim()
  445. : `The workflow sandbox process exited (code=${code}, signal=${sig}) before completing`;
  446. interruptRun(reason);
  447. });
  448. });
  449. }
  450. interface MessageDeps {
  451. engine: WorkflowEngine;
  452. actorMap: Map<string, ActorId>;
  453. child: ChildProcess;
  454. failRun: (error: WorkflowError) => void;
  455. }
  456. /** 分发一条 child→parent 消息。ask/world-read 异步桥接到引擎并回 response(搭载最新预算)。 */
  457. function handleChildMessage(message: ChildMessage, deps: MessageDeps): void {
  458. const { engine, actorMap, child, failRun } = deps;
  459. switch (message.kind) {
  460. case "create-actor": {
  461. // 同步处理:在任何引用该句柄的 ask 之前把映射建好(stdio FIFO 前提)。createActor 是纯同步的,
  462. // 若 run 已结算会同步抛错——此时没有 response 通道,捕获后归为 run 失败(多为无害的收尾竞态)。
  463. try {
  464. const actorId = engine.createActor(
  465. message.siteId,
  466. message.name,
  467. message.persona as string | undefined,
  468. );
  469. actorMap.set(message.localId, actorId);
  470. } catch (cause) {
  471. failRun(
  472. cause instanceof WorkflowError
  473. ? cause
  474. : new WorkflowError("DriverError", `createActor failed at site ${message.siteId}`, {
  475. cause,
  476. }),
  477. );
  478. }
  479. return;
  480. }
  481. case "event":
  482. // 同步分派,与 log 一致:事件通道的 FIFO 顺序对 report 与 declare-artifact 都是承重的
  483. // (父进程 journal 的就是到达的东西,而一条打了标签的 report 必须晚于它的声明落库),
  484. // 异步化会让到达顺序与 journal 顺序脱钩。
  485. if (message.type === "report") {
  486. engine.report(message.siteId, message.item, message.artifactId);
  487. } else if (message.type === "declare-artifact") {
  488. engine.declareArtifact(message.siteId, message.op, message.args);
  489. } else if (message.type === "phase-entered") {
  490. engine.enterPhase(message.name);
  491. } else {
  492. engine.log(message.message);
  493. }
  494. return;
  495. case "complete":
  496. if (message.ok) {
  497. engine.complete(message.value);
  498. } else {
  499. // 脚本抛错:run 失败(错误明细来自沙箱)。
  500. const err = message.error;
  501. failRun(
  502. new WorkflowError("DriverError", err?.message ?? "The workflow script threw an error", {
  503. cause: err?.stack ?? err?.name,
  504. }),
  505. );
  506. }
  507. return;
  508. case "request":
  509. handleRequest(message, { engine, actorMap, child, failRun });
  510. return;
  511. default: {
  512. const _exhaustive: never = message;
  513. void _exhaustive;
  514. }
  515. }
  516. }
  517. /** 桥接一次需应答的 host 调用(ask / world-read / publish-artifact / hole)到引擎,settle 后回 response。 */
  518. function handleRequest(
  519. message: Extract<ChildMessage, { kind: "request" }>,
  520. deps: MessageDeps,
  521. ): void {
  522. const { engine, actorMap, child } = deps;
  523. const respond = (ok: boolean, value: unknown, error?: WorkflowError): void => {
  524. const response: ResponseMessage = {
  525. kind: "response",
  526. id: message.id,
  527. ok,
  528. ...(ok ? { value } : { error: toWireError(error) }),
  529. };
  530. // 子进程可能已退出(取消/失败收尾):仅在可写时写,EPIPE 等 I/O 竞态吞在此边界(run 已在结算)。
  531. const stdin = child.stdin;
  532. if (stdin === null || !stdin.writable) return;
  533. stdin.write(`${JSON.stringify(response)}\n`, () => undefined);
  534. };
  535. let promise: Promise<unknown>;
  536. if (message.type === "ask") {
  537. const actorId = actorMap.get(message.actor ?? "");
  538. if (actorId === undefined) {
  539. // 映射缺失(理应不会发生:FIFO 保证)——归一成 UnknownActor 结构化拒绝,不静默。
  540. respond(
  541. false,
  542. undefined,
  543. new WorkflowError("UnknownActor", `Unknown subagent handle: ${message.actor}`),
  544. );
  545. return;
  546. }
  547. promise = engine.ask(message.siteId, actorId, message.instructions ?? "");
  548. } else if (message.type === "publish-artifact") {
  549. const op = message.artifactOp;
  550. if (op === undefined) {
  551. // 缺 op 是接线错误(lowering 恒填它)。**不编一个默认值**:一个被当成 file 处理的
  552. // markdown 发布,错误会出现在离故障点很远的地方。归一成结构化拒绝,脚本看得见。
  553. respond(
  554. false,
  555. undefined,
  556. new WorkflowError(
  557. "DriverError",
  558. `publish-artifact request is missing artifactOp (site ${message.siteId})`,
  559. ),
  560. );
  561. return;
  562. }
  563. promise = engine.publishArtifact(message.siteId, op, message.args ?? []);
  564. } else if (message.type === "hole") {
  565. // 留白:引擎把 promise 停在站点下,主代理经控制面 fillHole 放行后才有 `{code}` 可答;
  566. // 在此之前它就是一条在飞请求(docs/execution-engine.md「The vm cell」)。
  567. promise = engine.hole(message.siteId, message.name ?? "", message.prompt);
  568. } else {
  569. // op/args 原样转交引擎:本层不看 op、不校验元数(那是 driver 的职责)。缺失 args 归一为空数组,
  570. // 让 driver 的实参校验大声拒绝,而不是在这里悄悄编一个默认值。
  571. promise = engine.worldRead(message.siteId, message.op ?? "read", message.args ?? []);
  572. }
  573. promise.then(
  574. (value) => respond(true, value),
  575. (cause: unknown) => {
  576. const error =
  577. cause instanceof WorkflowError
  578. ? cause
  579. : new WorkflowError(
  580. "DriverError",
  581. cause instanceof Error ? cause.message : String(cause),
  582. { cause },
  583. );
  584. respond(false, undefined, error);
  585. },
  586. );
  587. }
  588. /** WorkflowError → 线形态(保留 code/violations/finalText,供沙箱脚本 try/catch 结构化处理)。 */
  589. function toWireError(error: WorkflowError | undefined): ResponseMessage["error"] {
  590. if (error === undefined) return { name: "Error", message: "unknown error" };
  591. const wire: NonNullable<ResponseMessage["error"]> = {
  592. name: error.name,
  593. message: error.message,
  594. code: error.code,
  595. };
  596. if (error.violations !== undefined) wire.violations = error.violations;
  597. if (error.finalText !== undefined) wire.finalText = error.finalText;
  598. return wire;
  599. }
  600. /** 保留字符串尾部 limit 字节内的内容(stderr 截断)。 */
  601. function trimTail(value: string, limit: number): string {
  602. if (Buffer.byteLength(value, "utf8") <= limit) return value;
  603. return value.slice(-limit);
  604. }
  605. /** abort reason 是 `{ superseded: <runId> }` 时取出后继 id;其余形状返回 undefined。 */
  606. function readSupersededBy(reason: unknown): string | undefined {
  607. if (typeof reason !== "object" || reason === null) return undefined;
  608. const value = (reason as { superseded?: unknown }).superseded;
  609. return typeof value === "string" && value.length > 0 ? value : undefined;
  610. }