script-workflow-child-runtime.test.ts 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  1. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { fileURLToPath } from "node:url";
  5. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  6. import { createNodeFileSystemAdapter } from "@zcode/adapters/fs";
  7. import { createInMemorySessionEventStore, createSqliteSessionStore } from "@zcode/adapters/storage";
  8. import { type AgentRuntime, PermissionService, defaultPermissionConfig } from "@zcode/core";
  9. import { createModelTelemetry } from "@zcode/telemetry";
  10. import {
  11. createRootTraceContext,
  12. createSessionId,
  13. createToolCallId,
  14. createTraceId,
  15. CREATE_WORKFLOW_TOOL_NAME,
  16. ESCALATE_TOOL_NAME,
  17. EVAL_WORKFLOW_SNIPPET_TOOL_NAME,
  18. LIST_WORKFLOW_RUNS_TOOL_NAME,
  19. type Model,
  20. type ModelResult,
  21. type ModelSelection,
  22. type PermissionBrokerRequest,
  23. SessionEventType,
  24. SUBMIT_RESULT_TOOL_NAME,
  25. type SessionEvent,
  26. type SessionEventStorePort,
  27. type SessionStorePort,
  28. type SkillRoot,
  29. type WorkflowEscalatePort,
  30. type WorkflowSubmitPort,
  31. } from "@zcode/contracts";
  32. import {
  33. createScriptWorkflowAgentRuntime,
  34. createWorkflowChildSkillPort,
  35. type ScriptWorkflowAgentRuntimeDeps,
  36. } from "../src/app/script-workflow-child-runtime.js";
  37. import { createProtocolBrowserControlBroker } from "../src/zcode-protocol/browser-control-broker.js";
  38. import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
  39. import {
  40. parseWorkflowSubagentPermissionMode,
  41. workflowActorInteractionDescription,
  42. workflowActorPermissionPolicy,
  43. type WorkflowSubagentPermissionMode,
  44. } from "../src/app/workflow-actor-permission.js";
  45. import { workflowActorToolPolicy } from "../src/app/workflow-actor-tools.js";
  46. import {
  47. createTestAgentRuntime,
  48. createTestModelFactory,
  49. createTestModelFactoryFromAdapter,
  50. } from "./helpers/test-agent-runtime.js";
  51. /**
  52. * actor transcript 的直播通道(照 subagent 同款)。三件事被钉住:
  53. * 共享 event store、构造期 sink 从 seq 1 起看全、事件在共享 store 里恰好一份。
  54. */
  55. describe("script workflow child runtime — actor transcript 直播通道", () => {
  56. const parentSessionId = createSessionId("dwf-parent");
  57. const actorSessionId = createSessionId("dwf-actor-a-1");
  58. let tempRoot: string;
  59. let parentStore: SessionEventStorePort;
  60. let sessionStore: SessionStorePort;
  61. let parentRuntime: AgentRuntime;
  62. let forwarded: SessionEvent[];
  63. beforeEach(async () => {
  64. tempRoot = await mkdtemp(join(tmpdir(), "zcode-actor-transcript-"));
  65. parentStore = createInMemorySessionEventStore();
  66. sessionStore = createSqliteSessionStore({ dbPath: ":memory:" });
  67. forwarded = [];
  68. parentRuntime = createTestAgentRuntime(
  69. parentSessionId,
  70. { workingDirectory: tempRoot },
  71. {
  72. eventStore: parentStore,
  73. fileSystemPort: createNodeFileSystemAdapter(),
  74. modelFactory: scriptedModelFactory,
  75. },
  76. );
  77. // 协议服务器听的就是父 record 自己的 runtime 订阅(server-operations.ts 的
  78. // `record.unsubscribe = app.runtime.subscribeEvents(...)`),detached 的子 sessionId
  79. // 在那里被路由成 live topic。测试因此断在同一个面上,而不是任何注入的旁路。
  80. parentRuntime.subscribeEvents({
  81. onSessionEvent: (event) => {
  82. forwarded.push(event);
  83. },
  84. });
  85. });
  86. afterEach(async () => {
  87. await rm(tempRoot, { force: true, recursive: true });
  88. });
  89. // 父会话的 model factory:生产里 child 与主 turn 共用 create-app 造的那一份(见
  90. // script-workflow-child-runtime.ts 的 deps.modelFactory)。
  91. const scriptedModelFactory = createTestModelFactoryFromAdapter({
  92. async generateText() {
  93. return {
  94. finishReason: "stop",
  95. providerMetadata: undefined,
  96. text: "actor done",
  97. usage: { inputTokens: 3, outputTokens: 2, totalTokens: 5 },
  98. } as unknown as ModelResult;
  99. },
  100. });
  101. function makeDeps(): ScriptWorkflowAgentRuntimeDeps {
  102. return {
  103. agentTelemetry: createModelTelemetry().agentExecution,
  104. appOptions: { env: process.env },
  105. appVersion: "0.0.0-test",
  106. configResult: {
  107. config: {
  108. features: { skill: false },
  109. modelStream: { idleTimeoutMs: 0 },
  110. network: {},
  111. skillOverrides: {},
  112. skills: { enabled: false, roots: [] },
  113. },
  114. },
  115. fileSystemPort: createNodeFileSystemAdapter(),
  116. imageProcessorPort: {},
  117. logger: undefined,
  118. modelFactory: scriptedModelFactory,
  119. permissionService: new PermissionService(defaultPermissionConfig),
  120. runtime: parentRuntime,
  121. runtimeConfig: { workingDirectory: tempRoot },
  122. sessionId: parentSessionId,
  123. sessionStore,
  124. storageRoot: tempRoot,
  125. workingDirectory: tempRoot,
  126. } as unknown as ScriptWorkflowAgentRuntimeDeps;
  127. }
  128. function makeActorRuntime(): AgentRuntime {
  129. return createScriptWorkflowAgentRuntime({
  130. childSessionId: actorSessionId,
  131. deps: makeDeps(),
  132. request: { opts: {} } as never,
  133. traceContext: createRootTraceContext({ sessionId: parentSessionId }),
  134. });
  135. }
  136. it("actor runtime 与父 runtime 共享 event store", async () => {
  137. const actorRuntime = makeActorRuntime();
  138. expect(actorRuntime.getSessionEventStore()).toBe(parentStore);
  139. await actorRuntime.ensureSessionPersistedForExternalActivity("workflow actor a#1@1");
  140. await actorRuntime.executeTurn("go");
  141. // v4 的 loadPersistedEvents 读的就是 record.eventStore,按 actorSessionId 取;
  142. // 私建内存 store 时这里恒为空,transcript 永久空白。
  143. const stored = await parentStore.getEvents(actorSessionId);
  144. expect(stored.length).toBeGreaterThan(1);
  145. // 会话行也落在共享的 sessionStore 上(v4 冷 hydration 的前提)。
  146. expect(await sessionStore.getSession(actorSessionId)).toBeDefined();
  147. });
  148. it("转发流从 sequenceNumber 1(SessionTitleUpdated)起,保留 actor 的 sessionId", async () => {
  149. const actorRuntime = makeActorRuntime();
  150. await actorRuntime.ensureSessionPersistedForExternalActivity("workflow actor a#1@1");
  151. await actorRuntime.executeTurn("go");
  152. expect(forwarded.length).toBeGreaterThan(1);
  153. // sink 装在构造期,所以 seq 1 的 title 事件也在流里。装在 persist 之后的旧订阅只能从
  154. // seq 2 起,而 v4 网关只排水连续 seq——它会永远等一个再也不会来的 seq 1。
  155. expect(forwarded[0]!.type).toBe(SessionEventType.SessionTitleUpdated);
  156. expect(forwarded[0]!.sequenceNumber).toBe(1);
  157. expect(forwarded.every((event) => event.sessionId === actorSessionId)).toBe(true);
  158. expect(forwarded.map((event) => event.sequenceNumber)).toEqual(
  159. forwarded.map((_event, index) => index + 1),
  160. );
  161. });
  162. it("恰好一次:每条 actor 事件在共享 store 里只有一份,父会话不被污染", async () => {
  163. const actorRuntime = makeActorRuntime();
  164. await actorRuntime.ensureSessionPersistedForExternalActivity("workflow actor a#1@1");
  165. await actorRuntime.executeTurn("go");
  166. const stored = await parentStore.getEvents(actorSessionId);
  167. expect(stored.length).toBeGreaterThan(1);
  168. const idCounts = new Map<string, number>();
  169. for (const event of stored) idCounts.set(event.id, (idCounts.get(event.id) ?? 0) + 1);
  170. expect([...idCounts.values()].filter((count) => count !== 1)).toEqual([]);
  171. // 转发是「只通知不 append」:转发条数与落库条数一致,没有第二次写入。
  172. expect(forwarded).toHaveLength(stored.length);
  173. expect(forwarded.map((event) => event.id)).toEqual(stored.map((event) => event.id));
  174. // 父会话自己一条事件都没有:actor 正文不许落到父 timeline 上。
  175. expect(await parentStore.getEvents(parentSessionId)).toEqual([]);
  176. });
  177. /**
  178. * actor 会话的两个控制端口 → 两个控制工具(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md)。
  179. *
  180. * 这条线是 escalate 的**整条命脉**:端口从 run service 经 create-app 的 createActorRuntime
  181. * 流到这里,core 再以「端口在场」为门注册工具。断在注册表上而不是断在参数透传上,是因为
  182. * 中间任何一环漏掉(没接、名字写错、门判据写反),透传断言都还会绿,而 actor 的求助通道
  183. * 已经没了——它撞上坏门时只剩死磕或投机绕过。
  184. */
  185. describe("script workflow child runtime — actor 的控制工具面", () => {
  186. const submitPort: WorkflowSubmitPort = { respond: async () => ({ accept: true }) };
  187. const escalatePort: WorkflowEscalatePort = {
  188. escalate: async () => ({ kind: "answered", answer: "ok", qid: "dwfq-x-1" }),
  189. };
  190. function actorRuntimeWith(ports: {
  191. workflowSubmitPort?: WorkflowSubmitPort;
  192. workflowEscalatePort?: WorkflowEscalatePort;
  193. }): AgentRuntime {
  194. return createScriptWorkflowAgentRuntime({
  195. childSessionId: createSessionId("dwf-actor-tools"),
  196. deps: makeDeps(),
  197. request: { opts: {} } as never,
  198. traceContext: createRootTraceContext({ sessionId: parentSessionId }),
  199. ...ports,
  200. });
  201. }
  202. it("注入 escalatePort 即为该会话注册 escalate", () => {
  203. const registry = actorRuntimeWith({
  204. workflowSubmitPort: submitPort,
  205. workflowEscalatePort: escalatePort,
  206. }).getToolRegistry();
  207. expect(registry.has(ESCALATE_TOOL_NAME)).toBe(true);
  208. expect(registry.has(SUBMIT_RESULT_TOOL_NAME)).toBe(true);
  209. });
  210. it("两个端口各自独立成门:只给 submitPort 时 escalate 不注册", () => {
  211. const registry = actorRuntimeWith({ workflowSubmitPort: submitPort }).getToolRegistry();
  212. expect(registry.has(SUBMIT_RESULT_TOOL_NAME)).toBe(true);
  213. expect(registry.has(ESCALATE_TOOL_NAME)).toBe(false);
  214. });
  215. it("两个端口都缺席时两个工具都不注册(非 actor 会话的形状)", () => {
  216. const registry = actorRuntimeWith({}).getToolRegistry();
  217. expect(registry.has(SUBMIT_RESULT_TOOL_NAME)).toBe(false);
  218. expect(registry.has(ESCALATE_TOOL_NAME)).toBe(false);
  219. });
  220. });
  221. // persona 经 configOverrides.workflowActor 叠加到基座之上,systemPrompt 必须缺席——哪怕父
  222. // 会话自带 custom system prompt(docs/dynamic-workflow/authoring.md「The system prompt」)。
  223. describe("script workflow child runtime — persona 走 workflowActor 而非 systemPrompt", () => {
  224. function configOf(runtime: AgentRuntime): Record<string, unknown> {
  225. return (runtime as unknown as { config: Record<string, unknown> }).config;
  226. }
  227. it("workflowActor 落到 child config,systemPrompt 不被父会话的 custom prompt 污染", () => {
  228. const deps = makeDeps();
  229. const runtime = createScriptWorkflowAgentRuntime({
  230. childSessionId: createSessionId("dwf-actor-persona"),
  231. configOverrides: { workflowActor: { name: "reviewer", persona: "You review." } },
  232. deps: {
  233. ...deps,
  234. runtimeConfig: { ...deps.runtimeConfig, systemPrompt: "parent custom prompt" },
  235. },
  236. request: { opts: {} } as never,
  237. traceContext: createRootTraceContext({ sessionId: parentSessionId }),
  238. });
  239. const config = configOf(runtime);
  240. expect(config.workflowActor).toEqual({ name: "reviewer", persona: "You review." });
  241. expect(config.systemPrompt).toBeUndefined();
  242. });
  243. it("没有 workflowActor 时 systemPrompt 照旧回落到父会话配置", () => {
  244. const deps = makeDeps();
  245. const runtime = createScriptWorkflowAgentRuntime({
  246. childSessionId: createSessionId("dwf-actor-legacy"),
  247. deps: {
  248. ...deps,
  249. runtimeConfig: { ...deps.runtimeConfig, systemPrompt: "parent custom prompt" },
  250. },
  251. request: { opts: {} } as never,
  252. traceContext: createRootTraceContext({ sessionId: parentSessionId }),
  253. });
  254. expect(configOf(runtime).systemPrompt).toBe("parent custom prompt");
  255. });
  256. });
  257. /**
  258. * 动态工作流灰度门在 workflow child 上的形态(docs/dynamic-workflow/launch.md「Gray release」):
  259. * 这里**没有**第二份判定,child config 由 `...deps.runtimeConfig` 整体继承父会话的结论。
  260. * 钉住它是因为构造点用的是展开而不是逐字段枚举——将来有人改成枚举(subagent.ts 就是枚举,
  261. * 并因此漏过这个字段)时,这条用例会红。
  262. *
  263. * 三种取值都要断:父会话开着(run 只可能在开着的会话里启动)child 必须拿到全部工具;
  264. * 父会话不参与灰度(TUI / headless)同理;父会话关着时 child 也关着,这在生产中不可达
  265. * (关着就没有 CreateWorkflow,起不了 run),断它只是为了证明继承没有方向性错误。
  266. */
  267. describe("script workflow child runtime — 灰度门整体继承父会话", () => {
  268. function childRuntimeForParent(parentFlag: boolean | undefined): AgentRuntime {
  269. const deps = makeDeps();
  270. return createScriptWorkflowAgentRuntime({
  271. childSessionId: createSessionId(`dwf-actor-gray-${String(parentFlag)}`),
  272. deps: {
  273. ...deps,
  274. runtimeConfig: {
  275. ...deps.runtimeConfig,
  276. ...(parentFlag === undefined ? {} : { dynamicWorkflowEnabled: parentFlag }),
  277. },
  278. },
  279. request: { opts: {} } as never,
  280. traceContext: createRootTraceContext({ sessionId: parentSessionId }),
  281. });
  282. }
  283. it.each([
  284. { parentFlag: true, available: true },
  285. { parentFlag: undefined, available: true },
  286. { parentFlag: false, available: false },
  287. ])("父会话 dynamicWorkflowEnabled=%j", ({ parentFlag, available }) => {
  288. const runtime = childRuntimeForParent(parentFlag);
  289. expect(
  290. (runtime as unknown as { config: { dynamicWorkflowEnabled?: boolean } }).config
  291. .dynamicWorkflowEnabled,
  292. ).toBe(parentFlag);
  293. const registry = runtime.getToolRegistry();
  294. // 探针刻意用两个**只读**工具:CreateWorkflow / AmendWorkflow / SaveWorkflow /
  295. // ResumeWorkflowRun / ResolveWorkflowQuestion 在 workflow_child 里另有一道结构性禁令
  296. // (tool-allowlist.ts 的 WORKFLOW_CHILD_DISALLOWED_TOOLS),三种取值下恒为 false,
  297. // 拿它们当探针只会写出一条永远为真的假断言。
  298. expect(registry.has(LIST_WORKFLOW_RUNS_TOOL_NAME)).toBe(available);
  299. expect(registry.has(EVAL_WORKFLOW_SNIPPET_TOOL_NAME)).toBe(available);
  300. // 反向断言:门只碰工作流那几件,普通工具面在三种取值下都在。
  301. expect(registry.has("Read")).toBe(true);
  302. // 结构性禁令与灰度门互不干扰:CreateWorkflow 在 workflow_child 里恒缺席。
  303. expect(registry.has(CREATE_WORKFLOW_TOOL_NAME)).toBe(false);
  304. });
  305. });
  306. });
  307. /**
  308. * actor / script workflow child 的模型面必须和父会话**同源**(一份 model factory)。
  309. *
  310. * 事故复盘(2026-09-02 日志包):自定义 provider 起初被存成 openai-compatible,主 turn 与 actor 都
  311. * 404;用户改成 anthropic 并推送 registry 后主 turn 恢复,但两分钟后启动的 actor 仍用旧 kind——
  312. * 因为 child 拿 app 创建时冻结的配置自建了一份 registry。provider 重构后 Registry 视图是进程级的、
  313. * Model 由 factory 按创建时刻的视图造出(docs/working-memory/provider-refactor/design/registry/runtime.md),
  314. * 所以这里只剩一条要钉住:child 造 Model 走的必须是 deps 里父会话那一份 factory,且以父会话
  315. * **当前**的选择为基线。
  316. */
  317. describe("script workflow child runtime — 与父会话共享 model factory", () => {
  318. const parentSessionId = createSessionId("dwf-parent-model");
  319. let tempRoot: string;
  320. beforeEach(async () => {
  321. tempRoot = await mkdtemp(join(tmpdir(), "zcode-actor-model-"));
  322. });
  323. afterEach(async () => {
  324. await rm(tempRoot, { force: true, recursive: true });
  325. });
  326. function baseDeps(parentRuntime: AgentRuntime): ScriptWorkflowAgentRuntimeDeps {
  327. return {
  328. agentTelemetry: createModelTelemetry().agentExecution,
  329. appOptions: { env: {} },
  330. appVersion: "0.0.0-test",
  331. configResult: {
  332. config: {
  333. features: { skill: false },
  334. modelStream: { idleTimeoutMs: 0 },
  335. network: {},
  336. skillOverrides: {},
  337. skills: { enabled: false, roots: [] },
  338. },
  339. },
  340. fileSystemPort: createNodeFileSystemAdapter(),
  341. imageProcessorPort: {},
  342. logger: undefined,
  343. permissionService: new PermissionService(defaultPermissionConfig),
  344. runtime: parentRuntime,
  345. runtimeConfig: { workingDirectory: tempRoot },
  346. sessionId: parentSessionId,
  347. sessionStore: createSqliteSessionStore({ dbPath: ":memory:" }),
  348. storageRoot: tempRoot,
  349. workingDirectory: tempRoot,
  350. } as unknown as ScriptWorkflowAgentRuntimeDeps;
  351. }
  352. it("child 用 deps 里父会话的 factory 造 Model,并以父会话当前的选择为基线", async () => {
  353. const parentModelFactory = vi.fn(
  354. (target: { selection: ModelSelection }): Model => ({
  355. providerId: target.selection.providerId as Model["providerId"],
  356. modelId: target.selection.modelId as Model["modelId"],
  357. properties: {
  358. contextWindow: 200_000,
  359. inputFormat: {
  360. supportsText: true,
  361. supportsImage: false,
  362. supportsVideo: false,
  363. supportsAudio: false,
  364. supportsPdf: false,
  365. },
  366. outputFormat: { supportsText: true },
  367. supportsMidConversationSystem: false,
  368. supportsNativeWebSearch: false,
  369. supportsJsonSchemaOutput: true,
  370. supportsToolCall: true,
  371. } as unknown as Model["properties"],
  372. optionSpecs: { maxOutputTokens: { max: 4096 } },
  373. options: { maxOutputTokens: 4096 },
  374. bind() {
  375. return this;
  376. },
  377. async generateText() {
  378. return {
  379. finishReason: "stop",
  380. providerMetadata: undefined,
  381. text: "actor done",
  382. usage: { inputTokens: 3, outputTokens: 2, totalTokens: 5 },
  383. } as unknown as ModelResult;
  384. },
  385. streamText(): never {
  386. throw new Error("streamText is not part of this fixture");
  387. },
  388. }),
  389. );
  390. const parentRuntime = createTestAgentRuntime(
  391. parentSessionId,
  392. {
  393. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Highspeed" },
  394. workingDirectory: tempRoot,
  395. },
  396. {
  397. eventStore: createInMemorySessionEventStore(),
  398. fileSystemPort: createNodeFileSystemAdapter(),
  399. modelFactory: parentModelFactory as unknown as ScriptWorkflowAgentRuntimeDeps["modelFactory"],
  400. },
  401. );
  402. const deps = baseDeps(parentRuntime);
  403. deps.modelFactory = parentModelFactory as unknown as ScriptWorkflowAgentRuntimeDeps["modelFactory"];
  404. const actorRuntime = createScriptWorkflowAgentRuntime({
  405. childSessionId: createSessionId("dwf-actor-model-wiring"),
  406. deps,
  407. request: { opts: {} } as never,
  408. traceContext: createRootTraceContext({ sessionId: parentSessionId }),
  409. });
  410. expect(actorRuntime.getSessionModelSelection()).toEqual({
  411. providerId: "glm",
  412. modelId: "GLM-5.3-Highspeed",
  413. });
  414. await actorRuntime.ensureSessionPersistedForExternalActivity("workflow actor a#1@1");
  415. await actorRuntime.executeTurn("go");
  416. expect(parentModelFactory).toHaveBeenCalled();
  417. expect(
  418. parentModelFactory.mock.calls.some(
  419. ([target]) =>
  420. target.selection.providerId === "glm" && target.selection.modelId === "GLM-5.3-Highspeed",
  421. ),
  422. ).toBe(true);
  423. });
  424. it("request.opts.model 必须带 provider 段:裸模型名不再借父会话的 provider 补全", () => {
  425. const parentRuntime = createTestAgentRuntime(
  426. parentSessionId,
  427. {
  428. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Highspeed" },
  429. workingDirectory: tempRoot,
  430. },
  431. {
  432. eventStore: createInMemorySessionEventStore(),
  433. fileSystemPort: createNodeFileSystemAdapter(),
  434. },
  435. );
  436. const deps = baseDeps(parentRuntime);
  437. deps.modelFactory = createTestModelFactoryFromAdapter({
  438. async generateText() {
  439. throw new Error("not called");
  440. },
  441. });
  442. expect(() =>
  443. createScriptWorkflowAgentRuntime({
  444. childSessionId: createSessionId("dwf-actor-model-bare"),
  445. deps,
  446. request: { opts: { model: "GLM-5.3-Highspeed" } } as never,
  447. traceContext: createRootTraceContext({ sessionId: parentSessionId }),
  448. }),
  449. ).toThrow(/provider-qualified/);
  450. });
  451. });
  452. /**
  453. * docs/zcode-protocol-model-backed-control-requests.md「反向请求的会话路由与终止保证」契约 2。
  454. *
  455. * Bug 根因(2026-09-09):actor 的对外交互端口过去直接取自 `appOptions` / `deps.permissionBroker`,
  456. * 于是带着自己的 `sess_dwf-…` 去问桌面;桌面 `requireSession` 抛错、response 永不发出,
  457. * 8 个子代理在首个模型请求前挂死 80 分钟(日志里只有一条 model.request.started)。
  458. * 现在端口只能由父 runtime 铸造,路由身份恒为父会话。
  459. */
  460. describe("script workflow child runtime — 对外交互端口由父 runtime 铸造", () => {
  461. const parentSessionId = createSessionId("dwf-parent-routing");
  462. const actorSessionId = createSessionId("dwf-actor-routing-1");
  463. let tempRoot: string;
  464. let parentRuntime: AgentRuntime;
  465. let refreshes: Array<{ providerId: string; routedSessionId?: string }>;
  466. let permissionRequests: Array<{ sessionId: string; origin?: unknown }>;
  467. beforeEach(async () => {
  468. tempRoot = await mkdtemp(join(tmpdir(), "zcode-actor-routing-"));
  469. refreshes = [];
  470. permissionRequests = [];
  471. parentRuntime = createTestAgentRuntime(
  472. parentSessionId,
  473. { workingDirectory: tempRoot },
  474. {
  475. eventStore: createInMemorySessionEventStore(),
  476. fileSystemPort: createNodeFileSystemAdapter(),
  477. // 主 runtime 的端口:每次调用报自己的 sessionId;child 拿到的是父 runtime 派生的实例,
  478. // 派生层把 sessionId 改写成父会话(core 的 child-client-ports.ts)。
  479. providerRuntimeHeadersPort: {
  480. shouldRefreshBeforeModelRequest: () => true,
  481. async refreshBeforeModelRequest(input) {
  482. refreshes.push({ providerId: input.providerId, routedSessionId: input.sessionId });
  483. return { headersApplied: true };
  484. },
  485. },
  486. modelFactory: routingModelFactory,
  487. permissionBroker: {
  488. async requestPermission(request) {
  489. permissionRequests.push({ sessionId: request.sessionId, origin: request.origin });
  490. return { decision: "allow" };
  491. },
  492. },
  493. } as never,
  494. );
  495. });
  496. afterEach(async () => {
  497. await rm(tempRoot, { force: true, recursive: true });
  498. });
  499. // 真实 adapter 在每次 attempt 发出前刷新 runtime headers;这里照做,好让断言落在真实链路上
  500. // (runtime deps → 调用上下文 → 端口)。
  501. const routingModelFactory = createTestModelFactory({
  502. async generateText(_request, observation) {
  503. await observation.invocationContext?.refreshRuntimeHeadersBeforeAttempt?.({ attempt: 1 });
  504. return {
  505. finishReason: "stop",
  506. providerMetadata: undefined,
  507. text: "actor done",
  508. usage: { inputTokens: 3, outputTokens: 2, totalTokens: 5 },
  509. } as unknown as ModelResult;
  510. },
  511. });
  512. function makeActorRuntime(): AgentRuntime {
  513. const deps = {
  514. agentTelemetry: createModelTelemetry().agentExecution,
  515. appOptions: { env: process.env },
  516. appVersion: "0.0.0-test",
  517. configResult: {
  518. config: {
  519. features: { skill: false },
  520. modelStream: { idleTimeoutMs: 0 },
  521. network: {},
  522. skillOverrides: {},
  523. skills: { enabled: false, roots: [] },
  524. },
  525. },
  526. fileSystemPort: createNodeFileSystemAdapter(),
  527. imageProcessorPort: {},
  528. logger: undefined,
  529. modelFactory: routingModelFactory,
  530. permissionService: new PermissionService(defaultPermissionConfig),
  531. runtime: parentRuntime,
  532. runtimeConfig: { workingDirectory: tempRoot },
  533. sessionId: parentSessionId,
  534. sessionStore: createSqliteSessionStore({ dbPath: ":memory:" }),
  535. storageRoot: tempRoot,
  536. workingDirectory: tempRoot,
  537. } as unknown as ScriptWorkflowAgentRuntimeDeps;
  538. return createScriptWorkflowAgentRuntime({
  539. childSessionId: actorSessionId,
  540. deps,
  541. request: { opts: { agentType: "reviewer", label: "复核员" }, prompt: "go" } as never,
  542. traceContext: createRootTraceContext({ sessionId: parentSessionId }),
  543. });
  544. }
  545. it("actor 的 provider runtime headers 刷新以父会话为路由身份", async () => {
  546. const actorRuntime = makeActorRuntime();
  547. await actorRuntime.executeTurn("go");
  548. expect(refreshes.length).toBeGreaterThan(0);
  549. // 端口入参里的 sessionId 必须是父会话:桌面只订阅父 task 的会话,带子会话去问没人应答。
  550. expect(refreshes.every((entry) => entry.routedSessionId === parentSessionId)).toBe(true);
  551. });
  552. it("父 runtime 铸造的 permission broker 带父会话身份与子代理 origin", async () => {
  553. // 这正是 createScriptWorkflowAgentRuntime 装进 actor deps 的那一份(见实现里的
  554. // `...deps.runtime.createChildClientPorts(...)`)。
  555. const ports = parentRuntime.createChildClientPorts({
  556. agentId: actorSessionId,
  557. agentType: "reviewer",
  558. childSessionId: actorSessionId,
  559. description: "复核员",
  560. });
  561. await ports.permissionBroker!.requestPermission({
  562. requestId: "req-actor",
  563. sessionId: actorSessionId,
  564. traceId: createTraceId(),
  565. toolCallId: createToolCallId(),
  566. toolName: "Bash",
  567. input: {},
  568. mode: "yolo",
  569. ruleId: "rule",
  570. reason: "test",
  571. riskLevel: "low",
  572. requestedAt: new Date(0),
  573. } as never);
  574. expect(permissionRequests).toHaveLength(1);
  575. // 桌面 UI 只订阅父 task 的 sessionId;带子会话来就没人能应答。
  576. expect(permissionRequests[0]!.sessionId).toBe(parentSessionId);
  577. expect(permissionRequests[0]!.origin).toMatchObject({
  578. kind: "subagent",
  579. childSessionId: actorSessionId,
  580. parentSessionId,
  581. });
  582. });
  583. });
  584. /**
  585. * workflow 子代理跑在发起会话的权限模式上(docs/dynamic-workflow/launch.md「Permissions inside a
  586. * run」):该问时经父 runtime 派生的 broker 请求用户,origin 标注这个子代理,并镜像到父会话;
  587. * guarded 的危险命令是 user-once,拒绝时命令不执行、拒绝结果回到子代理。YOLO 不问普通工具,
  588. * AskUserQuestion 在任何模式下都问。
  589. */
  590. describe("script workflow child runtime — 子代理经父 broker 请求权限与提问", () => {
  591. const parentSessionId = createSessionId("dwf-parent-guarded");
  592. const actorSessionId = createSessionId("dwf-actor-guarded-1");
  593. let tempRoot: string;
  594. let parentRuntime: AgentRuntime;
  595. let requests: PermissionBrokerRequest[];
  596. let modelRequests: string[];
  597. let execute: ReturnType<typeof vi.fn>;
  598. /** actor 第一次模型请求发出的工具调用;默认一条危险 Bash。 */
  599. let firstToolCall: { id: string; name: string; input: Record<string, unknown> };
  600. beforeEach(async () => {
  601. tempRoot = await mkdtemp(join(tmpdir(), "zcode-actor-guarded-"));
  602. requests = [];
  603. modelRequests = [];
  604. firstToolCall = {
  605. id: "actor-guarded-rm",
  606. name: "Bash",
  607. input: { command: "rm -rf fixture-only" },
  608. };
  609. execute = vi.fn(async () => ({
  610. status: "completed" as const,
  611. stdout: { text: "executed", bytes: 8, truncated: false },
  612. stderr: { text: "", bytes: 0, truncated: false },
  613. exitCode: 0,
  614. durationMs: 1,
  615. timedOut: false,
  616. cancelled: false,
  617. startedAt: new Date(),
  618. completedAt: new Date(),
  619. }));
  620. parentRuntime = createTestAgentRuntime(
  621. parentSessionId,
  622. { workingDirectory: tempRoot, mode: "guarded" },
  623. {
  624. eventStore: createInMemorySessionEventStore(),
  625. fileSystemPort: createNodeFileSystemAdapter(),
  626. modelFactory: guardedModelFactory,
  627. permissionBroker: {
  628. async requestPermission(request: PermissionBrokerRequest) {
  629. requests.push(request);
  630. return { decision: "deny", reason: "guarded actor fixture denial" };
  631. },
  632. },
  633. } as never,
  634. );
  635. });
  636. afterEach(async () => {
  637. await rm(tempRoot, { force: true, recursive: true });
  638. });
  639. // 第一次请求发出 firstToolCall;拿到工具结果后结束。
  640. const guardedModelFactory = createTestModelFactoryFromAdapter({
  641. async generateText(request) {
  642. modelRequests.push(JSON.stringify(request));
  643. const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  644. if (modelRequests.length === 1) {
  645. return {
  646. finishReason: "tool-calls",
  647. text: "",
  648. usage,
  649. toolCalls: [firstToolCall],
  650. } as unknown as ModelResult;
  651. }
  652. return { finishReason: "stop", text: "actor done", usage } as unknown as ModelResult;
  653. },
  654. });
  655. function makeActorRuntime(
  656. subagentPermissionMode: WorkflowSubagentPermissionMode | undefined,
  657. ): AgentRuntime {
  658. const deps = {
  659. agentTelemetry: createModelTelemetry().agentExecution,
  660. appOptions: { env: process.env, executionPort: { run: execute } },
  661. appVersion: "0.0.0-test",
  662. configResult: {
  663. config: {
  664. features: { skill: false },
  665. modelStream: { idleTimeoutMs: 0 },
  666. network: {},
  667. skillOverrides: {},
  668. skills: { enabled: false, roots: [] },
  669. },
  670. },
  671. fileSystemPort: createNodeFileSystemAdapter(),
  672. imageProcessorPort: {},
  673. logger: undefined,
  674. modelFactory: guardedModelFactory,
  675. permissionService: new PermissionService(defaultPermissionConfig),
  676. runtime: parentRuntime,
  677. runtimeConfig: { workingDirectory: tempRoot, mcp: { enabled: false } },
  678. sessionId: parentSessionId,
  679. sessionStore: createSqliteSessionStore({ dbPath: ":memory:" }),
  680. storageRoot: tempRoot,
  681. workingDirectory: tempRoot,
  682. } as unknown as ScriptWorkflowAgentRuntimeDeps;
  683. // 与 create-app 的 actor 工厂同一组展开:工具面 + 权限面 + 交互归属描述。
  684. return createScriptWorkflowAgentRuntime({
  685. childSessionId: actorSessionId,
  686. configOverrides: {
  687. ...workflowActorToolPolicy(),
  688. ...workflowActorPermissionPolicy(subagentPermissionMode),
  689. },
  690. deps,
  691. interactionDescription: workflowActorInteractionDescription({
  692. actor: { siteId: "agent#1", ordinal: 0 },
  693. persona: { name: "reviewer" },
  694. }),
  695. request: { opts: {} } as never,
  696. traceContext: createRootTraceContext({ sessionId: parentSessionId }),
  697. });
  698. }
  699. it("guarded:一次 user-once 请求,父会话路由、子代理 origin;拒绝后不执行且结果回到子代理", async () => {
  700. const actorRuntime = makeActorRuntime("guarded");
  701. expect(actorRuntime.getMode()).toBe("guarded");
  702. await actorRuntime.executeTurn("go");
  703. expect(requests).toHaveLength(1);
  704. expect(requests[0]).toMatchObject({
  705. approvalMode: "user-once",
  706. sessionId: parentSessionId,
  707. toolName: "Bash",
  708. origin: {
  709. kind: "subagent",
  710. agentId: actorSessionId,
  711. childSessionId: actorSessionId,
  712. description: "reviewer (agent#1@0)",
  713. parentSessionId,
  714. },
  715. });
  716. expect(execute).not.toHaveBeenCalled();
  717. expect(modelRequests.some((request) => request.includes("guarded actor fixture denial"))).toBe(
  718. true,
  719. );
  720. // 子代理的 guarded 不改父会话的模式。
  721. expect(parentRuntime.getMode()).toBe("guarded");
  722. });
  723. it("交互事件镜像到父会话:父流里看到 PermissionRequested(带 origin)与随后的终态", async () => {
  724. // 回归(2026-09-23 实机):request 到达了 broker,但桌面只从**父会话**的实时投影生成
  725. // 确认窗;actor 的 PermissionRequested 只落在子会话,窗不出现、子代理永久等待。
  726. const parentEvents: SessionEvent[] = [];
  727. parentRuntime.subscribeEvents({
  728. onSessionEvent: (event) => {
  729. if (event.sessionId === parentSessionId) parentEvents.push(event);
  730. },
  731. });
  732. const actorRuntime = makeActorRuntime("guarded");
  733. await actorRuntime.executeTurn("go");
  734. const requested = parentEvents.filter(
  735. (event) => event.type === SessionEventType.PermissionRequested,
  736. );
  737. expect(requested).toHaveLength(1);
  738. const payload = requested[0]!.payload as Record<string, unknown>;
  739. expect(payload).toMatchObject({
  740. requestId: requests[0]!.requestId,
  741. toolName: "Bash",
  742. approvalMode: "user-once",
  743. childSessionId: actorSessionId,
  744. origin: {
  745. kind: "subagent",
  746. childSessionId: actorSessionId,
  747. description: "reviewer (agent#1@0)",
  748. parentSessionId,
  749. },
  750. });
  751. // 终态也要镜像过去,否则父投影里的待办交互永远不消失。
  752. const settled = parentEvents.filter(
  753. (event) =>
  754. event.type === SessionEventType.PermissionResolved ||
  755. event.type === SessionEventType.PermissionDenied,
  756. );
  757. expect(settled.length).toBeGreaterThan(0);
  758. expect(
  759. settled.every(
  760. (event) => (event.payload as { toolCallId?: unknown }).toolCallId === payload.toolCallId,
  761. ),
  762. ).toBe(true);
  763. // 只镜像交互:actor 的工具事件不进父会话 timeline。
  764. expect(
  765. parentEvents.some(
  766. (event) =>
  767. event.type === SessionEventType.ToolCallStarted ||
  768. event.type === SessionEventType.ToolCallResult,
  769. ),
  770. ).toBe(false);
  771. });
  772. it("停止 run(actor turn 被 abort)撤销挂起的请求:broker 收到 abort,命令不执行", async () => {
  773. const aborted = Promise.withResolvers<void>();
  774. const registered = Promise.withResolvers<void>();
  775. // 换一个永不作答、只响应 abort 的 broker:代表用户还没看到的那一个确认窗。
  776. parentRuntime = createTestAgentRuntime(
  777. parentSessionId,
  778. { workingDirectory: tempRoot, mode: "guarded" },
  779. {
  780. eventStore: createInMemorySessionEventStore(),
  781. fileSystemPort: createNodeFileSystemAdapter(),
  782. modelFactory: guardedModelFactory,
  783. permissionBroker: {
  784. requestPermission(request: PermissionBrokerRequest, options?: { signal?: AbortSignal }) {
  785. requests.push(request);
  786. registered.resolve();
  787. return new Promise((_resolve, reject) => {
  788. options?.signal?.addEventListener(
  789. "abort",
  790. () => {
  791. aborted.resolve();
  792. reject(new Error("aborted"));
  793. },
  794. { once: true },
  795. );
  796. });
  797. },
  798. },
  799. } as never,
  800. );
  801. const actorRuntime = makeActorRuntime("guarded");
  802. const controller = new AbortController();
  803. const turn = actorRuntime.executeTurn("go", undefined, { abortSignal: controller.signal });
  804. await registered.promise;
  805. controller.abort();
  806. await aborted.promise;
  807. await turn.catch(() => undefined);
  808. expect(requests).toHaveLength(1);
  809. expect(execute).not.toHaveBeenCalled();
  810. });
  811. it("YOLO run(键缺席):子代理不问,命令照常执行", async () => {
  812. const actorRuntime = makeActorRuntime(undefined);
  813. expect(actorRuntime.getMode()).toBe("yolo");
  814. await actorRuntime.executeTurn("go");
  815. expect(requests).toHaveLength(0);
  816. expect(execute).toHaveBeenCalledTimes(1);
  817. });
  818. it("build run:子代理的普通 Bash 也经父会话请求(非 user-once),并镜像到父会话", async () => {
  819. const parentEvents: SessionEvent[] = [];
  820. parentRuntime.subscribeEvents({
  821. onSessionEvent: (event) => {
  822. if (event.sessionId === parentSessionId) parentEvents.push(event);
  823. },
  824. });
  825. const actorRuntime = makeActorRuntime("build");
  826. expect(actorRuntime.getMode()).toBe("build");
  827. await actorRuntime.executeTurn("go");
  828. expect(requests).toHaveLength(1);
  829. expect(requests[0]!.approvalMode).not.toBe("user-once");
  830. expect(requests[0]).toMatchObject({
  831. sessionId: parentSessionId,
  832. toolName: "Bash",
  833. origin: { kind: "subagent", description: "reviewer (agent#1@0)" },
  834. });
  835. expect(execute).not.toHaveBeenCalled();
  836. expect(parentEvents.some((event) => event.type === SessionEventType.PermissionRequested)).toBe(
  837. true,
  838. );
  839. });
  840. it("AskUserQuestion:子代理的提问经父会话送达,父流里有带 origin 的 PermissionRequested", async () => {
  841. firstToolCall = {
  842. id: "actor-question",
  843. name: "AskUserQuestion",
  844. input: {
  845. questions: [
  846. {
  847. question: "Which file should I review first?",
  848. header: "Order",
  849. multiSelect: false,
  850. options: [
  851. { label: "a.ts", description: "The entry point" },
  852. { label: "b.ts", description: "The helper" },
  853. ],
  854. },
  855. ],
  856. },
  857. };
  858. const parentEvents: SessionEvent[] = [];
  859. parentRuntime.subscribeEvents({
  860. onSessionEvent: (event) => {
  861. if (event.sessionId === parentSessionId) parentEvents.push(event);
  862. },
  863. });
  864. // YOLO 也问:AskUserQuestion 在任何模式下都要用户作答。
  865. const actorRuntime = makeActorRuntime("yolo");
  866. await actorRuntime.executeTurn("go");
  867. expect(requests).toHaveLength(1);
  868. expect(requests[0]).toMatchObject({
  869. sessionId: parentSessionId,
  870. toolName: "AskUserQuestion",
  871. origin: { kind: "subagent", childSessionId: actorSessionId },
  872. });
  873. const requested = parentEvents.filter(
  874. (event) => event.type === SessionEventType.PermissionRequested,
  875. );
  876. expect(requested).toHaveLength(1);
  877. expect(requested[0]!.payload).toMatchObject({
  878. toolName: "AskUserQuestion",
  879. origin: { kind: "subagent", description: "reviewer (agent#1@0)" },
  880. });
  881. });
  882. });
  883. describe("workflow actor permission — run 记下的模式读回", () => {
  884. it("认识的模式原样读回;缺席、未知值与 plan 读成缺席(= YOLO)", () => {
  885. for (const mode of ["build", "edit", "yolo", "guarded", "auto"] as const) {
  886. expect(parseWorkflowSubagentPermissionMode(mode)).toBe(mode);
  887. expect(workflowActorPermissionPolicy(mode)).toEqual({ mode });
  888. }
  889. for (const raw of [undefined, "plan", "full-auto-2027", 42]) {
  890. expect(parseWorkflowSubagentPermissionMode(raw)).toBeUndefined();
  891. }
  892. expect(workflowActorPermissionPolicy(undefined)).toEqual({ mode: "yolo" });
  893. });
  894. });
  895. /**
  896. * 动态工作流子代理的 Browser Use(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md
  897. * 「Subagent sessions」)。
  898. *
  899. * Bug 根因(2026-09-30):actor 的 `mcp__node_repl__js` 带着自己的 `sess_dwf-…` 到达协议 broker,
  900. * `requireSession` 只认客户端会话,每个 `agent.browsers.*` 都以 `Session is not active` 失败;actor
  901. * runtime 也没有 browser 端口,turn end / 关闭从不通知桌面。现在由父端口派生子端口:tab 归属是
  902. * actor 自己的 sessionId,workspace / clientMode 取父会话,关闭时 closeTabs 并撤销登记。
  903. */
  904. describe("script workflow child runtime — 子代理的 Browser Use", () => {
  905. const parentSessionId = createSessionId("dwf-parent-browser");
  906. const actorSessionId = createSessionId("dwf-dwfrun-b-actor_1_1");
  907. let tempRoot: string;
  908. let parentRuntime: AgentRuntime;
  909. beforeEach(async () => {
  910. tempRoot = await mkdtemp(join(tmpdir(), "zcode-actor-browser-"));
  911. parentRuntime = createTestAgentRuntime(
  912. parentSessionId,
  913. { workingDirectory: tempRoot },
  914. {
  915. eventStore: createInMemorySessionEventStore(),
  916. fileSystemPort: createNodeFileSystemAdapter(),
  917. modelFactory: browserModelFactory,
  918. },
  919. );
  920. });
  921. afterEach(async () => {
  922. await rm(tempRoot, { force: true, recursive: true });
  923. });
  924. const browserModelFactory = createTestModelFactoryFromAdapter({
  925. async generateText() {
  926. return {
  927. finishReason: "stop",
  928. providerMetadata: undefined,
  929. text: "actor done",
  930. usage: { inputTokens: 3, outputTokens: 2, totalTokens: 5 },
  931. } as unknown as ModelResult;
  932. },
  933. });
  934. /** 协议 server 的 context:只登记父会话(客户端认识的唯一会话)。 */
  935. function makeProtocolContext(requestClient: ReturnType<typeof vi.fn>) {
  936. return {
  937. requestClient,
  938. sessions: new Map([
  939. [
  940. parentSessionId,
  941. {
  942. deliveryKind: "desktop-continuous",
  943. workspace: { workspaceKey: "/repo", workspacePath: "/repo" },
  944. },
  945. ],
  946. ]),
  947. } as unknown as ZCodeProtocolAgentServerContext;
  948. }
  949. function makeActorRuntime(
  950. browserControlPort: Parameters<
  951. typeof createScriptWorkflowAgentRuntime
  952. >[0]["browserControlPort"],
  953. ): AgentRuntime {
  954. const deps = {
  955. agentTelemetry: createModelTelemetry().agentExecution,
  956. appOptions: { env: process.env },
  957. appVersion: "0.0.0-test",
  958. configResult: {
  959. config: {
  960. features: { skill: false },
  961. modelStream: { idleTimeoutMs: 0 },
  962. network: {},
  963. skillOverrides: {},
  964. skills: { enabled: false, roots: [] },
  965. },
  966. },
  967. fileSystemPort: createNodeFileSystemAdapter(),
  968. imageProcessorPort: {},
  969. logger: undefined,
  970. modelFactory: browserModelFactory,
  971. permissionService: new PermissionService(defaultPermissionConfig),
  972. pluginSkillRoots: [],
  973. runtime: parentRuntime,
  974. runtimeConfig: {
  975. workingDirectory: tempRoot,
  976. runtimeFeatures: { browserUse: true },
  977. },
  978. sessionId: parentSessionId,
  979. sessionStore: createSqliteSessionStore({ dbPath: ":memory:" }),
  980. storageRoot: tempRoot,
  981. workingDirectory: tempRoot,
  982. } as unknown as ScriptWorkflowAgentRuntimeDeps;
  983. return createScriptWorkflowAgentRuntime({
  984. childSessionId: actorSessionId,
  985. deps,
  986. request: { opts: {} } as never,
  987. traceContext: createRootTraceContext({ sessionId: parentSessionId }),
  988. ...(browserControlPort === undefined ? {} : { browserControlPort }),
  989. });
  990. }
  991. function sentCommands(requestClient: ReturnType<typeof vi.fn>) {
  992. return requestClient.mock.calls.map((call) => {
  993. const params = call[1] as {
  994. command?: Record<string, unknown>;
  995. sessionId: string;
  996. workspaceKey: string;
  997. };
  998. return {
  999. command: params.command,
  1000. sessionId: params.sessionId,
  1001. workspaceKey: params.workspaceKey,
  1002. };
  1003. });
  1004. }
  1005. it("actor 经 node_repl 的浏览器请求用自己的 sessionId,workspace 取父会话;turn end 与关闭都到达桌面", async () => {
  1006. const requestClient = vi.fn(async () => ({ ok: true, elapsedMs: 0 }));
  1007. const context = makeProtocolContext(requestClient);
  1008. // 生产里有两个实例:app 的 runtime 端口(传给工厂的父端口)与进程级 node_repl broker 用的那个。
  1009. const appPort = createProtocolBrowserControlBroker(context);
  1010. const nodeReplPort = createProtocolBrowserControlBroker(context);
  1011. const actorRuntime = makeActorRuntime(appPort);
  1012. // actor 的 `mcp__node_repl__js` 最终以 actor 的 session_id 调到进程级实例。
  1013. await expect(
  1014. nodeReplPort.execute({
  1015. browserId: "iab-1",
  1016. browserGeneration: 7,
  1017. sessionId: actorSessionId,
  1018. command: { method: "newTab" },
  1019. }),
  1020. ).resolves.toMatchObject({ ok: true });
  1021. await actorRuntime.executeTurn("go");
  1022. await actorRuntime.closeBrowserSession();
  1023. expect(sentCommands(requestClient)).toEqual([
  1024. { command: { method: "newTab" }, sessionId: actorSessionId, workspaceKey: "/repo" },
  1025. {
  1026. command: expect.objectContaining({ method: "turnEnded" }),
  1027. sessionId: actorSessionId,
  1028. workspaceKey: "/repo",
  1029. },
  1030. {
  1031. command: { method: "closeSession", closeTabs: true },
  1032. sessionId: actorSessionId,
  1033. workspaceKey: "/repo",
  1034. },
  1035. ]);
  1036. // 关闭即撤销登记:之后同一 id 与未登记的会话一样被拒。
  1037. await expect(nodeReplPort.list({ sessionId: actorSessionId })).rejects.toThrow(
  1038. `Session is not active: ${actorSessionId}`,
  1039. );
  1040. });
  1041. it("不传父端口(legacy Workflow child):actor 没有 Browser 登记,关闭不发任何浏览器请求", async () => {
  1042. const requestClient = vi.fn(async () => ({ ok: true, elapsedMs: 0 }));
  1043. const nodeReplPort = createProtocolBrowserControlBroker(makeProtocolContext(requestClient));
  1044. const actorRuntime = makeActorRuntime(undefined);
  1045. await expect(nodeReplPort.list({ sessionId: actorSessionId })).rejects.toThrow(
  1046. `Session is not active: ${actorSessionId}`,
  1047. );
  1048. await actorRuntime.executeTurn("go");
  1049. await actorRuntime.closeBrowserSession();
  1050. expect(requestClient).not.toHaveBeenCalled();
  1051. });
  1052. it("端口没有 forChildSession(CLI headless CDP):actor 直接用父端口,关闭时关自己的 session", async () => {
  1053. const closed: string[] = [];
  1054. const port = {
  1055. list: vi.fn(async () => []),
  1056. execute: vi.fn(async () => ({ ok: true, elapsedMs: 0 })),
  1057. closeSession: vi.fn(async (input: { sessionId: string }) => {
  1058. closed.push(input.sessionId);
  1059. }),
  1060. };
  1061. const actorRuntime = makeActorRuntime(port);
  1062. await actorRuntime.closeBrowserSession();
  1063. expect(closed).toEqual([actorSessionId]);
  1064. });
  1065. });
  1066. describe("script workflow child runtime — 子代理的技能清单", () => {
  1067. const PACKAGES_ROOT = fileURLToPath(new URL("../../", import.meta.url));
  1068. let tempRoot: string;
  1069. beforeEach(async () => {
  1070. tempRoot = await mkdtemp(join(tmpdir(), "zcode-actor-skills-"));
  1071. });
  1072. afterEach(async () => {
  1073. await rm(tempRoot, { force: true, recursive: true });
  1074. });
  1075. function skillDeps(input: { pluginSkillRoots: SkillRoot[] }) {
  1076. return {
  1077. appOptions: { env: process.env },
  1078. configResult: {
  1079. config: {
  1080. features: { skill: true },
  1081. skillOverrides: {},
  1082. skills: { enabled: true, roots: [join(tempRoot, "configured")] },
  1083. },
  1084. },
  1085. pluginSkillRoots: input.pluginSkillRoots,
  1086. } as unknown as ScriptWorkflowAgentRuntimeDeps;
  1087. }
  1088. // Bug 根因(2026-09-30):child 自己造 skill adapter 时只带了用户配置的 roots,插件技能根
  1089. // (browser-use 的 control-browser 等)是后来才加到主会话那一份上的,child 这边漂掉了。
  1090. it("插件技能根与用户配置根都在:actor 看得见 browser-use 的 control-browser", async () => {
  1091. await mkdir(join(tempRoot, "configured", "house-style"), { recursive: true });
  1092. await writeFile(
  1093. join(tempRoot, "configured", "house-style", "SKILL.md"),
  1094. "---\nname: house-style\ndescription: House style.\n---\n\nBody.\n",
  1095. );
  1096. const port = createWorkflowChildSkillPort(
  1097. skillDeps({
  1098. pluginSkillRoots: [
  1099. {
  1100. path: join(PACKAGES_ROOT, "browser-use-plugin", "skills"),
  1101. priority: 1_000,
  1102. scope: "system",
  1103. source: "plugin",
  1104. pluginId: "browser-use@zcode-plugins-official",
  1105. },
  1106. ],
  1107. }),
  1108. );
  1109. const outcome = await port!.discoverSkills({ workingDirectory: tempRoot });
  1110. const names = outcome.skills.map((skill) => skill.name);
  1111. expect(names).toEqual(expect.arrayContaining(["control-browser", "house-style"]));
  1112. // 捆绑的 dynamic-workflows 技能不给子代理:它不能起工作流。
  1113. expect(names).not.toContain("dynamic-workflows");
  1114. });
  1115. it("技能总开关关闭时没有 skill 端口", () => {
  1116. const deps = skillDeps({ pluginSkillRoots: [] });
  1117. (deps.configResult.config.features as { skill: boolean }).skill = false;
  1118. expect(createWorkflowChildSkillPort(deps)).toBeUndefined();
  1119. });
  1120. });