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

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