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

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