workflow-driver-tool-activity.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. /**
  2. * driver 侧的工具活动面(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Amend-resume」):
  3. * - actor runtime 的 `ToolCallStarted` 会话事件里、解析后能力判为「会改写工作区」的那一条 → onMutating;
  4. * - 每个 ask 至多一次;reset 之后重新武装;
  5. * - 只读工具、别的会话、别的事件种类一律不算;
  6. * - 两个计数(全部调用 / 碰过外部世界的调用)由这份订阅数出来,喂给 statsFromTurn。
  7. */
  8. import { describe, expect, it, vi } from "vitest";
  9. import {
  10. SessionEventType,
  11. createSessionId,
  12. type SessionEvent,
  13. type SessionEventSink,
  14. } from "@zcode/contracts";
  15. import type { TurnResult } from "@zcode/core";
  16. import { createActorToolActivity } from "../src/app/workflow-driver-tool-activity.js";
  17. import { deriveToolTarget, summarizeToolCall } from "../src/app/workflow-driver-tool-target.js";
  18. import { statsFromTurn } from "../src/app/workflow-driver-helpers.js";
  19. const SESSION = createSessionId("sess-actor");
  20. function stubRuntime() {
  21. const sinks = new Set<SessionEventSink>();
  22. return {
  23. unsubscribeCalls: 0,
  24. subscribeEvents(sink: SessionEventSink) {
  25. sinks.add(sink);
  26. return () => {
  27. this.unsubscribeCalls++;
  28. sinks.delete(sink);
  29. };
  30. },
  31. emit(type: SessionEventType, payload: Record<string, unknown>, sessionId: string = SESSION) {
  32. const event = {
  33. id: "evt",
  34. sessionId,
  35. type,
  36. timestamp: new Date(),
  37. traceId: "trace",
  38. sequenceNumber: 1,
  39. payload,
  40. } as unknown as SessionEvent;
  41. for (const sink of sinks) void sink.onSessionEvent(event);
  42. },
  43. };
  44. }
  45. const started = (flags: Record<string, unknown>) => ({
  46. toolCallId: "tc",
  47. toolName: "Probe",
  48. startedAt: new Date(),
  49. ...flags,
  50. });
  51. describe("createActorToolActivity", () => {
  52. it("reports the first workspace write of an ask once, and again after reset", () => {
  53. const onMutating = vi.fn();
  54. const activity = createActorToolActivity({ onMutating });
  55. const runtime = stubRuntime();
  56. activity.observe(runtime as never, SESSION);
  57. runtime.emit(
  58. SessionEventType.ToolCallStarted,
  59. started({ toolName: "Read", readOnly: true, sideEffectScope: "none" }),
  60. );
  61. expect(onMutating).not.toHaveBeenCalled();
  62. runtime.emit(
  63. SessionEventType.ToolCallStarted,
  64. started({ toolName: "Write", readOnly: false, sideEffectScope: "workspace" }),
  65. );
  66. runtime.emit(
  67. SessionEventType.ToolCallStarted,
  68. started({ toolName: "Edit", readOnly: false, sideEffectScope: "workspace" }),
  69. );
  70. expect(onMutating).toHaveBeenCalledTimes(1);
  71. activity.reset();
  72. runtime.emit(
  73. SessionEventType.ToolCallStarted,
  74. started({ toolName: "Bash", readOnly: false, sideEffectScope: "system" }),
  75. );
  76. expect(onMutating).toHaveBeenCalledTimes(2);
  77. });
  78. it("ignores other sessions, other event types, and tools that only touch the network or the session", () => {
  79. const onMutating = vi.fn();
  80. const activity = createActorToolActivity({ onMutating });
  81. const runtime = stubRuntime();
  82. activity.observe(runtime as never, SESSION);
  83. runtime.emit(
  84. SessionEventType.ToolCallStarted,
  85. started({ readOnly: false, sideEffectScope: "workspace" }),
  86. "sess-other",
  87. );
  88. runtime.emit(SessionEventType.ToolCallResult, {
  89. toolCallId: "tc",
  90. readOnly: false,
  91. sideEffectScope: "workspace",
  92. });
  93. runtime.emit(
  94. SessionEventType.ToolCallStarted,
  95. started({ toolName: "WebFetch", readOnly: false, sideEffectScope: "network" }),
  96. );
  97. runtime.emit(
  98. SessionEventType.ToolCallStarted,
  99. started({ toolName: "submit_result", readOnly: false, sideEffectScope: "session" }),
  100. );
  101. runtime.emit(
  102. SessionEventType.ToolCallStarted,
  103. started({ toolName: "escalate", readOnly: false, sideEffectScope: "session" }),
  104. );
  105. expect(onMutating).not.toHaveBeenCalled();
  106. });
  107. it("treats a call without flags as a write (conservative), and unsubscribes cleanly", () => {
  108. const onMutating = vi.fn();
  109. const activity = createActorToolActivity({ onMutating });
  110. const runtime = stubRuntime();
  111. activity.observe(runtime as never, SESSION);
  112. runtime.emit(SessionEventType.ToolCallStarted, started({}));
  113. expect(onMutating).toHaveBeenCalledTimes(1);
  114. activity.unsubscribe();
  115. expect(runtime.unsubscribeCalls).toBe(1);
  116. activity.reset();
  117. runtime.emit(SessionEventType.ToolCallStarted, started({}));
  118. expect(onMutating).toHaveBeenCalledTimes(1);
  119. });
  120. it("is a no-op on a runtime without subscribeEvents", () => {
  121. const activity = createActorToolActivity({ onMutating: () => {} });
  122. expect(() => activity.observe({} as never, SESSION)).not.toThrow();
  123. expect(() => activity.unsubscribe()).not.toThrow();
  124. });
  125. });
  126. describe("statsFromTurn · 工具计数来自观察面,不是 TurnResult", () => {
  127. const result = (totalTokens: number, modelRequestCount: number) =>
  128. ({
  129. response: "done",
  130. usage: { totalTokens, modelRequestCount },
  131. events: [],
  132. }) as unknown as TurnResult;
  133. it("原样带上观察到的两个计数", () => {
  134. expect(statsFromTurn(result(42, 2), { toolCalls: 4, worldToolCalls: 2 })).toEqual({
  135. tokens: 42,
  136. toolCalls: 4,
  137. turns: 2,
  138. worldToolCalls: 2,
  139. });
  140. });
  141. it("只交了结果的 typed ask 是纯的:toolCalls 1(submit_result)而 worldToolCalls 0", () => {
  142. expect(statsFromTurn(result(7, 1), { toolCalls: 1, worldToolCalls: 0 })).toEqual({
  143. tokens: 7,
  144. toolCalls: 1,
  145. turns: 1,
  146. worldToolCalls: 0,
  147. });
  148. });
  149. it("计数不看 TurnResult.events —— 那里没有工具事件(本轮修的正是这个 0)", () => {
  150. const withToolEvents = {
  151. response: "done",
  152. usage: { totalTokens: 5, modelRequestCount: 1 },
  153. events: [
  154. {
  155. type: SessionEventType.ToolCallStarted,
  156. payload: started({ readOnly: false, sideEffectScope: "workspace" }),
  157. },
  158. {
  159. type: SessionEventType.ToolCallStarted,
  160. payload: started({ readOnly: true, sideEffectScope: "none" }),
  161. },
  162. ],
  163. } as unknown as TurnResult;
  164. expect(statsFromTurn(withToolEvents, { toolCalls: 0, worldToolCalls: 0 })).toMatchObject({
  165. toolCalls: 0,
  166. worldToolCalls: 0,
  167. });
  168. });
  169. });
  170. describe("观察面的计数(ask 内累加,startAsk 归零)", () => {
  171. it("数出总调用数与其中碰过外部世界的那些;协议工具不计入 world;reset 之后重新数", () => {
  172. const activity = createActorToolActivity({ onMutating: () => {} });
  173. const runtime = stubRuntime();
  174. activity.observe(runtime as never, SESSION);
  175. expect(activity.counts()).toEqual({ toolCalls: 0, worldToolCalls: 0 });
  176. runtime.emit(
  177. SessionEventType.ToolCallStarted,
  178. started({ toolName: "Read", readOnly: true, sideEffectScope: "none" }),
  179. );
  180. runtime.emit(
  181. SessionEventType.ToolCallStarted,
  182. started({ toolName: "Write", readOnly: false, sideEffectScope: "workspace" }),
  183. );
  184. runtime.emit(
  185. SessionEventType.ToolCallStarted,
  186. started({ toolName: "Edit", readOnly: false, sideEffectScope: "workspace" }),
  187. );
  188. // 协议工具(交结果 / 提问)计入总数,但不算碰过外部世界——否则每条 typed ask 都不再是纯的。
  189. runtime.emit(
  190. SessionEventType.ToolCallStarted,
  191. started({ toolName: "submit_result", readOnly: false, sideEffectScope: "session" }),
  192. );
  193. runtime.emit(
  194. SessionEventType.ToolCallStarted,
  195. started({ toolName: "escalate", readOnly: false, sideEffectScope: "session" }),
  196. );
  197. // 别的会话不算。
  198. runtime.emit(
  199. SessionEventType.ToolCallStarted,
  200. started({ readOnly: false, sideEffectScope: "workspace" }),
  201. "sess-other",
  202. );
  203. expect(activity.counts()).toEqual({ toolCalls: 5, worldToolCalls: 3 });
  204. activity.reset();
  205. expect(activity.counts()).toEqual({ toolCalls: 0, worldToolCalls: 0 });
  206. // Read 声明的范围是 none(无副作用),但它的答案取决于工作区 —— 算碰过。
  207. runtime.emit(
  208. SessionEventType.ToolCallStarted,
  209. started({ toolName: "Read", readOnly: true, sideEffectScope: "none" }),
  210. );
  211. expect(activity.counts()).toEqual({ toolCalls: 1, worldToolCalls: 1 });
  212. });
  213. });
  214. describe("lastTool · 最近一次真正开跑的工具调用", () => {
  215. const scheduled = (toolCallId: string, toolName: string, input: unknown) => ({
  216. toolCallId,
  217. assistantMessageId: "m1",
  218. toolName,
  219. input,
  220. schedule: { parallelGroups: [], executionOrder: [] },
  221. });
  222. const startedCall = (toolCallId: string, toolName: string) => ({
  223. toolCallId,
  224. toolName,
  225. startedAt: new Date(),
  226. readOnly: true,
  227. sideEffectScope: "none",
  228. });
  229. it("名字来自 started,目标来自更早的 scheduled 入参;后一次覆盖前一次", () => {
  230. const activity = createActorToolActivity({ onMutating: () => {} });
  231. const runtime = stubRuntime();
  232. activity.observe(runtime as never, SESSION);
  233. expect(activity.lastTool()).toBeUndefined();
  234. runtime.emit(
  235. SessionEventType.ToolCallScheduled,
  236. scheduled("tc-1", "Read", {
  237. file_path: "/repo/src/auth/session.ts",
  238. }),
  239. );
  240. runtime.emit(SessionEventType.ToolCallStarted, startedCall("tc-1", "Read"));
  241. expect(activity.lastTool()).toEqual({ name: "Read", target: "/repo/src/auth/session.ts" });
  242. runtime.emit(
  243. SessionEventType.ToolCallScheduled,
  244. scheduled("tc-2", "Bash", {
  245. command: "pnpm exec vitest run tests/auth.test.ts\n# 第二行不算",
  246. }),
  247. );
  248. runtime.emit(SessionEventType.ToolCallStarted, startedCall("tc-2", "Bash"));
  249. expect(activity.lastTool()).toEqual({
  250. name: "Bash",
  251. target: "pnpm exec vitest run tests/auth.test.ts",
  252. });
  253. });
  254. it("只在 started 上落:scheduled 之后被拒掉、从未开跑的调用不冒充当前动作", () => {
  255. const activity = createActorToolActivity({ onMutating: () => {} });
  256. const runtime = stubRuntime();
  257. activity.observe(runtime as never, SESSION);
  258. runtime.emit(
  259. SessionEventType.ToolCallScheduled,
  260. scheduled("tc-1", "Write", { file_path: "/x" }),
  261. );
  262. expect(activity.lastTool()).toBeUndefined();
  263. });
  264. it("没有 scheduled 那一手时仍给出名字,只是没有目标", () => {
  265. const activity = createActorToolActivity({ onMutating: () => {} });
  266. const runtime = stubRuntime();
  267. activity.observe(runtime as never, SESSION);
  268. runtime.emit(SessionEventType.ToolCallStarted, startedCall("tc-lonely", "Glob"));
  269. expect(activity.lastTool()).toEqual({ name: "Glob" });
  270. });
  271. it("别的会话不算;reset 之后重新从「没有」开始", () => {
  272. const activity = createActorToolActivity({ onMutating: () => {} });
  273. const runtime = stubRuntime();
  274. activity.observe(runtime as never, SESSION);
  275. runtime.emit(
  276. SessionEventType.ToolCallScheduled,
  277. scheduled("tc-other", "Read", { file_path: "/other" }),
  278. "sess-other",
  279. );
  280. runtime.emit(SessionEventType.ToolCallStarted, startedCall("tc-other", "Read"), "sess-other");
  281. expect(activity.lastTool()).toBeUndefined();
  282. runtime.emit(
  283. SessionEventType.ToolCallScheduled,
  284. scheduled("tc-1", "Read", { file_path: "/mine" }),
  285. );
  286. runtime.emit(SessionEventType.ToolCallStarted, startedCall("tc-1", "Read"));
  287. expect(activity.lastTool()).toEqual({ name: "Read", target: "/mine" });
  288. activity.reset();
  289. expect(activity.lastTool()).toBeUndefined();
  290. });
  291. });
  292. describe("目标线索的分寸(deriveToolTarget / summarizeToolCall)", () => {
  293. it("按键名认,不按工具名认:file_path > path > command > pattern > url > query", () => {
  294. expect(deriveToolTarget({ file_path: "/a.ts", command: "rm -rf /" })).toBe("/a.ts");
  295. expect(deriveToolTarget({ path: "src", pattern: "TODO" })).toBe("src");
  296. expect(deriveToolTarget({ pattern: "TODO", url: "https://x" })).toBe("TODO");
  297. expect(deriveToolTarget({ url: "https://example.com/a" })).toBe("https://example.com/a");
  298. expect(deriveToolTarget({ query: "release notes" })).toBe("release notes");
  299. });
  300. it("认不出就缺席:没有已知键、值不是字符串、空串、不是对象", () => {
  301. expect(deriveToolTarget({ todos: [{ content: "x" }] })).toBeUndefined();
  302. expect(deriveToolTarget({ file_path: 42 })).toBeUndefined();
  303. expect(deriveToolTarget({ command: " " })).toBeUndefined();
  304. expect(deriveToolTarget("/a.ts")).toBeUndefined();
  305. expect(deriveToolTarget(undefined)).toBeUndefined();
  306. expect(deriveToolTarget(["/a.ts"])).toBeUndefined();
  307. });
  308. it("命令只取第一行并压掉连续空白(整段 heredoc 不是「在跑什么」)", () => {
  309. expect(deriveToolTarget({ command: " git log --oneline \nwhile read x; do :; done" })).toBe(
  310. "git log --oneline",
  311. );
  312. });
  313. it("超长路径保尾(文件名才是分辨点),超长命令保头", () => {
  314. const deepPath = `/${"segment/".repeat(40)}session.ts`;
  315. const pathTarget = deriveToolTarget({ file_path: deepPath })!;
  316. expect(pathTarget.length).toBe(120);
  317. expect(pathTarget.startsWith("…")).toBe(true);
  318. expect(pathTarget.endsWith("session.ts")).toBe(true);
  319. const longCommand = `echo ${"a".repeat(300)}`;
  320. const commandTarget = deriveToolTarget({ command: longCommand })!;
  321. expect(commandTarget.length).toBe(120);
  322. expect(commandTarget.startsWith("echo a")).toBe(true);
  323. });
  324. it("没有名字就整条缺席;名字超长截到 64", () => {
  325. expect(summarizeToolCall({ input: { file_path: "/a.ts" } })).toBeUndefined();
  326. expect(summarizeToolCall({ toolName: " " })).toBeUndefined();
  327. expect(summarizeToolCall({ toolName: "T".repeat(100) })?.name).toHaveLength(64);
  328. });
  329. });