create-workflow-permission.test.ts 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. import { mkdtempSync, readFileSync, rmSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterAll, describe, expect, it, vi } from "vitest";
  5. import {
  6. HookEventName,
  7. SessionEventType,
  8. createRootTraceContext,
  9. createSessionId,
  10. createToolCallId,
  11. createTurnId,
  12. type CollaborationMode,
  13. type CreateWorkflowOutput,
  14. type DynamicWorkflowRunPort,
  15. type DynamicWorkflowRunSubmitRequest,
  16. type ModelCatalogEntry,
  17. type ModelCatalogPort,
  18. type PermissionBrokerPort,
  19. type PermissionBrokerRequest,
  20. type PermissionRequestedPayload,
  21. type SessionEvent,
  22. type SessionStorePort,
  23. type ToolExecutionResult,
  24. } from "@zcode/contracts";
  25. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  26. import { createToolExecutor } from "../src/tool/executor.js";
  27. import { createWorkflowToolEntry } from "../src/tool/handlers/create-workflow.js";
  28. import { createToolRegistry } from "../src/tool/registry.js";
  29. import type { HookRunner } from "../src/hooks/index.js";
  30. import type { ToolEntry } from "../src/tool/types.js";
  31. // 统计真实编译次数,让"把 gate 前分析折叠进 handler 自身分析"的记忆槽变得可断言。
  32. // 用 importOriginal 保持分析本身是真的——下面的 display 断言依赖真实因果图。
  33. const { analyzedScripts } = vi.hoisted(() => ({ analyzedScripts: [] as string[] }));
  34. vi.mock("@zcode/dynamic-workflow", async (importOriginal) => {
  35. const actual = await importOriginal<typeof import("@zcode/dynamic-workflow")>();
  36. return {
  37. ...actual,
  38. analyzeWorkflowScript: (script: string) => {
  39. analyzedScripts.push(script);
  40. return actual.analyzeWorkflowScript(script);
  41. },
  42. };
  43. });
  44. // 记忆槽是单槽、按脚本原文取键,所以每个用例用自己的脚本;否则上一个用例存下的分析
  45. // 会直接满足下一个用例的断言。
  46. function cleanScript(actor: string): string {
  47. return [
  48. "interface R { done: boolean }",
  49. `const r = await agent("${actor}").ask<R>("do");`,
  50. "return r.done;",
  51. ].join("\n");
  52. }
  53. /** 分析器语料里的脚本(与 create-workflow-tool.test.ts 同一份 corpus、同一条读法)。 */
  54. function fixture(name: string): string {
  55. return readFileSync(
  56. new URL(`../../dynamic-workflow/tests/graphs/${name}`, import.meta.url),
  57. "utf8",
  58. );
  59. }
  60. const BROKEN_SCRIPT = 'const x: number = "s";';
  61. // 每次 CreateWorkflow 调用都会把脚本落成 `<cwd>/.zcode/workflow-drafts/` 下的草稿(编不过也写)。
  62. // executor 缺省的工作目录是 ".",会解析到 vitest 进程的 cwd——也就是本包目录——于是每跑一遍
  63. // 就往源码树里漏几十个草稿(该目录自带 `*` 的 .gitignore,git status 看不见)。所以每个调用都
  64. // 落在这个临时目录里,跑完删掉。
  65. const TEST_CWD = mkdtempSync(join(tmpdir(), "zcode-create-workflow-permission-"));
  66. afterAll(() => {
  67. rmSync(TEST_CWD, { recursive: true, force: true });
  68. });
  69. interface RunOptions {
  70. broker?: PermissionBrokerPort;
  71. dynamicWorkflowRunPort?: DynamicWorkflowRunPort;
  72. entry?: ToolEntry;
  73. hookRunner?: HookRunner;
  74. /** 工具输入里的并发上界(模型面字段 `max_concurrency`)。 */
  75. maxConcurrency?: number;
  76. /** 宿主的模型目录;缺席即「这台机器不能选子代理模型」。 */
  77. modelCatalogPort?: ModelCatalogPort;
  78. mode?: CollaborationMode;
  79. /** 工具输入里的子代理模型(模型面字段 `subagent_model`),按用户说的原样传。 */
  80. subagentModel?: string;
  81. name: string;
  82. /** 跨调用共享的权限服务实例(会话免确认的载体,见第 7 轮用例)。 */
  83. permissionService?: PermissionService;
  84. script: string;
  85. /** session store 桩:用来断言会话授权绝不落到项目级规则。 */
  86. sessionStore?: SessionStorePort;
  87. /** 工具输入里的可选展示名(`options.name` 已被会话/调用 id 占用)。 */
  88. workflowName?: string;
  89. workingDirectory?: string;
  90. }
  91. interface RunOutcome {
  92. brokerRequests: PermissionBrokerRequest[];
  93. events: SessionEvent[];
  94. permissionRequested: PermissionRequestedPayload[];
  95. result: ToolExecutionResult;
  96. }
  97. /**
  98. * 记录 submit 请求的桩端口。只实现 submit(handler 唯一触达的方法),其余方法在被调用时
  99. * 抛错——本文件测的是提交路径,任何对 getTask/cancel 的触达都说明接线跑偏了。
  100. *
  101. * `defaultConcurrency` 缺省不提供端口的 `defaultConcurrency`:那正是「老宿主的端口没有这个方法」的形状,
  102. * 也是绝大多数用例不该关心并发的形状。
  103. */
  104. function stubRunPort(
  105. runId: string,
  106. defaultConcurrency?: number,
  107. ): {
  108. port: DynamicWorkflowRunPort;
  109. submits: DynamicWorkflowRunSubmitRequest[];
  110. } {
  111. const submits: DynamicWorkflowRunSubmitRequest[] = [];
  112. const unreachable = (name: string) => () => {
  113. throw new Error(`stubRunPort.${name} 不应被 CreateWorkflow handler 触及`);
  114. };
  115. return {
  116. port: {
  117. async submit(request) {
  118. submits.push(request);
  119. return { ok: true, runId };
  120. },
  121. ...(defaultConcurrency === undefined ? {} : { defaultConcurrency: () => defaultConcurrency }),
  122. getTask: unreachable("getTask"),
  123. waitForTask: unreachable("waitForTask"),
  124. cancel: unreachable("cancel"),
  125. listEvents: unreachable("listEvents"),
  126. } as unknown as DynamicWorkflowRunPort,
  127. submits,
  128. };
  129. }
  130. async function run(options: RunOptions): Promise<RunOutcome> {
  131. const sessionId = createSessionId(options.name);
  132. const turnId = createTurnId(options.name);
  133. const traceContext = createRootTraceContext({ sessionId, turnId });
  134. const events: SessionEvent[] = [];
  135. const brokerRequests: PermissionBrokerRequest[] = [];
  136. const permissionBroker: PermissionBrokerPort = {
  137. async requestPermission(request, requestOptions) {
  138. brokerRequests.push(request);
  139. return (
  140. options.broker?.requestPermission(request, requestOptions) ?? { decision: "allow" as const }
  141. );
  142. },
  143. };
  144. const registry = createToolRegistry();
  145. registry.register(options.entry ?? createWorkflowToolEntry);
  146. const executor = createToolExecutor({
  147. emitEvent: async (event) => {
  148. events.push(event);
  149. },
  150. ...(options.dynamicWorkflowRunPort
  151. ? { dynamicWorkflowRunPort: options.dynamicWorkflowRunPort }
  152. : {}),
  153. ...(options.hookRunner ? { hookRunner: options.hookRunner } : {}),
  154. ...(options.modelCatalogPort ? { modelCatalogPort: options.modelCatalogPort } : {}),
  155. mode: options.mode ?? "build",
  156. permissionBroker,
  157. permissionService: options.permissionService ?? new PermissionService(defaultPermissionConfig),
  158. registry,
  159. sessionId,
  160. ...(options.sessionStore ? { sessionStore: options.sessionStore } : {}),
  161. turnId,
  162. traceContext,
  163. workingDirectory: options.workingDirectory ?? TEST_CWD,
  164. });
  165. const result = await executor.execute(
  166. {
  167. id: createToolCallId(options.name),
  168. input: {
  169. script: options.script,
  170. ...(options.workflowName === undefined ? {} : { name: options.workflowName }),
  171. ...(options.maxConcurrency === undefined
  172. ? {}
  173. : { max_concurrency: options.maxConcurrency }),
  174. ...(options.subagentModel === undefined ? {} : { subagent_model: options.subagentModel }),
  175. },
  176. name: "CreateWorkflow",
  177. },
  178. { traceContext },
  179. );
  180. return {
  181. brokerRequests,
  182. events,
  183. permissionRequested: events
  184. .filter((event) => event.type === SessionEventType.PermissionRequested)
  185. .map((event) => event.payload as PermissionRequestedPayload),
  186. result,
  187. };
  188. }
  189. describe("CreateWorkflow run confirmation", () => {
  190. it("asks with a causality-graph preview and the session-scoped always-allow policy for a clean script", async () => {
  191. const script = cleanScript("preview");
  192. analyzedScripts.length = 0;
  193. const outcome = await run({ name: "create-workflow-ask", script });
  194. expect(outcome.permissionRequested).toHaveLength(1);
  195. const payload = outcome.permissionRequested[0]!;
  196. // 第 7 轮:项目级 always allow 仍被裁掉,换成会话作用域的免确认选项。
  197. expect(payload.optionsPolicy).toBe("session-always-allow");
  198. expect(payload.display?.kind).toBe("create_workflow");
  199. const display = payload.display as { causalityGraph?: { steps: unknown[] }; ok?: boolean };
  200. expect(display.ok).toBe(true);
  201. expect(display.causalityGraph?.steps).toHaveLength(1);
  202. // broker 请求同样要带上策略:legacy 反向 RPC 自己合成选项列表,不带就仍会给出
  203. // "始终允许本项目"。
  204. expect(outcome.brokerRequests).toHaveLength(1);
  205. expect(outcome.brokerRequests[0]!.optionsPolicy).toBe("session-always-allow");
  206. expect(outcome.result.success).toBe(true);
  207. const output = outcome.result.output as CreateWorkflowOutput;
  208. expect(output.ok).toBe(true);
  209. expect(output.causalityGraph?.steps).toHaveLength(1);
  210. // gate 与 handler 共用一次编译。
  211. expect(analyzedScripts.filter((entry) => entry === script)).toHaveLength(1);
  212. });
  213. it("skips the confirmation for a script that does not typecheck and returns diagnostics", async () => {
  214. const outcome = await run({ name: "create-workflow-broken", script: BROKEN_SCRIPT });
  215. expect(outcome.permissionRequested).toHaveLength(0);
  216. expect(outcome.events.map((event) => event.type)).toEqual([
  217. SessionEventType.ToolCallStarted,
  218. SessionEventType.ToolCallResult,
  219. ]);
  220. expect(outcome.result.success).toBe(true);
  221. const output = outcome.result.output as CreateWorkflowOutput;
  222. expect(output.ok).toBe(false);
  223. expect(output.diagnostics.length).toBeGreaterThan(0);
  224. expect(output.causalityGraph).toBeUndefined();
  225. });
  226. // 第 2 轮用户复议:workflow 是一大块执行 + 模型调用,任何模式都要问。yolo 的直通
  227. // 放行和 plan 的 readOnly 放行都压不过 alwaysAsk。
  228. for (const mode of ["yolo", "plan", "edit"] as const) {
  229. it(`${mode} 模式同样弹窗并携带预览`, async () => {
  230. const script = cleanScript(`mode-${mode}`);
  231. analyzedScripts.length = 0;
  232. const outcome = await run({ mode, name: `create-workflow-${mode}`, script });
  233. expect(outcome.permissionRequested).toHaveLength(1);
  234. const payload = outcome.permissionRequested[0]!;
  235. expect(payload.display?.kind).toBe("create_workflow");
  236. expect(payload.optionsPolicy).toBe("session-always-allow");
  237. expect(outcome.brokerRequests).toHaveLength(1);
  238. // 弹窗既然要出,gate 前分析在这些模式下当然也要跑;仍然只编译一次。
  239. expect(analyzedScripts.filter((entry_) => entry_ === script)).toHaveLength(1);
  240. expect(outcome.result.success).toBe(true);
  241. expect((outcome.result.output as CreateWorkflowOutput).ok).toBe(true);
  242. });
  243. }
  244. // 刻意保留的例外,且不分模式:编不过的脚本没有可确认的东西,直接回诊断。
  245. it("yolo 模式下坏脚本仍然不弹窗,直接回诊断", async () => {
  246. const outcome = await run({
  247. mode: "yolo",
  248. name: "create-workflow-broken-yolo",
  249. script: 'const y: number = "still broken";',
  250. });
  251. expect(outcome.permissionRequested).toHaveLength(0);
  252. expect(outcome.brokerRequests).toHaveLength(0);
  253. expect(outcome.result.success).toBe(true);
  254. const output = outcome.result.output as CreateWorkflowOutput;
  255. expect(output.ok).toBe(false);
  256. expect(output.diagnostics.length).toBeGreaterThan(0);
  257. });
  258. it("PreToolUse hook 的 allow 不能抹掉这道确认", async () => {
  259. const hookRunner: HookRunner = {
  260. async run(input) {
  261. return input.hookEventName === HookEventName.PreToolUse
  262. ? { additionalContexts: [], permissionBehavior: "allow" }
  263. : { additionalContexts: [] };
  264. },
  265. };
  266. const outcome = await run({
  267. hookRunner,
  268. mode: "yolo",
  269. name: "create-workflow-pretooluse-allow",
  270. script: cleanScript("pretooluse"),
  271. });
  272. // 对普通工具这个 hook 会把 ask 提升成 allow;alwaysAsk 的工具不受影响。
  273. expect(outcome.permissionRequested).toHaveLength(1);
  274. expect(outcome.brokerRequests).toHaveLength(1);
  275. expect(outcome.result.success).toBe(true);
  276. });
  277. it("PermissionRequest hook 仍可自动应答这道确认", async () => {
  278. const hookRunner: HookRunner = {
  279. async run(input) {
  280. return input.hookEventName === HookEventName.PermissionRequest
  281. ? {
  282. additionalContexts: [],
  283. permissionRequestResult: { behavior: "allow" },
  284. }
  285. : { additionalContexts: [] };
  286. },
  287. };
  288. const outcome = await run({
  289. // rebase 语义修正(2026-08-27):staging 引入 responder race 后 broker 请求总是与
  290. // hook 链并发发起(docs/design/v2/permission-responder-race.md),不再是"hook 先答
  291. // 则 broker 不被触达"。这里让 broker 悬置不应答,成功只能来自 hook 的自动应答,
  292. // 用例仍然证明 hook 是有效的自动化出口。
  293. broker: {
  294. requestPermission: () => new Promise<never>(() => {}),
  295. },
  296. hookRunner,
  297. name: "create-workflow-permissionrequest-hook",
  298. script: cleanScript("auto-answer"),
  299. });
  300. // 正规自动化出口:弹窗事件照常发出(UI 会看到并随 resolved 收口),
  301. // broker 请求也照常发起,但用户无须应答——hook 赢下竞速。
  302. expect(outcome.permissionRequested).toHaveLength(1);
  303. expect(outcome.brokerRequests).toHaveLength(1);
  304. expect(outcome.events.some((event) => event.type === SessionEventType.PermissionResolved)).toBe(
  305. true,
  306. );
  307. expect(outcome.result.success).toBe(true);
  308. expect((outcome.result.output as CreateWorkflowOutput).ok).toBe(true);
  309. });
  310. it("still asks, without a preview, when the approval hook throws", async () => {
  311. const entry: ToolEntry = {
  312. ...createWorkflowToolEntry,
  313. prepareApproval: () => {
  314. throw new Error("preview build failed");
  315. },
  316. };
  317. const outcome = await run({
  318. entry,
  319. name: "create-workflow-hook-throws",
  320. script: cleanScript("throws"),
  321. });
  322. expect(outcome.permissionRequested).toHaveLength(1);
  323. const payload = outcome.permissionRequested[0]!;
  324. expect(payload.display).toBeUndefined();
  325. // 策略来自工具声明而不是钩子,所以钩子抛错后它依然在。
  326. expect(payload.optionsPolicy).toBe("session-always-allow");
  327. expect(outcome.brokerRequests).toHaveLength(1);
  328. expect(outcome.result.success).toBe(true);
  329. });
  330. // 对照组:alwaysAsk 是逐工具声明的,不能顺手改掉其他工具的模式语义。
  331. // 普通只读工具在 yolo 下仍应静默放行。
  332. it("不影响其他工具:普通只读工具在 yolo 下仍静默放行", async () => {
  333. const sessionId = createSessionId("control-readonly");
  334. const turnId = createTurnId("control-readonly");
  335. const traceContext = createRootTraceContext({ sessionId, turnId });
  336. const events: SessionEvent[] = [];
  337. const requestPermission = vi.fn(async () => ({ decision: "allow" as const }));
  338. const registry = createToolRegistry();
  339. registry.register({
  340. capability: "Echo a value back without touching the outside world",
  341. metadata: {
  342. name: "ControlEcho",
  343. description: "Echo for permission-mode regression",
  344. readOnly: true,
  345. destructive: false,
  346. concurrentSafe: true,
  347. timeoutMs: 1_000,
  348. maxOutputBytes: 1_000,
  349. sideEffectScope: "none",
  350. riskLevel: "low",
  351. needsApproval: false,
  352. },
  353. handler: async (input) => input,
  354. inputSchema: { type: "object" },
  355. outputSchema: { type: "object" },
  356. permission: {
  357. permission: "read",
  358. reason: "ControlEcho has no side effects",
  359. riskLevel: "low",
  360. sideEffectScope: "none",
  361. needsApproval: false,
  362. patternSources: ["toolName"],
  363. denyPriority: "beforeAsk",
  364. },
  365. resultBudget: { maxInlineBytes: 1_000, maxModelBytes: 1_000, strategy: "truncate" },
  366. timeout: { defaultMs: 1_000, maxMs: 1_000, allowCallOverride: false },
  367. cancellation: { supported: false, cleanup: "none", userVisibleMessage: "n/a" },
  368. trace: {
  369. required: true,
  370. propagateToAdapters: false,
  371. recordInput: "summary",
  372. recordOutput: "summary",
  373. },
  374. });
  375. const executor = createToolExecutor({
  376. emitEvent: async (event) => {
  377. events.push(event);
  378. },
  379. mode: "yolo",
  380. permissionBroker: { requestPermission },
  381. permissionService: new PermissionService(defaultPermissionConfig),
  382. registry,
  383. sessionId,
  384. turnId,
  385. traceContext,
  386. });
  387. const result = await executor.execute(
  388. { id: createToolCallId("control-echo"), input: { ok: true }, name: "ControlEcho" },
  389. { traceContext },
  390. );
  391. expect(result.success).toBe(true);
  392. expect(requestPermission).not.toHaveBeenCalled();
  393. expect(events.some((event) => event.type === SessionEventType.PermissionRequested)).toBe(false);
  394. });
  395. it("returns a permission error when the confirmation is denied", async () => {
  396. const outcome = await run({
  397. broker: {
  398. async requestPermission() {
  399. return { decision: "deny", reason: "User declined to run the workflow" };
  400. },
  401. },
  402. name: "create-workflow-deny",
  403. script: cleanScript("deny"),
  404. });
  405. expect(outcome.permissionRequested).toHaveLength(1);
  406. expect(outcome.result.success).toBe(false);
  407. expect(outcome.result.error?.type).toBe("permission_denied");
  408. expect(outcome.result.error?.message).toContain("User declined to run the workflow");
  409. expect(outcome.events.some((event) => event.type === SessionEventType.ToolCallResult)).toBe(
  410. false,
  411. );
  412. });
  413. });
  414. // 会话免确认(docs/dynamic-workflow/launch.md「Always allow in this session」):broker 应答带
  415. // sessionPermissionUpdates → 同一 PermissionService 实例内后续 CreateWorkflow 不再问;
  416. // 授权纯内存、绝不落项目规则;新实例(重启 / 冷恢复 / /new)从零开始。
  417. describe("CreateWorkflow always allow in this session", () => {
  418. const sessionAllow: PermissionBrokerPort = {
  419. async requestPermission(request) {
  420. return {
  421. decision: "allow",
  422. reason: "Approved for this session",
  423. sessionPermissionUpdates: [
  424. { behavior: "allow", rules: [{ toolName: request.toolName }], type: "addRules" },
  425. ],
  426. };
  427. },
  428. };
  429. function projectStoreSpy(): { sessionStore: SessionStorePort; saves: unknown[] } {
  430. const saves: unknown[] = [];
  431. const sessionStore = {
  432. async getSession() {
  433. return { projectID: "proj-1" };
  434. },
  435. async getProjectPermission() {
  436. return null;
  437. },
  438. async saveProjectPermission(input: unknown) {
  439. saves.push(input);
  440. },
  441. } as unknown as SessionStorePort;
  442. return { sessionStore, saves };
  443. }
  444. it("第一次弹窗选会话免确认后,同一会话的第二次 CreateWorkflow 不再问,也不发 permission 事件", async () => {
  445. const permissionService = new PermissionService(defaultPermissionConfig);
  446. const { sessionStore, saves } = projectStoreSpy();
  447. const first = await run({
  448. broker: sessionAllow,
  449. name: "session-allow-first",
  450. permissionService,
  451. script: cleanScript("first"),
  452. sessionStore,
  453. });
  454. expect(first.permissionRequested).toHaveLength(1);
  455. expect(first.brokerRequests).toHaveLength(1);
  456. expect(first.result.success).toBe(true);
  457. // 脚本不同也免确认:授权的是这个工具,不是某一段脚本。
  458. const second = await run({
  459. broker: {
  460. async requestPermission() {
  461. throw new Error("第二次不该再向 broker 要确认");
  462. },
  463. },
  464. mode: "plan",
  465. name: "session-allow-second",
  466. permissionService,
  467. script: cleanScript("second"),
  468. sessionStore,
  469. });
  470. expect(second.permissionRequested).toHaveLength(0);
  471. expect(second.brokerRequests).toHaveLength(0);
  472. expect(second.events.map((event) => event.type)).toEqual([
  473. SessionEventType.ToolCallStarted,
  474. SessionEventType.ToolCallResult,
  475. ]);
  476. expect(second.result.success).toBe(true);
  477. expect((second.result.output as CreateWorkflowOutput).ok).toBe(true);
  478. // 会话授权绝不落项目级规则。
  479. expect(saves).toHaveLength(0);
  480. });
  481. it("授权不跨 PermissionService 实例:新实例(重启 / 冷恢复)第一次照常弹窗", async () => {
  482. const granted = new PermissionService(defaultPermissionConfig);
  483. await run({
  484. broker: sessionAllow,
  485. name: "session-allow-restart-a",
  486. permissionService: granted,
  487. script: cleanScript("restart-a"),
  488. });
  489. const fresh = await run({
  490. name: "session-allow-restart-b",
  491. permissionService: new PermissionService(defaultPermissionConfig),
  492. script: cleanScript("restart-b"),
  493. });
  494. expect(fresh.permissionRequested).toHaveLength(1);
  495. expect(fresh.brokerRequests).toHaveLength(1);
  496. });
  497. it("坏脚本在授权后仍走诊断路径(gate 之前就 proceed,与授权无关)", async () => {
  498. const permissionService = new PermissionService(defaultPermissionConfig);
  499. await run({
  500. broker: sessionAllow,
  501. name: "session-allow-broken-a",
  502. permissionService,
  503. script: cleanScript("broken-a"),
  504. });
  505. const outcome = await run({
  506. name: "session-allow-broken-b",
  507. permissionService,
  508. script: BROKEN_SCRIPT,
  509. });
  510. expect(outcome.permissionRequested).toHaveLength(0);
  511. expect((outcome.result.output as CreateWorkflowOutput).ok).toBe(false);
  512. });
  513. });
  514. // Refine 应答(docs/dynamic-workflow/launch.md「Refine」):deny + workflow_refine_feedback 的
  515. // 反馈要升级为 followUpUserInput(steer 成真实 user message),tool_result 只留桥接文案。
  516. describe("CreateWorkflow Refine feedback", () => {
  517. it("Refine deny 把反馈升级为 followUpUserInput,tool_result 换桥接文案", async () => {
  518. const { port, submits } = stubRunPort("dwfrun-refine");
  519. const outcome = await run({
  520. broker: {
  521. async requestPermission() {
  522. return {
  523. decision: "deny",
  524. reason: "只保留三个 finder,去掉 verify 阶段",
  525. reasonSource: "workflow_refine_feedback",
  526. };
  527. },
  528. },
  529. dynamicWorkflowRunPort: port,
  530. name: "create-workflow-refine",
  531. script: cleanScript("refine"),
  532. });
  533. expect(outcome.result.success).toBe(false);
  534. expect(outcome.result.error?.type).toBe("permission_denied");
  535. // 反馈全文既在 error.message(errors.ts 对该 source 不截断)也在 followUpUserInput。
  536. expect(outcome.result.error?.reasonSource).toBe("workflow_refine_feedback");
  537. expect(outcome.result.error?.message).toBe("只保留三个 finder,去掉 verify 阶段");
  538. expect(outcome.result.followUpUserInput).toEqual({
  539. input: "只保留三个 finder,去掉 verify 阶段",
  540. reasonSource: "workflow_refine_feedback",
  541. });
  542. // 桥接文案不承诺反馈一定跟随(steer 可能被拒),只表达未获批准。
  543. expect(outcome.result.modelContent).toBe("The workflow run was not approved by the user.");
  544. // Refine 是拒绝:端口绝不能被触达。
  545. expect(submits).toHaveLength(0);
  546. // Refine 不停 turn:反馈在同一 turn 内引导模型修订重提。
  547. expect(outcome.result.turnControl).toBeUndefined();
  548. });
  549. it("普通 deny 不带 followUpUserInput,也不换桥接文案", async () => {
  550. const outcome = await run({
  551. broker: {
  552. async requestPermission() {
  553. return { decision: "deny", reason: "User declined to run the workflow" };
  554. },
  555. },
  556. name: "create-workflow-plain-deny",
  557. script: cleanScript("plain-deny"),
  558. });
  559. expect(outcome.result.success).toBe(false);
  560. expect(outcome.result.followUpUserInput).toBeUndefined();
  561. expect(outcome.result.modelContent).toBeUndefined();
  562. });
  563. it("空白反馈不升级(broker 不该发出,但 turn-control 兜底 trim)", async () => {
  564. const outcome = await run({
  565. broker: {
  566. async requestPermission() {
  567. return {
  568. decision: "deny",
  569. reason: " ",
  570. reasonSource: "workflow_refine_feedback",
  571. };
  572. },
  573. },
  574. name: "create-workflow-blank-refine",
  575. script: cleanScript("blank-refine"),
  576. });
  577. expect(outcome.result.followUpUserInput).toBeUndefined();
  578. });
  579. // 升级按 toolName 键入:其他工具的 deny 即便伪造该 source 也不得变成用户消息。
  580. it("非 CreateWorkflow 工具带该 source 的 deny 不被升级", async () => {
  581. const sessionId = createSessionId("refine-other-tool");
  582. const turnId = createTurnId("refine-other-tool");
  583. const traceContext = createRootTraceContext({ sessionId, turnId });
  584. const registry = createToolRegistry();
  585. registry.register({
  586. capability: "Write a marker file",
  587. metadata: {
  588. name: "ControlWrite",
  589. description: "Ask-gated control tool for refine-source regression",
  590. readOnly: false,
  591. destructive: false,
  592. concurrentSafe: true,
  593. timeoutMs: 1_000,
  594. maxOutputBytes: 1_000,
  595. sideEffectScope: "workspace",
  596. riskLevel: "high",
  597. needsApproval: true,
  598. },
  599. handler: async (input) => input,
  600. inputSchema: { type: "object" },
  601. outputSchema: { type: "object" },
  602. permission: {
  603. permission: "write",
  604. reason: "ControlWrite mutates the workspace",
  605. riskLevel: "high",
  606. sideEffectScope: "workspace",
  607. needsApproval: true,
  608. patternSources: ["toolName"],
  609. denyPriority: "beforeAsk",
  610. },
  611. resultBudget: { maxInlineBytes: 1_000, maxModelBytes: 1_000, strategy: "truncate" },
  612. timeout: { defaultMs: 1_000, maxMs: 1_000, allowCallOverride: false },
  613. cancellation: { supported: false, cleanup: "none", userVisibleMessage: "n/a" },
  614. trace: {
  615. required: true,
  616. propagateToAdapters: false,
  617. recordInput: "summary",
  618. recordOutput: "summary",
  619. },
  620. });
  621. const executor = createToolExecutor({
  622. emitEvent: async () => {},
  623. mode: "build",
  624. permissionBroker: {
  625. async requestPermission() {
  626. return {
  627. decision: "deny" as const,
  628. reason: "spoofed refine feedback",
  629. reasonSource: "workflow_refine_feedback" as const,
  630. };
  631. },
  632. },
  633. permissionService: new PermissionService(defaultPermissionConfig),
  634. registry,
  635. sessionId,
  636. turnId,
  637. traceContext,
  638. });
  639. const result = await executor.execute(
  640. { id: createToolCallId("control-write"), input: { ok: true }, name: "ControlWrite" },
  641. { traceContext },
  642. );
  643. expect(result.success).toBe(false);
  644. expect(result.followUpUserInput).toBeUndefined();
  645. });
  646. });
  647. // 引擎接线后的提交路径。gate 的 Allow 之后 handler 不再回占位,而是经窄端口启动一个后台 run。
  648. describe("CreateWorkflow backgrounded submit", () => {
  649. it("Allow 之后经端口启动 run,输出 backgrounded + runId 并告知模型等通知", async () => {
  650. const { port, submits } = stubRunPort("dwfrun-alpha");
  651. const script = cleanScript("submit-allow");
  652. const outcome = await run({
  653. dynamicWorkflowRunPort: port,
  654. name: "create-workflow-submit-allow",
  655. script,
  656. workingDirectory: TEST_CWD,
  657. });
  658. // 弹窗照旧:提交路径挂在 Allow 之后,不绕过确认。
  659. expect(outcome.permissionRequested).toHaveLength(1);
  660. expect(outcome.result.success).toBe(true);
  661. const output = outcome.result.output as CreateWorkflowOutput;
  662. expect(output.ok).toBe(true);
  663. expect(output.status).toBe("backgrounded");
  664. // runId ≡ backgroundTaskId ≡ workId:三条路径同一个键。
  665. expect(output.backgroundTaskId).toBe("dwfrun-alpha");
  666. // 因果图仍随输出走(工具卡的入口与摘要靠它)。
  667. expect(output.causalityGraph?.steps).toHaveLength(1);
  668. // 面向模型的文案:告知已在后台启动、结果以通知形式回来;占位提示必须消失,
  669. // 否则模型会以为什么都没发生而重复提交。
  670. expect(output.response).toContain("dwfrun-alpha");
  671. expect(output.response).toMatch(/background/i);
  672. expect(output.response).toMatch(/notified/i);
  673. // 异步引导(桌面实测:模型拿到 backgrounded 输出后立刻 TaskOutput 阻塞等待):
  674. // 文案必须劝阻等待/轮询并点名 TaskOutput。钉住存在性,不钉逐字。
  675. expect(output.response).toMatch(/do not wait/i);
  676. expect(output.response).toContain("TaskOutput");
  677. expect(output.response).not.toContain("NOT executed");
  678. expect(output.response).not.toContain("still under development");
  679. // 端口拿到的是脚本原文与执行上下文,且带 trace(端口契约要求 trace 非可选)。
  680. expect(submits).toHaveLength(1);
  681. const request = submits[0]!;
  682. expect(request.scriptText).toBe(script);
  683. expect(request.cwd).toBe(TEST_CWD);
  684. expect(request.parentSessionId).toBe(createSessionId("create-workflow-submit-allow"));
  685. expect(request.toolCallId).toBe(createToolCallId("create-workflow-submit-allow"));
  686. expect(request.trace?.traceId).toBeTruthy();
  687. });
  688. // input.name 的持久化路:handler → port.submit → EngineConfig → createRun → dwf_run.name。
  689. // 此前这个字段只活在工具行与任务标题的兜底链上,于是跨会话枚举出来的 run 只能是一串裸
  690. // runId(docs/dynamic-workflow/launch.md「`ListWorkflowRuns`」)。
  691. it("把 input.name 递给端口(run 标签的唯一来源)", async () => {
  692. const { port, submits } = stubRunPort("dwfrun-named");
  693. await run({
  694. dynamicWorkflowRunPort: port,
  695. name: "create-workflow-submit-named",
  696. script: cleanScript("submit-named"),
  697. workflowName: "nightly triage",
  698. });
  699. expect(submits).toHaveLength(1);
  700. expect(submits[0]!.name).toBe("nightly triage");
  701. });
  702. // 侧栏迷你轨道的两张表(docs/dynamic-workflow/presentation.md「The sidebar run line」):
  703. // 站点名与「哪两站是并行的」必须来自同一次分析、同一张图,否则下标会指错站。
  704. it("声明阶段表与「同时在跑」表同车递给端口", async () => {
  705. const { port, submits } = stubRunPort("dwfrun-alongside");
  706. await run({
  707. dynamicWorkflowRunPort: port,
  708. name: "create-workflow-submit-alongside",
  709. script: fixture("strand-fanout-two-phases-join.ts"),
  710. });
  711. expect(submits).toHaveLength(1);
  712. expect(submits[0]!.phaseNames).toEqual(["A", "B", "C"]);
  713. // B 是在 A 的 strand 还在跑时进入的;下标指向的正是上面那张 phaseNames。
  714. expect(submits[0]!.phaseAlongside).toEqual([[], [0], []]);
  715. });
  716. it("没有阶段并行的脚本不给端口造 phaseAlongside 键(缺席 = 一条直线)", async () => {
  717. const { port, submits } = stubRunPort("dwfrun-straight");
  718. await run({
  719. dynamicWorkflowRunPort: port,
  720. name: "create-workflow-submit-straight",
  721. script: fixture("strand-fanout-awaited-per-phase.ts"),
  722. });
  723. expect(submits).toHaveLength(1);
  724. expect(submits[0]!.phaseNames).toEqual(["A", "B", "C"]);
  725. expect("phaseAlongside" in submits[0]!).toBe(false);
  726. });
  727. it("未命名的调用不给端口造 name 键(读侧据此走脚本首行兜底)", async () => {
  728. const { port, submits } = stubRunPort("dwfrun-unnamed");
  729. await run({
  730. dynamicWorkflowRunPort: port,
  731. name: "create-workflow-submit-unnamed",
  732. script: cleanScript("submit-unnamed"),
  733. });
  734. expect(submits).toHaveLength(1);
  735. expect("name" in submits[0]!).toBe(false);
  736. });
  737. /**
  738. * 端口缺席(未接线宿主 / 单测)的降级路径。这条钉子原先叫「占位行为逐字不变」并按逐字节钉
  739. * 文案;占位文案真化后改钉**语义**:字段缺席照旧,文案要说清「本会话没有执行能力」,且不再
  740. * 自述成开发中的占位实现。
  741. */ it("端口缺席时降级语义不变,文案改说本会话无执行能力", async () => {
  742. const outcome = await run({
  743. name: "create-workflow-submit-no-port",
  744. script: cleanScript("submit-no-port"),
  745. });
  746. expect(outcome.result.success).toBe(true);
  747. const output = outcome.result.output as CreateWorkflowOutput;
  748. expect(output.ok).toBe(true);
  749. // 没有端口就没有 run:两个新字段必须整个缺席(.strict() 的输出不带空壳键)。
  750. expect(output.status).toBeUndefined();
  751. expect(output.backgroundTaskId).toBeUndefined();
  752. expect(output.response).toContain("The workflow script compiled cleanly.");
  753. expect(output.response).toContain("NOT executed");
  754. // 真化后这条路径为真的那句:能力缺席是本会话的事实,不是工具还没做完。
  755. expect(output.response).toContain("not available in this session");
  756. expect(output.response).not.toContain("under development");
  757. expect(output.response).not.toContain("placeholder");
  758. });
  759. // 坏脚本路径完全不变:不弹窗、不启动、不建 run。端口在场也不能改变这一点。
  760. it("坏脚本即便端口在场也不提交,只回诊断", async () => {
  761. const { port, submits } = stubRunPort("dwfrun-should-not-start");
  762. const outcome = await run({
  763. dynamicWorkflowRunPort: port,
  764. name: "create-workflow-submit-broken",
  765. script: 'const broken: number = "not a number";',
  766. });
  767. expect(outcome.permissionRequested).toHaveLength(0);
  768. expect(submits).toHaveLength(0);
  769. expect(outcome.result.success).toBe(true);
  770. const output = outcome.result.output as CreateWorkflowOutput;
  771. expect(output.ok).toBe(false);
  772. expect(output.diagnostics.length).toBeGreaterThan(0);
  773. expect(output.status).toBeUndefined();
  774. expect(output.backgroundTaskId).toBeUndefined();
  775. });
  776. // Deny 早于 handler:端口在场也绝不能启动。
  777. it("Deny 时端口不被触达", async () => {
  778. const { port, submits } = stubRunPort("dwfrun-denied");
  779. const outcome = await run({
  780. broker: {
  781. async requestPermission() {
  782. return { decision: "deny", reason: "User declined to run the workflow" };
  783. },
  784. },
  785. dynamicWorkflowRunPort: port,
  786. name: "create-workflow-submit-deny",
  787. script: cleanScript("submit-deny"),
  788. });
  789. expect(outcome.result.success).toBe(false);
  790. expect(outcome.result.error?.type).toBe("permission_denied");
  791. expect(submits).toHaveLength(0);
  792. });
  793. // 提交失败是一等失败:端口抛错不能被吞成"看起来启动了"的成功输出。
  794. it("端口 submit 抛错时工具调用失败,不伪造 backgrounded", async () => {
  795. const failing = {
  796. async submit() {
  797. throw new Error("journal unavailable");
  798. },
  799. } as unknown as DynamicWorkflowRunPort;
  800. const outcome = await run({
  801. dynamicWorkflowRunPort: failing,
  802. name: "create-workflow-submit-throws",
  803. script: cleanScript("submit-throws"),
  804. });
  805. expect(outcome.result.success).toBe(false);
  806. expect(outcome.result.error?.message).toContain("journal unavailable");
  807. });
  808. // metadata 的只读声明随执行语义一并翻面(前置 spec 的遗留项)。
  809. it("工具不再声明 readOnly", () => {
  810. expect(createWorkflowToolEntry.metadata.readOnly).toBe(false);
  811. });
  812. });
  813. // 每 run 的并发上界(docs/dynamic-workflow/concurrency.md「Two bounds on a run」)。这里走完整
  814. // executor,所以钉的是接线本身:取整发生在确认窗**之前**,handler 再把归一化后的那个数递给端口。
  815. // 默认并发是起点不是上限:高于它的数原样生效。
  816. describe("CreateWorkflow max_concurrency", () => {
  817. it("把上界递给端口,并在文案里说出生效的数", async () => {
  818. const { port, submits } = stubRunPort("dwfrun-capped", 8);
  819. const outcome = await run({
  820. dynamicWorkflowRunPort: port,
  821. maxConcurrency: 3,
  822. name: "create-workflow-maxconc",
  823. script: cleanScript("maxconc"),
  824. });
  825. expect(submits).toHaveLength(1);
  826. expect(submits[0]!.maxConcurrency).toBe(3);
  827. const output = outcome.result.output as CreateWorkflowOutput;
  828. expect(output.response).toContain("At most 3 subagents run at once.");
  829. // 不等于默认就不提默认——那会让模型以为 3 与没设一样。
  830. expect(output.response).not.toContain("(the default)");
  831. });
  832. it("高于默认并发的请求原样生效,确认窗与端口看到同一个数", async () => {
  833. const { port, submits } = stubRunPort("dwfrun-raised", 8);
  834. const outcome = await run({
  835. dynamicWorkflowRunPort: port,
  836. maxConcurrency: 32,
  837. name: "create-workflow-maxconc-raised",
  838. script: cleanScript("maxconc-raised"),
  839. });
  840. // 用户批准的必须是将要生效的那个数:确认窗读的是归一化后的入参。
  841. expect(outcome.permissionRequested[0]!.input).toMatchObject({ max_concurrency: 32 });
  842. expect(submits[0]!.maxConcurrency).toBe(32);
  843. const output = outcome.result.output as CreateWorkflowOutput;
  844. expect(output.response).toContain("At most 32 subagents run at once.");
  845. });
  846. it("正好等于默认并发时注明「(默认)」", async () => {
  847. const { port } = stubRunPort("dwfrun-at-default", 8);
  848. const outcome = await run({
  849. dynamicWorkflowRunPort: port,
  850. maxConcurrency: 8,
  851. name: "create-workflow-maxconc-default",
  852. script: cleanScript("maxconc-default"),
  853. });
  854. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  855. "At most 8 subagents run at once (the default).",
  856. );
  857. });
  858. it("没给上界就不造键,也不在文案里凭空多一句", async () => {
  859. const { port, submits } = stubRunPort("dwfrun-default", 8);
  860. const outcome = await run({
  861. dynamicWorkflowRunPort: port,
  862. name: "create-workflow-maxconc-absent",
  863. script: cleanScript("maxconc-absent"),
  864. });
  865. expect("maxConcurrency" in submits[0]!).toBe(false);
  866. expect((outcome.result.output as CreateWorkflowOutput).response).not.toContain("At most");
  867. });
  868. it("端口说不出默认并发时照样原样下传", async () => {
  869. const { port, submits } = stubRunPort("dwfrun-no-default");
  870. await run({
  871. dynamicWorkflowRunPort: port,
  872. maxConcurrency: 32,
  873. name: "create-workflow-maxconc-no-default",
  874. script: cleanScript("maxconc-no-default"),
  875. });
  876. expect(submits[0]!.maxConcurrency).toBe(32);
  877. });
  878. });
  879. // 每 run 的子代理模型(docs/dynamic-workflow/launch.md)。同样走完整 executor:钉的是接线
  880. // ——目录经 resolveInput 的上下文读到,解析发生在确认窗**之前**,handler 再把规范形拆成结构化
  881. // 选型递给端口。
  882. describe("CreateWorkflow subagent_model", () => {
  883. function entry(
  884. providerId: string,
  885. modelId: string,
  886. extra: Partial<ModelCatalogEntry> = {},
  887. ): ModelCatalogEntry {
  888. return { providerId, modelId, reasoningLevels: [], current: false, ...extra };
  889. }
  890. const CATALOG: ModelCatalogPort = {
  891. listModels: () => [
  892. entry("bigmodel", "GLM-4.6", {
  893. reasoningLevels: ["low", "high"],
  894. defaultReasoningLevel: "high",
  895. current: true,
  896. }),
  897. entry("openai", "gpt-5"),
  898. ],
  899. };
  900. it("把解析后的选型递给端口,确认窗显示的是同一个规范形", async () => {
  901. const { port, submits } = stubRunPort("dwfrun-model");
  902. const outcome = await run({
  903. dynamicWorkflowRunPort: port,
  904. modelCatalogPort: CATALOG,
  905. name: "create-workflow-subagent-model",
  906. script: cleanScript("subagent-model"),
  907. // 用户说的是裸名,大小写也不同。
  908. subagentModel: "glm-4.6",
  909. });
  910. // 用户批准的必须是将要生效的那个模型:确认窗读的是归一化后的入参。
  911. expect(outcome.permissionRequested[0]!.input).toMatchObject({
  912. subagent_model: "bigmodel/GLM-4.6$high",
  913. });
  914. expect(submits).toHaveLength(1);
  915. expect(submits[0]!.subagentModel).toEqual({
  916. providerId: "bigmodel",
  917. modelId: "GLM-4.6",
  918. options: { reasoningLevel: "high" },
  919. });
  920. const output = outcome.result.output as CreateWorkflowOutput;
  921. // 括号里那半句是给模型自己听的:它最容易把「子代理换了模型」读成「我也换了」。
  922. expect(output.response).toContain(
  923. "Subagents run on bigmodel/GLM-4.6$high (the main agent stays on the session model).",
  924. );
  925. });
  926. it("没选模型就不造键,也不在文案里凭空多一句", async () => {
  927. const { port, submits } = stubRunPort("dwfrun-model-absent");
  928. const outcome = await run({
  929. dynamicWorkflowRunPort: port,
  930. modelCatalogPort: CATALOG,
  931. name: "create-workflow-subagent-model-absent",
  932. script: cleanScript("subagent-model-absent"),
  933. });
  934. expect("subagentModel" in submits[0]!).toBe(false);
  935. expect((outcome.result.output as CreateWorkflowOutput).response).not.toContain(
  936. "Subagents run on",
  937. );
  938. });
  939. it("解不出来的模型名在确认窗之前就退回:没弹窗、没启动", async () => {
  940. const { port, submits } = stubRunPort("dwfrun-model-unresolved");
  941. const outcome = await run({
  942. dynamicWorkflowRunPort: port,
  943. modelCatalogPort: CATALOG,
  944. name: "create-workflow-subagent-model-miss",
  945. script: cleanScript("subagent-model-miss"),
  946. subagentModel: "gemini-3",
  947. });
  948. expect(outcome.result.success).toBe(false);
  949. expect(outcome.permissionRequested).toHaveLength(0);
  950. expect(submits).toHaveLength(0);
  951. });
  952. it("宿主没有目录时给了字段即被拒,同样不弹窗不启动", async () => {
  953. const { port, submits } = stubRunPort("dwfrun-model-no-catalog");
  954. const outcome = await run({
  955. dynamicWorkflowRunPort: port,
  956. name: "create-workflow-subagent-model-no-catalog",
  957. script: cleanScript("subagent-model-no-catalog"),
  958. subagentModel: "gpt-5",
  959. });
  960. expect(outcome.result.success).toBe(false);
  961. expect(outcome.permissionRequested).toHaveLength(0);
  962. expect(submits).toHaveLength(0);
  963. });
  964. });
  965. // docs/dynamic-workflow/launch.md「Adjusting the settings in the window」
  966. describe("CreateWorkflow settings adjusted in the confirmation window", () => {
  967. const CATALOG: ModelCatalogPort = {
  968. listModels: () => [
  969. {
  970. providerId: "bigmodel",
  971. modelId: "GLM-4.6",
  972. reasoningLevels: ["low", "high"],
  973. defaultReasoningLevel: "high",
  974. current: true,
  975. },
  976. { providerId: "openai", modelId: "gpt-5", reasoningLevels: [], current: false },
  977. ],
  978. };
  979. /** 放行应答带着窗里改过的字段(broker 从 v4 answer.content 收成的形状)。 */
  980. function allowWith(inputAdjustments: Record<string, unknown>): PermissionBrokerPort {
  981. return {
  982. async requestPermission() {
  983. return { decision: "allow", reason: "Approved once", inputAdjustments };
  984. },
  985. };
  986. }
  987. it("回填 adjustable_settings:确认窗读得到目录在不在、默认并发是多少", async () => {
  988. const { port } = stubRunPort("dwfrun-adjustable", 13);
  989. const outcome = await run({
  990. dynamicWorkflowRunPort: port,
  991. modelCatalogPort: CATALOG,
  992. name: "create-workflow-adjustable-block",
  993. script: cleanScript("adjustable-block"),
  994. });
  995. expect(outcome.permissionRequested[0]!.input).toMatchObject({
  996. adjustable_settings: { subagent_model: true, concurrency_ceiling: 13 },
  997. });
  998. });
  999. it("没有目录时块里说模型不可调;端口说不出默认并发时不造键", async () => {
  1000. const { port } = stubRunPort("dwfrun-adjustable-no-catalog");
  1001. const outcome = await run({
  1002. dynamicWorkflowRunPort: port,
  1003. name: "create-workflow-adjustable-no-catalog",
  1004. script: cleanScript("adjustable-no-catalog"),
  1005. });
  1006. const input = outcome.permissionRequested[0]!.input as Record<string, unknown>;
  1007. expect(input.adjustable_settings).toEqual({ subagent_model: false });
  1008. });
  1009. it("没有 run 端口就没有块:什么都不会跑,窗里也没什么可调", async () => {
  1010. const outcome = await run({
  1011. name: "create-workflow-adjustable-no-port",
  1012. script: cleanScript("adjustable-no-port"),
  1013. });
  1014. const input = outcome.permissionRequested[0]!.input as Record<string, unknown>;
  1015. expect("adjustable_settings" in input).toBe(false);
  1016. });
  1017. it.each(["build", "guarded"] as const)(
  1018. "%s:窗里改的模型与上界在 handler 之前落进入参,端口收到的就是它们,文案先把调整说出来",
  1019. async (mode) => {
  1020. const { port, submits } = stubRunPort("dwfrun-adjusted", 13);
  1021. const outcome = await run({
  1022. broker: allowWith({ subagent_model: "openai/gpt-5", max_concurrency: 4 }),
  1023. dynamicWorkflowRunPort: port,
  1024. modelCatalogPort: CATALOG,
  1025. name: "create-workflow-adjusted",
  1026. mode,
  1027. script: cleanScript("adjusted"),
  1028. });
  1029. expect(outcome.result.success).toBe(true);
  1030. expect(submits).toHaveLength(1);
  1031. expect(submits[0]!.subagentModel).toEqual({ providerId: "openai", modelId: "gpt-5" });
  1032. expect(submits[0]!.maxConcurrency).toBe(4);
  1033. const response = (outcome.result.output as CreateWorkflowOutput).response;
  1034. expect(response).toContain(
  1035. "Before approving, the user adjusted the settings in the confirmation window: subagents run on openai/gpt-5 (the main agent stays on the session model); at most 4 subagents run at once (the default is 13).",
  1036. );
  1037. // 调整句已经替两项说过了:普通的设置句不再重复一遍。
  1038. expect(response).not.toContain("At most 4 subagents run at once.");
  1039. expect(response).not.toContain("Subagents run on");
  1040. },
  1041. );
  1042. it("两个 null 把模型提议的值清掉:会话模型、默认并发", async () => {
  1043. const { port, submits } = stubRunPort("dwfrun-adjusted-null", 13);
  1044. const outcome = await run({
  1045. broker: allowWith({ subagent_model: null, max_concurrency: null }),
  1046. dynamicWorkflowRunPort: port,
  1047. maxConcurrency: 8,
  1048. modelCatalogPort: CATALOG,
  1049. name: "create-workflow-adjusted-null",
  1050. script: cleanScript("adjusted-null"),
  1051. subagentModel: "glm-4.6",
  1052. });
  1053. expect("subagentModel" in submits[0]!).toBe(false);
  1054. expect("maxConcurrency" in submits[0]!).toBe(false);
  1055. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  1056. "Before approving, the user adjusted the settings in the confirmation window: subagents are back on the session model; the limit on subagents at once is back to the default.",
  1057. );
  1058. });
  1059. it("窗里高于默认并发的上界原样生效:默认不是上限", async () => {
  1060. const { port, submits } = stubRunPort("dwfrun-adjusted-raise", 13);
  1061. const outcome = await run({
  1062. broker: allowWith({ max_concurrency: 50 }),
  1063. dynamicWorkflowRunPort: port,
  1064. name: "create-workflow-adjusted-raise",
  1065. script: cleanScript("adjusted-raise"),
  1066. });
  1067. expect(submits[0]!.maxConcurrency).toBe(50);
  1068. expect((outcome.result.output as CreateWorkflowOutput).response).toContain(
  1069. "at most 50 subagents run at once (the default is 13).",
  1070. );
  1071. });
  1072. it("用户没动的那一项保留它自己的句子", async () => {
  1073. const { port } = stubRunPort("dwfrun-adjusted-model-only", 13);
  1074. const outcome = await run({
  1075. broker: allowWith({ subagent_model: "openai/gpt-5" }),
  1076. dynamicWorkflowRunPort: port,
  1077. maxConcurrency: 8,
  1078. modelCatalogPort: CATALOG,
  1079. name: "create-workflow-adjusted-model-only",
  1080. script: cleanScript("adjusted-model-only"),
  1081. });
  1082. const response = (outcome.result.output as CreateWorkflowOutput).response;
  1083. expect(response).toContain(
  1084. "Before approving, the user adjusted the settings in the confirmation window: subagents run on openai/gpt-5 (the main agent stays on the session model).",
  1085. );
  1086. expect(response).toContain("At most 8 subagents run at once.");
  1087. });
  1088. it("与提议相同的「改动」不算调整,文案不说空话", async () => {
  1089. const { port, submits } = stubRunPort("dwfrun-adjusted-same", 13);
  1090. const outcome = await run({
  1091. broker: allowWith({ max_concurrency: 8 }),
  1092. dynamicWorkflowRunPort: port,
  1093. maxConcurrency: 8,
  1094. name: "create-workflow-adjusted-same",
  1095. script: cleanScript("adjusted-same"),
  1096. });
  1097. expect(submits[0]!.maxConcurrency).toBe(8);
  1098. const response = (outcome.result.output as CreateWorkflowOutput).response;
  1099. expect(response).not.toContain("Before approving");
  1100. expect(response).toContain("At most 8 subagents run at once.");
  1101. });
  1102. it("窗里选的模型此刻解不出来:整次调用失败,什么都不启动", async () => {
  1103. const { port, submits } = stubRunPort("dwfrun-adjusted-miss", 13);
  1104. const outcome = await run({
  1105. broker: allowWith({ subagent_model: "gemini-3" }),
  1106. dynamicWorkflowRunPort: port,
  1107. modelCatalogPort: CATALOG,
  1108. name: "create-workflow-adjusted-miss",
  1109. script: cleanScript("adjusted-miss"),
  1110. });
  1111. expect(outcome.result.success).toBe(false);
  1112. expect(outcome.result.error?.message).toContain("workflow_subagent_model_unresolved");
  1113. expect(submits).toHaveLength(0);
  1114. });
  1115. it("本会话始终允许 + 调整:授权照常写进会话规则,调整只属于这一次", async () => {
  1116. const permissionService = new PermissionService(defaultPermissionConfig);
  1117. const { port, submits } = stubRunPort("dwfrun-adjusted-session", 13);
  1118. await run({
  1119. broker: {
  1120. async requestPermission(request) {
  1121. return {
  1122. decision: "allow",
  1123. reason: "Approved for this session",
  1124. sessionPermissionUpdates: [
  1125. { behavior: "allow", rules: [{ toolName: request.toolName }], type: "addRules" },
  1126. ],
  1127. inputAdjustments: { max_concurrency: 2 },
  1128. };
  1129. },
  1130. },
  1131. dynamicWorkflowRunPort: port,
  1132. name: "create-workflow-adjusted-session-a",
  1133. permissionService,
  1134. script: cleanScript("adjusted-session-a"),
  1135. });
  1136. const second = await run({
  1137. broker: {
  1138. async requestPermission() {
  1139. throw new Error("第二次不该再向 broker 要确认");
  1140. },
  1141. },
  1142. dynamicWorkflowRunPort: port,
  1143. name: "create-workflow-adjusted-session-b",
  1144. permissionService,
  1145. script: cleanScript("adjusted-session-b"),
  1146. });
  1147. expect(submits.map((submit) => submit.maxConcurrency)).toEqual([2, undefined]);
  1148. expect((second.result.output as CreateWorkflowOutput).response).not.toContain(
  1149. "Before approving",
  1150. );
  1151. });
  1152. });