tool-call-started-capability.test.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /**
  2. * `ToolCallStarted` 载荷上的解析后副作用能力(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md
  3. * 「Amend-resume」)。dynamic-workflow 的 driver 据它在子代理动手前关导入缓存,所以这里钉三件事:
  4. * 1. 元数据声明的 readOnly / sideEffectScope 原样上载荷;
  5. * 2. 按入参解析的运行时能力(`resolvePermissionCapability`,Bash 的只读命令判定就是它)覆盖元数据;
  6. * 3. 事件在 handler 之前发出——handler 一开跑,订阅者就已经知道了。
  7. */
  8. import { describe, expect, it } from "vitest";
  9. import {
  10. SessionEventType,
  11. createRootTraceContext,
  12. createSessionId,
  13. createToolCallId,
  14. createTurnId,
  15. isWorkspaceMutatingToolCall,
  16. type SessionEvent,
  17. type ExecutionShellSelection,
  18. type ToolCallStartedPayload,
  19. } from "@zcode/contracts";
  20. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  21. import { createToolExecutor } from "../src/tool/executor.js";
  22. import { createToolRegistry } from "../src/tool/registry.js";
  23. import type { ToolEntry } from "../src/tool/types.js";
  24. import { bashToolEntry } from "../src/tool/handlers/bash.js";
  25. function probeEntry(overrides: Partial<ToolEntry>): ToolEntry {
  26. return {
  27. capability: "Probe for the ToolCallStarted capability flags",
  28. metadata: {
  29. name: "CapabilityProbe",
  30. description: "Probe",
  31. readOnly: false,
  32. destructive: false,
  33. concurrentSafe: true,
  34. timeoutMs: 1_000,
  35. maxOutputBytes: 10_000,
  36. sideEffectScope: "workspace",
  37. riskLevel: "low",
  38. needsApproval: false,
  39. },
  40. handler: async () => ({ ok: true }),
  41. inputSchema: { type: "object" },
  42. outputSchema: { type: "object" },
  43. permission: {
  44. permission: "capabilityProbe",
  45. reason: "probe",
  46. riskLevel: "low",
  47. sideEffectScope: "workspace",
  48. needsApproval: false,
  49. patternSources: ["toolName"],
  50. denyPriority: "beforeAsk",
  51. },
  52. resultBudget: { maxInlineBytes: 10_000, maxModelBytes: 10_000, strategy: "truncate" },
  53. timeout: { defaultMs: 1_000, maxMs: 1_000, allowCallOverride: false },
  54. cancellation: { supported: false, cleanup: "none", userVisibleMessage: "n/a" },
  55. trace: {
  56. required: true,
  57. propagateToAdapters: false,
  58. recordInput: "summary",
  59. recordOutput: "summary",
  60. },
  61. ...overrides,
  62. };
  63. }
  64. async function run(
  65. entry: ToolEntry,
  66. input: Record<string, unknown>,
  67. name: string,
  68. bashShellSelection?: ExecutionShellSelection,
  69. ) {
  70. const sessionId = createSessionId(name);
  71. const turnId = createTurnId(name);
  72. const traceContext = createRootTraceContext({ sessionId, turnId });
  73. const events: SessionEvent[] = [];
  74. const order: string[] = [];
  75. const registry = createToolRegistry();
  76. registry.register({
  77. ...entry,
  78. handler: async (...args) => {
  79. order.push("handler");
  80. return entry.handler(...args);
  81. },
  82. });
  83. const executor = createToolExecutor({
  84. emitEvent: async (event) => {
  85. if (event.type === SessionEventType.ToolCallStarted) order.push("started");
  86. events.push(event);
  87. },
  88. mode: "yolo",
  89. bashShellSelection,
  90. permissionBroker: {
  91. async requestPermission() {
  92. return { decision: "allow" as const };
  93. },
  94. },
  95. permissionService: new PermissionService(defaultPermissionConfig),
  96. registry,
  97. sessionId,
  98. turnId,
  99. traceContext,
  100. workingDirectory: "/probe/cwd",
  101. });
  102. await executor.execute(
  103. { id: createToolCallId(name), input, name: entry.metadata.name },
  104. { traceContext },
  105. );
  106. const started = events.find((event) => event.type === SessionEventType.ToolCallStarted);
  107. return { payload: started?.payload as ToolCallStartedPayload | undefined, order, events };
  108. }
  109. describe("ToolCallStarted carries the resolved side-effect capability", () => {
  110. it("keeps explicitly permitted CMD commands marked as system side effects", async () => {
  111. const entry = { ...bashToolEntry, handler: async () => ({}) };
  112. const { payload } = await run(entry, { command: "type README.md" }, "cmd-capability", {
  113. dialect: "cmd",
  114. source: "user-config",
  115. display: { name: "CMD" },
  116. });
  117. expect(payload).toMatchObject({ readOnly: false, sideEffectScope: "system" });
  118. });
  119. it("declares the metadata flags on the payload, before the handler runs", async () => {
  120. const { payload, order } = await run(probeEntry({}), {}, "cap-meta");
  121. expect(payload).toMatchObject({
  122. toolName: "CapabilityProbe",
  123. readOnly: false,
  124. sideEffectScope: "workspace",
  125. });
  126. expect(isWorkspaceMutatingToolCall(payload!)).toBe(true);
  127. expect(order).toEqual(["started", "handler"]);
  128. });
  129. it("lets the per-call runtime capability override the metadata (the Bash read-only case)", async () => {
  130. const entry = probeEntry({
  131. resolvePermissionCapability: (input) =>
  132. (input as { command?: string }).command === "ls"
  133. ? { readOnly: true, sideEffectScope: "none" }
  134. : undefined,
  135. });
  136. const safe = await run(entry, { command: "ls" }, "cap-safe");
  137. expect(safe.payload).toMatchObject({ readOnly: true, sideEffectScope: "none" });
  138. expect(isWorkspaceMutatingToolCall(safe.payload!)).toBe(false);
  139. const unsafe = await run(entry, { command: "rm -rf build" }, "cap-unsafe");
  140. expect(unsafe.payload).toMatchObject({ readOnly: false, sideEffectScope: "workspace" });
  141. expect(isWorkspaceMutatingToolCall(unsafe.payload!)).toBe(true);
  142. });
  143. it("a read-only tool is not a write, whatever its scope", async () => {
  144. const entry = probeEntry({
  145. metadata: { ...probeEntry({}).metadata, readOnly: true, sideEffectScope: "none" },
  146. });
  147. const { payload } = await run(entry, {}, "cap-readonly");
  148. expect(payload).toMatchObject({ readOnly: true, sideEffectScope: "none" });
  149. expect(isWorkspaceMutatingToolCall(payload!)).toBe(false);
  150. });
  151. });
  152. describe("MCP execution attribution", () => {
  153. it.each([false, true])(
  154. "keeps actual plugin ownership on terminal events (failure=%s)",
  155. async (fails) => {
  156. const entry = probeEntry({});
  157. entry.metadata.mcpPresentation = {
  158. pluginId: "actual@market",
  159. serverName: "server",
  160. toolName: "tool",
  161. };
  162. entry.handler = async () => {
  163. if (fails) throw new Error("tool failed");
  164. // 注册表在执行期间变化,也不能丢失本次执行的归属。
  165. entry.metadata.mcpPresentation!.pluginId = "changed@market";
  166. return { ok: true };
  167. };
  168. const { events } = await run(entry, {}, "mcp-owner");
  169. const terminal = events.filter(
  170. (event) =>
  171. event.type === (fails ? SessionEventType.ToolCallError : SessionEventType.ToolCallResult),
  172. );
  173. expect(terminal).toHaveLength(1);
  174. expect(terminal[0].payload).toMatchObject({ pluginId: "actual@market" });
  175. },
  176. );
  177. });