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

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