headless-workflow.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. import assert from "node:assert/strict";
  2. import test from "node:test";
  3. import {
  4. SessionEventType,
  5. type DynamicWorkflowRunProgressPayload,
  6. type SessionEvent,
  7. } from "@zcode/contracts";
  8. import type { RunContext } from "@zcode/shared-types";
  9. import { zcodeSessionEventTypeSchema } from "@zcode/shared";
  10. import { run } from "../src/run.js";
  11. import type { RunDependencies } from "../src/run.js";
  12. import {
  13. WORKFLOW_RUN_PROGRESS_STREAM_TYPE,
  14. createHeadlessPermissionBroker,
  15. createWorkflowProgressReporter,
  16. isDynamicWorkflowRunProgressEvent,
  17. mapWorkflowRunProgressStreamLine,
  18. waitForHeadlessSettle,
  19. } from "../src/headless-workflow.js";
  20. const progressEvent = (
  21. payload: Partial<DynamicWorkflowRunProgressPayload> & { eventType: string },
  22. envelope: Partial<SessionEvent> = {},
  23. ): SessionEvent =>
  24. ({
  25. id: "evt-dwf-1",
  26. sessionId: "session-test",
  27. traceId: "trace-test",
  28. type: SessionEventType.DynamicWorkflowRunProgress,
  29. timestamp: new Date(1_700_000_000_000),
  30. sequenceNumber: 7,
  31. payload: {
  32. runId: "dwfrun-abc",
  33. sequence: 3,
  34. payload: {},
  35. ...payload,
  36. },
  37. ...envelope,
  38. }) as SessionEvent;
  39. const permissionRequest = (toolName: string) =>
  40. ({
  41. requestId: "perm_1",
  42. sessionId: "session-test",
  43. traceId: "trace-test",
  44. toolCallId: "call-1",
  45. toolName,
  46. input: {},
  47. mode: "build",
  48. ruleId: "tool.alwaysAsk",
  49. reason: `Tool ${toolName} always requires explicit approval`,
  50. riskLevel: "low",
  51. requestedAt: new Date(),
  52. }) as never;
  53. // —————————————————————————————————————————————————————————————
  54. // 审批旁路(headless broker)
  55. // —————————————————————————————————————————————————————————————
  56. test("headless broker allows CreateWorkflow", async () => {
  57. const broker = createHeadlessPermissionBroker();
  58. const result = await broker.requestPermission(permissionRequest("CreateWorkflow"));
  59. assert.equal(result.decision, "allow");
  60. });
  61. test("headless broker leaves every other tool at today's deny semantics", async () => {
  62. // 回归钉:旁路必须是按工具名的一个洞,不是一把开关。文案也钉住——它来自 core 的
  63. // deny broker,旁路只委托、不复写,所以这里的断言同时证明"没有第二份文案"。
  64. const broker = createHeadlessPermissionBroker();
  65. for (const toolName of ["Bash", "Write", "Edit", "Agent", "Workflow"]) {
  66. const result = await broker.requestPermission(permissionRequest(toolName));
  67. assert.equal(result.decision, "deny", `${toolName} must stay denied`);
  68. assert.equal(
  69. result.reason,
  70. `ZCode requested permissions to use ${toolName}, but you haven't granted it yet.`,
  71. );
  72. }
  73. });
  74. // —————————————————————————————————————————————————————————————
  75. // stream-json 定型行
  76. // —————————————————————————————————————————————————————————————
  77. test("dwf progress events are recognised, other session events are not", () => {
  78. assert.equal(
  79. isDynamicWorkflowRunProgressEvent(progressEvent({ eventType: "run-started" })),
  80. true,
  81. );
  82. assert.equal(
  83. isDynamicWorkflowRunProgressEvent(
  84. progressEvent({ eventType: "run-started" }, { type: SessionEventType.AssistantMessage }),
  85. ),
  86. false,
  87. );
  88. });
  89. test("the CLI-private stream type stays out of the v3 protocol enum", () => {
  90. // 绊线:定型行的 type 刻意不是 zcodeSessionEventTypeSchema 的成员。那个 enum 是闭集
  91. // 且喂给 zcodeSessionEventSchema 的 discriminated union,加值等于让 v3 app-server 在
  92. // 类型面上宣告一个它永不发出的事件(协议路径在 mapSessionEventForProtocol 里就已经
  93. // 把这个事件剥掉了)。谁把映射搬进协议枚举,这条先红。
  94. assert.equal(
  95. zcodeSessionEventTypeSchema.options.includes(WORKFLOW_RUN_PROGRESS_STREAM_TYPE as never),
  96. false,
  97. );
  98. });
  99. test("the typed stream-json line carries its own type and the bounded payload verbatim", () => {
  100. const event = progressEvent({
  101. eventType: "node-settled",
  102. runId: "dwfrun-abc",
  103. sequence: 12,
  104. toolCallId: "call-42",
  105. payload: { instance: { siteId: "ask#1", ordinal: 2 }, outcome: "ok" },
  106. truncated: true,
  107. });
  108. const line = mapWorkflowRunProgressStreamLine(event);
  109. // 定型:独立 type,不是 catch-all session.updated。
  110. assert.equal(line.type, WORKFLOW_RUN_PROGRESS_STREAM_TYPE);
  111. assert.notEqual(line.type as string, "session.updated");
  112. // 信封与 mapSessionEvent 对齐(同样的 String()/getTime() 规范化)。
  113. assert.equal(line.eventId, "evt-dwf-1");
  114. assert.equal(line.sessionId, "session-test");
  115. assert.equal(line.traceId, "trace-test");
  116. assert.equal(line.seq, 7);
  117. assert.equal(line.timestamp, 1_700_000_000_000);
  118. // dwf 事件是出回合的,信封里没有 turnId 键(不是 undefined 值)。
  119. assert.equal("turnId" in line, false);
  120. // payload 原样:不重塑字段名,读端按 eventType 解释。
  121. assert.deepEqual(line.payload, {
  122. runId: "dwfrun-abc",
  123. sequence: 12,
  124. toolCallId: "call-42",
  125. eventType: "node-settled",
  126. payload: { instance: { siteId: "ask#1", ordinal: 2 }, outcome: "ok" },
  127. truncated: true,
  128. });
  129. // 一行 NDJSON 必须能独立 parse。
  130. assert.doesNotThrow(() => JSON.parse(JSON.stringify(line)));
  131. });
  132. // —————————————————————————————————————————————————————————————
  133. // text 模式的 stderr 进度
  134. // —————————————————————————————————————————————————————————————
  135. const collectProgress = (
  136. events: readonly SessionEvent[],
  137. options: { throttleMs?: number; clock?: number[] } = {},
  138. ): string[] => {
  139. const lines: string[] = [];
  140. const clock = options.clock ? [...options.clock] : undefined;
  141. let fallbackNow = 0;
  142. const reporter = createWorkflowProgressReporter({
  143. now: () => (clock ? (clock.shift() ?? 0) : fallbackNow++),
  144. ...(options.throttleMs === undefined ? {} : { throttleMs: options.throttleMs }),
  145. write: (line) => lines.push(line),
  146. });
  147. for (const event of events) reporter(event);
  148. return lines;
  149. };
  150. test("run lifecycle and log lines are never throttled away", () => {
  151. const lines = collectProgress(
  152. [
  153. progressEvent({ eventType: "run-started" }),
  154. progressEvent({ eventType: "log", payload: { message: "compiled" } }),
  155. progressEvent({ eventType: "log", payload: { message: "asking reviewer" } }),
  156. progressEvent({ eventType: "run-settled", payload: { status: "completed" } }),
  157. ],
  158. // 时钟不动:任何按时间的节流都会在这里吃掉后三条——这正是这条用例要挡住的退步。
  159. { clock: [0, 0, 0, 0] },
  160. );
  161. assert.deepEqual(lines, [
  162. "workflow dwfrun-abc: started\n",
  163. "workflow dwfrun-abc: log: compiled\n",
  164. "workflow dwfrun-abc: log: asking reviewer\n",
  165. "workflow dwfrun-abc: completed\n",
  166. ]);
  167. });
  168. test("a failed settle carries the error message", () => {
  169. const lines = collectProgress([
  170. progressEvent({
  171. eventType: "run-settled",
  172. payload: { status: "errored", error: { code: "DriverError", message: "boom" } },
  173. }),
  174. ]);
  175. assert.deepEqual(lines, ["workflow dwfrun-abc: errored: boom\n"]);
  176. });
  177. test("a stopped settle prints the stop reason next to the status", () => {
  178. const lines = collectProgress([
  179. progressEvent({
  180. eventType: "run-settled",
  181. payload: {
  182. status: "stopped",
  183. stopReason: "provider",
  184. error: { code: "ProviderStop", message: "sign-in expired" },
  185. },
  186. }),
  187. ]);
  188. assert.deepEqual(lines, ["workflow dwfrun-abc: stopped/provider: sign-in expired\n"]);
  189. });
  190. test("node phase transitions are throttled but the first one gets through", () => {
  191. const nodeEvent = (eventType: string, ordinal: number) =>
  192. progressEvent({
  193. eventType,
  194. payload: {
  195. instance: { siteId: "ask#1", ordinal },
  196. ...(eventType === "node-settled" ? { outcome: "ok" } : {}),
  197. },
  198. });
  199. // 节流对**所有**节点相位一视同仁,`node-settled` 也会被吃掉——刻意如此:run 的
  200. // 端点由 run-settled 保证(上面那条用例),节点级的完成不是必达面,否则一个
  201. // 100 节点的 run 在 text 模式下会刷屏。
  202. const lines = collectProgress(
  203. [
  204. nodeEvent("node-queued", 1),
  205. nodeEvent("node-dispatched", 1),
  206. nodeEvent("node-settled", 1),
  207. nodeEvent("node-queued", 2),
  208. ],
  209. { clock: [0, 100, 200, 1_000], throttleMs: 400 },
  210. );
  211. assert.deepEqual(lines, [
  212. "workflow dwfrun-abc: queued ask#1@1\n",
  213. "workflow dwfrun-abc: queued ask#1@2\n",
  214. ]);
  215. });
  216. test("counting-only and non-transition events produce no progress line", () => {
  217. const lines = collectProgress([
  218. progressEvent({ eventType: "usage-updated", payload: { spentTokens: 12 } }),
  219. progressEvent({
  220. eventType: "actor-created",
  221. payload: { actor: { siteId: "actor#1", ordinal: 1 } },
  222. }),
  223. progressEvent({ eventType: "compaction", payload: {} }),
  224. progressEvent({ eventType: "log", payload: {} }),
  225. progressEvent({ eventType: "run-started" }, { type: SessionEventType.AssistantMessage }),
  226. ]);
  227. assert.deepEqual(lines, []);
  228. });
  229. // —————————————————————————————————————————————————————————————
  230. // 经 run() 的端到端接线(headless prompt 路径)
  231. // —————————————————————————————————————————————————————————————
  232. type CapturedWriteStream = NodeJS.WriteStream & { output: () => string };
  233. const createWriteStream = (): CapturedWriteStream => {
  234. let output = "";
  235. return {
  236. output: () => output,
  237. write: (
  238. chunk: string | Uint8Array,
  239. encodingOrCallback?: BufferEncoding | ((err?: Error | null) => void),
  240. callback?: (err?: Error | null) => void,
  241. ): boolean => {
  242. output += typeof chunk === "string" ? chunk : chunk.toString();
  243. (typeof encodingOrCallback === "function" ? encodingOrCallback : callback)?.();
  244. return true;
  245. },
  246. } as CapturedWriteStream;
  247. };
  248. const createContext = (
  249. argv: string[],
  250. ): RunContext & { stderr: CapturedWriteStream; stdout: CapturedWriteStream } => ({
  251. argv,
  252. stderr: createWriteStream(),
  253. stdin: { isTTY: false } as NodeJS.ReadStream,
  254. stdout: createWriteStream(),
  255. });
  256. const turnEvents: readonly SessionEvent[] = [
  257. progressEvent({ eventType: "run-started" }, { id: "evt-1" }),
  258. progressEvent(
  259. {
  260. eventType: "node-settled",
  261. payload: { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" },
  262. },
  263. { id: "evt-2", sequenceNumber: 8 },
  264. ),
  265. {
  266. ...progressEvent({ eventType: "run-started" }),
  267. id: "evt-3",
  268. type: SessionEventType.TurnComplete,
  269. payload: {},
  270. } as SessionEvent,
  271. ];
  272. const createRunDeps = (): RunDependencies & { appOptions: () => unknown } => {
  273. let appOptions: unknown;
  274. return {
  275. appOptions: () => appOptions,
  276. createZCodeApp: (options?: unknown) => {
  277. appOptions = options;
  278. return {
  279. getModel: () => "openai/gpt-test",
  280. getThoughtLevel: () => "medium",
  281. sessionId: "session-test",
  282. traceId: "trace-test",
  283. runtime: {} as never,
  284. submitPrompt: async (
  285. _prompt: unknown,
  286. submitOptions?: { onEvent?: (event: unknown) => void | Promise<void> },
  287. ) => {
  288. for (const event of turnEvents) submitOptions?.onEvent?.(event);
  289. return {
  290. events: turnEvents,
  291. projection: {
  292. contextUsed: 12,
  293. contextWindow: 1000,
  294. status: "idle",
  295. totalTokenCount: 12,
  296. turnCount: 1,
  297. } as never,
  298. response: "the answer",
  299. traceId: "trace-test" as never,
  300. turnId: "turn-test" as never,
  301. };
  302. },
  303. } as never;
  304. },
  305. loadDotenv: () => ({ keys: [], loaded: false }),
  306. // The prompt command now starts the process Provider Registry runtime before it
  307. // creates the app; without this stand-in `run` exits 1 before the broker is built.
  308. startProcessProviderRegistryRuntime: async () =>
  309. ({
  310. dispose: () => {},
  311. runtime: { registryService: {} },
  312. }) as never,
  313. mapSessionEvent: ((event: { id: string; type: string }) => ({
  314. eventId: event.id,
  315. type: event.type,
  316. })) as never,
  317. } as RunDependencies & { appOptions: () => unknown };
  318. };
  319. test("headless app creation installs the CreateWorkflow-only broker", async () => {
  320. const ctx = createContext(["--workflow-mode", "alwaysOn", "--prompt", "hi"]);
  321. const deps = createRunDeps();
  322. assert.equal(await run(ctx, deps), 0);
  323. const broker = (deps.appOptions() as { permissionBroker?: { requestPermission: unknown } })
  324. .permissionBroker;
  325. const allowed = await (
  326. broker as { requestPermission: (r: unknown) => Promise<{ decision: string }> }
  327. ).requestPermission(permissionRequest("CreateWorkflow"));
  328. assert.equal(allowed.decision, "allow");
  329. const denied = await (
  330. broker as { requestPermission: (r: unknown) => Promise<{ decision: string }> }
  331. ).requestPermission(permissionRequest("Bash"));
  332. assert.equal(denied.decision, "deny");
  333. });
  334. test("stream-json emits the typed workflow line and still terminates with the result line", async () => {
  335. const ctx = createContext([
  336. "--workflow-mode",
  337. "alwaysOn",
  338. "--output-format",
  339. "stream-json",
  340. "--prompt",
  341. "hi",
  342. ]);
  343. assert.equal(await run(ctx, createRunDeps()), 0);
  344. const lines = ctx.stdout
  345. .output()
  346. .trim()
  347. .split("\n")
  348. .map((line) => JSON.parse(line) as { type: string; payload?: { eventType?: string } });
  349. const workflowLines = lines.filter((line) => line.type === WORKFLOW_RUN_PROGRESS_STREAM_TYPE);
  350. assert.equal(workflowLines.length, 2);
  351. assert.deepEqual(
  352. workflowLines.map((line) => line.payload?.eventType),
  353. ["run-started", "node-settled"],
  354. );
  355. // 回归钉:这两条今天漏成 catch-all session.updated。
  356. assert.equal(
  357. lines.some((line) => line.type === "session.updated"),
  358. false,
  359. );
  360. // 非 dwf 事件仍走 mapSessionEvent,result 行仍是流的终止符。
  361. assert.equal(lines.at(-2)?.type, "turn_complete");
  362. assert.equal(lines.at(-1)?.type, "result");
  363. });
  364. test("text mode prints workflow progress to stderr and keeps stdout to the answer", async () => {
  365. const ctx = createContext(["--workflow-mode", "alwaysOn", "--prompt", "hi"]);
  366. assert.equal(await run(ctx, createRunDeps()), 0);
  367. assert.equal(ctx.stdout.output(), "the answer\n");
  368. const stderr = ctx.stderr.output();
  369. assert.match(stderr, /^workflow dwfrun-abc: started$/m);
  370. assert.match(stderr, /^workflow dwfrun-abc: settled ask#1@1 \(ok\)$/m);
  371. });
  372. test("json mode stays exactly one object: no progress, no stderr noise", async () => {
  373. const ctx = createContext([
  374. "--workflow-mode",
  375. "alwaysOn",
  376. "--output-format",
  377. "json",
  378. "--prompt",
  379. "hi",
  380. ]);
  381. assert.equal(await run(ctx, createRunDeps()), 0);
  382. assert.doesNotThrow(() => JSON.parse(ctx.stdout.output()));
  383. assert.equal(ctx.stderr.output().includes("workflow dwfrun-abc"), false);
  384. });
  385. test("stream-json does not duplicate progress onto stderr", async () => {
  386. const ctx = createContext([
  387. "--workflow-mode",
  388. "alwaysOn",
  389. "--output-format",
  390. "stream-json",
  391. "--prompt",
  392. "hi",
  393. ]);
  394. assert.equal(await run(ctx, createRunDeps()), 0);
  395. assert.equal(ctx.stderr.output().includes("workflow dwfrun-abc"), false);
  396. });
  397. // —————————————————————————————————————————————————————————————
  398. // 等待结算(在飞 run + 通知驱动回合)
  399. // —————————————————————————————————————————————————————————————
  400. const abortedSignal = (): AbortSignal => {
  401. const controller = new AbortController();
  402. controller.abort();
  403. return controller.signal;
  404. };
  405. test("the wait returns immediately when the runtime reports no work", async () => {
  406. let polls = 0;
  407. await waitForHeadlessSettle({
  408. runtime: {
  409. hasActiveOrQueuedTurnWork: () => {
  410. polls += 1;
  411. return false;
  412. },
  413. hasRunningBackgroundTasks: () => false,
  414. },
  415. signal: new AbortController().signal,
  416. sleep: async () => assert.fail("must not sleep when there is nothing to wait for"),
  417. });
  418. assert.equal(polls, 1);
  419. });
  420. test("the wait polls until both busy facts clear", async () => {
  421. // 谓词是"或":后台任务先清空,但通知回合还在队列里,等待必须继续。
  422. // 两个计数器各自独立,因为谓词短路——后台任务为真时根本不问回合工作。
  423. let backgroundCalls = 0;
  424. let turnWorkCalls = 0;
  425. let sleeps = 0;
  426. await waitForHeadlessSettle({
  427. runtime: {
  428. hasActiveOrQueuedTurnWork: () => {
  429. turnWorkCalls += 1;
  430. return turnWorkCalls <= 1;
  431. },
  432. hasRunningBackgroundTasks: () => {
  433. backgroundCalls += 1;
  434. return backgroundCalls <= 2;
  435. },
  436. },
  437. signal: new AbortController().signal,
  438. sleep: async () => {
  439. sleeps += 1;
  440. },
  441. });
  442. // 2 轮等后台 + 1 轮等通知回合,第 4 轮两者都清空才退出。
  443. assert.equal(sleeps, 3);
  444. assert.equal(backgroundCalls, 4);
  445. });
  446. test("an already-aborted signal never enters the wait: Ctrl-C is not swallowed", async () => {
  447. await waitForHeadlessSettle({
  448. runtime: {
  449. hasActiveOrQueuedTurnWork: () => true,
  450. hasRunningBackgroundTasks: () => true,
  451. },
  452. signal: abortedSignal(),
  453. sleep: async () => assert.fail("an aborted wait must not sleep"),
  454. });
  455. });
  456. test("aborting mid-wait breaks the loop even while the runtime stays busy", async () => {
  457. const controller = new AbortController();
  458. let sleeps = 0;
  459. await waitForHeadlessSettle({
  460. runtime: {
  461. hasActiveOrQueuedTurnWork: () => true,
  462. hasRunningBackgroundTasks: () => true,
  463. },
  464. signal: controller.signal,
  465. sleep: async () => {
  466. sleeps += 1;
  467. if (sleeps === 2) controller.abort();
  468. },
  469. });
  470. assert.equal(sleeps, 2);
  471. });
  472. /**
  473. * 一个会「起 dwf run、结算、再由通知驱动一个回合」的 app 替身。
  474. *
  475. * 关键点:`submitPrompt` 把事件**同时**扇给常驻订阅的 sink 与 `options.onEvent`——真实
  476. * runtime 在两者都装上时就是这个行为。于是"恰好一次"这件事在这个装配下是可证的:
  477. * 若 prompt-command 两个都装,每条事件就会出现两行。
  478. */
  479. const createWaitingRunDeps = (
  480. script: {
  481. busyPolls: number;
  482. /** 第一个回合的响应文本,缺省是工作流替身的文本。 */
  483. firstResponse?: string;
  484. notificationTurns?: readonly { turnId: string; response: string }[];
  485. /** 第一个回合的事件,缺省带 dwf 活动。 */
  486. turnEvents?: readonly SessionEvent[];
  487. } = {
  488. busyPolls: 2,
  489. },
  490. ): RunDependencies & { pollCount: () => number } => {
  491. let remainingBusyPolls = script.busyPolls;
  492. let polls = 0;
  493. const sinks: ((event: SessionEvent) => void)[] = [];
  494. const firstTurnEvents = script.turnEvents ?? turnEvents;
  495. return {
  496. pollCount: () => polls,
  497. createZCodeApp: () =>
  498. ({
  499. getModel: () => "openai/gpt-test",
  500. getThoughtLevel: () => "medium",
  501. sessionId: "session-test",
  502. traceId: "trace-test",
  503. runtime: {
  504. subscribeEvents: (sink: { onSessionEvent: (event: SessionEvent) => void }) => {
  505. sinks.push(sink.onSessionEvent);
  506. return () => {
  507. const at = sinks.indexOf(sink.onSessionEvent);
  508. if (at >= 0) sinks.splice(at, 1);
  509. };
  510. },
  511. hasRunningBackgroundTasks: () => {
  512. polls += 1;
  513. return remainingBusyPolls-- > 0;
  514. },
  515. hasActiveOrQueuedTurnWork: () => false,
  516. } as never,
  517. submitPrompt: async (
  518. _prompt: unknown,
  519. submitOptions?: { onEvent?: (event: SessionEvent) => void | Promise<void> },
  520. ) => {
  521. const emit = (event: SessionEvent) => {
  522. for (const sink of [...sinks]) sink(event);
  523. void submitOptions?.onEvent?.(event);
  524. };
  525. for (const event of firstTurnEvents) emit(event);
  526. // 通知驱动的回合在等待期到达:sleep(100) 之前这个 0ms timer 必然先触发。
  527. setTimeout(() => {
  528. for (const turn of script.notificationTurns ?? []) {
  529. emit({
  530. ...progressEvent({ eventType: "run-settled" }),
  531. id: `evt-${turn.turnId}`,
  532. turnId: turn.turnId as never,
  533. type: SessionEventType.TurnComplete,
  534. payload: { response: turn.response },
  535. } as SessionEvent);
  536. }
  537. }, 0);
  538. return {
  539. events: firstTurnEvents,
  540. projection: {
  541. contextUsed: 12,
  542. contextWindow: 1000,
  543. status: "idle",
  544. totalTokenCount: 12,
  545. turnCount: 1,
  546. } as never,
  547. response: script.firstResponse ?? "starting the workflow",
  548. traceId: "trace-test" as never,
  549. turnId: "turn-test" as never,
  550. };
  551. },
  552. }) as never,
  553. loadDotenv: () => ({ keys: [], loaded: false }),
  554. startProcessProviderRegistryRuntime: async () =>
  555. ({
  556. dispose: () => {},
  557. runtime: { registryService: {} },
  558. }) as never,
  559. mapSessionEvent: ((event: { id: string; type: string }) => ({
  560. eventId: event.id,
  561. type: event.type,
  562. })) as never,
  563. } as RunDependencies & { pollCount: () => number };
  564. };
  565. test("text mode waits for settle and prints every turn, ending with the post-settle answer", async () => {
  566. const ctx = createContext(["--workflow-mode", "alwaysOn", "--prompt", "run my workflow"]);
  567. const deps = createWaitingRunDeps({
  568. busyPolls: 2,
  569. notificationTurns: [{ turnId: "turn-notify", response: "the workflow produced 42" }],
  570. });
  571. assert.equal(await run(ctx, deps), 0);
  572. // 等待真的发生了(谓词被轮询过不止一次)。
  573. assert.ok(deps.pollCount() >= 3, `expected repeated polling, got ${deps.pollCount()}`);
  574. // 两个回合按到达序,最后一段是结算后的总结。
  575. assert.equal(ctx.stdout.output(), "starting the workflow\n\nthe workflow produced 42\n");
  576. });
  577. test("json mode reports the last turn as response and every turn in turnResponses", async () => {
  578. const ctx = createContext([
  579. "--workflow-mode",
  580. "alwaysOn",
  581. "--output-format",
  582. "json",
  583. "--prompt",
  584. "run my workflow",
  585. ]);
  586. const deps = createWaitingRunDeps({
  587. busyPolls: 1,
  588. notificationTurns: [{ turnId: "turn-notify", response: "the workflow produced 42" }],
  589. });
  590. assert.equal(await run(ctx, deps), 0);
  591. const parsed = JSON.parse(ctx.stdout.output()) as {
  592. response: string;
  593. turnResponses?: string[];
  594. };
  595. assert.equal(parsed.response, "the workflow produced 42");
  596. assert.deepEqual(parsed.turnResponses, ["starting the workflow", "the workflow produced 42"]);
  597. });
  598. test("a late turn_complete for the first turn is not counted twice", async () => {
  599. // 首个回合的文本来自 submitPrompt 的返回值。它的 turn_complete 若在等待期才到达,
  600. // 必须被 turnId 挡住——否则 response 会退回第一个回合的文本。
  601. const ctx = createContext([
  602. "--workflow-mode",
  603. "alwaysOn",
  604. "--output-format",
  605. "json",
  606. "--prompt",
  607. "run my workflow",
  608. ]);
  609. const deps = createWaitingRunDeps({
  610. busyPolls: 1,
  611. notificationTurns: [
  612. { turnId: "turn-notify", response: "the workflow produced 42" },
  613. { turnId: "turn-test", response: "starting the workflow" },
  614. ],
  615. });
  616. assert.equal(await run(ctx, deps), 0);
  617. const parsed = JSON.parse(ctx.stdout.output()) as { response: string; turnResponses?: string[] };
  618. assert.equal(parsed.response, "the workflow produced 42");
  619. assert.deepEqual(parsed.turnResponses, ["starting the workflow", "the workflow produced 42"]);
  620. });
  621. test("every event reaches stdout exactly once even though both sinks are offered", async () => {
  622. // 这条钉的是重复行:替身把每条事件同时扇给常驻 sink 与 options.onEvent。
  623. // prompt-command 必须二选一——两个都装的话每条事件就是两行。
  624. const ctx = createContext([
  625. "--workflow-mode",
  626. "alwaysOn",
  627. "--output-format",
  628. "stream-json",
  629. "--prompt",
  630. "run my workflow",
  631. ]);
  632. const deps = createWaitingRunDeps({
  633. busyPolls: 1,
  634. notificationTurns: [{ turnId: "turn-notify", response: "the workflow produced 42" }],
  635. });
  636. assert.equal(await run(ctx, deps), 0);
  637. const lines = ctx.stdout
  638. .output()
  639. .trim()
  640. .split("\n")
  641. .map((line) => JSON.parse(line) as { type: string; eventId?: string });
  642. const eventIds = lines.filter((line) => line.eventId !== undefined).map((line) => line.eventId);
  643. assert.deepEqual(
  644. eventIds.length,
  645. new Set(eventIds).size,
  646. `duplicate NDJSON lines for the same event: ${eventIds.join(", ")}`,
  647. );
  648. // 通知回合的事件也在流里(常驻订阅跨回合),且 result 行仍是唯一的终止符。
  649. assert.equal(
  650. lines.some((line) => line.eventId === "evt-turn-notify"),
  651. true,
  652. );
  653. assert.equal(lines.filter((line) => line.type === "result").length, 1);
  654. assert.equal(lines.at(-1)?.type, "result");
  655. });
  656. test("a resolvable custom command waits for settle instead of early-returning", async () => {
  657. // Bug 回归钉:自定义命令解析出来是 type === "unknown",过去因此早退进 command-center,
  658. // 第一个回合结束就退出进程,把在飞的 run 孤儿化成 stopped(interrupted)。现在能解析成真实
  659. // 自定义命令的走普通 prompt 路径,于是等待与"最后一个回合"语义都生效;提交给 app 的是
  660. // 原文(展开由 facade 负责)。示例命令是一个项目自定义命令(`/workflow` 已是内置保留名,见下一条)。
  661. const ctx = createContext([
  662. "--workflow-mode",
  663. "alwaysOn",
  664. "--prompt",
  665. "/launch-plan build me a plan",
  666. ]);
  667. const deps = createWaitingRunDeps({
  668. busyPolls: 2,
  669. notificationTurns: [{ turnId: "turn-notify", response: "the workflow produced 42" }],
  670. });
  671. const loadedNames: string[] = [];
  672. const exitCode = await run(ctx, {
  673. ...deps,
  674. isReservedSlashCommandName: () => false,
  675. loadCustomCommand: async (options) => {
  676. loadedNames.push(options.name);
  677. return {
  678. content: "Run the dynamic workflow: $ARGUMENTS.",
  679. metadata: {
  680. description: "Start a dynamic workflow",
  681. name: "launch-plan",
  682. path: "/workspace/.zcode/commands/launch-plan.md",
  683. scope: "project",
  684. source: "zcode",
  685. },
  686. } as never;
  687. },
  688. });
  689. assert.equal(exitCode, 0);
  690. assert.deepEqual(loadedNames, ["launch-plan"]);
  691. assert.ok(deps.pollCount() >= 3, `expected repeated polling, got ${deps.pollCount()}`);
  692. assert.equal(ctx.stdout.output(), "starting the workflow\n\nthe workflow produced 42\n");
  693. });
  694. test("the builtin /workflow command rides the plain prompt path without a custom command lookup", async () => {
  695. // `/workflow` 现在是 CLI 内置 prompt 命令(bootstrap/src/builtin-workflow-command.ts):
  696. // 解析成 known 且不是 expert/goal,直接进普通 prompt 路径,不再探测自定义命令;原文交给
  697. // facade 展开。dwf 结算等待与"最后一个回合"语义与自定义命令一致。独立 CLI 缺省 disabled
  698. // (launch.md「The standalone CLI: `--workflow-mode`」),所以这里显式开启。
  699. const ctx = createContext([
  700. "--prompt",
  701. "/workflow build me a plan",
  702. "--workflow-mode",
  703. "alwaysOn",
  704. ]);
  705. const deps = createWaitingRunDeps({
  706. busyPolls: 2,
  707. notificationTurns: [{ turnId: "turn-notify", response: "the workflow produced 42" }],
  708. });
  709. const loadedNames: string[] = [];
  710. const exitCode = await run(ctx, {
  711. ...deps,
  712. loadCustomCommand: async (options) => {
  713. loadedNames.push(options.name);
  714. throw new Error(`Custom command not found: ${options.name}`);
  715. },
  716. });
  717. assert.equal(exitCode, 0);
  718. assert.deepEqual(loadedNames, []);
  719. assert.ok(deps.pollCount() >= 3, `expected repeated polling, got ${deps.pollCount()}`);
  720. assert.equal(ctx.stdout.output(), "starting the workflow\n\nthe workflow produced 42\n");
  721. });
  722. // 修复回归:等待原来只在观察到 dwf 活动后才开始。Agent 总在后台运行后,模型派出子代理、
  723. // 第一个回合结束时进程就退出,子代理还没做完,benchmark 的校验随即开始。
  724. test("a run waits for a background subagent although no workflow ran", async () => {
  725. const ctx = createContext(["--output-format", "json", "--prompt", "delegate the review"]);
  726. const deps = createWaitingRunDeps({
  727. busyPolls: 2,
  728. firstResponse: "I started a reviewer agent",
  729. notificationTurns: [{ turnId: "turn-notify", response: "the reviewer found 3 issues" }],
  730. turnEvents: [],
  731. });
  732. assert.equal(await run(ctx, deps), 0);
  733. assert.ok(deps.pollCount() >= 3, `expected repeated polling, got ${deps.pollCount()}`);
  734. const parsed = JSON.parse(ctx.stdout.output()) as { response: string; turnResponses?: string[] };
  735. assert.equal(parsed.response, "the reviewer found 3 issues");
  736. assert.deepEqual(parsed.turnResponses, [
  737. "I started a reviewer agent",
  738. "the reviewer found 3 issues",
  739. ]);
  740. });
  741. test("a run with no background work checks the runtime once and keeps its output", async () => {
  742. const ctx = createContext(["--prompt", "hi"]);
  743. const deps = createWaitingRunDeps({ busyPolls: 0, firstResponse: "the answer", turnEvents: [] });
  744. assert.equal(await run(ctx, deps), 0);
  745. assert.equal(ctx.stdout.output(), "the answer\n");
  746. assert.equal(deps.pollCount(), 1);
  747. });