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

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