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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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 ToolCallStartedPayload,
  18. } from "@zcode/contracts";
  19. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  20. import { createToolExecutor } from "../src/tool/executor.js";
  21. import { createToolRegistry } from "../src/tool/registry.js";
  22. import type { ToolEntry } from "../src/tool/types.js";
  23. function probeEntry(overrides: Partial<ToolEntry>): ToolEntry {
  24. return {
  25. capability: "Probe for the ToolCallStarted capability flags",
  26. metadata: {
  27. name: "CapabilityProbe",
  28. description: "Probe",
  29. readOnly: false,
  30. destructive: false,
  31. concurrentSafe: true,
  32. timeoutMs: 1_000,
  33. maxOutputBytes: 10_000,
  34. sideEffectScope: "workspace",
  35. riskLevel: "low",
  36. needsApproval: false,
  37. },
  38. handler: async () => ({ ok: true }),
  39. inputSchema: { type: "object" },
  40. outputSchema: { type: "object" },
  41. permission: {
  42. permission: "capabilityProbe",
  43. reason: "probe",
  44. riskLevel: "low",
  45. sideEffectScope: "workspace",
  46. needsApproval: false,
  47. patternSources: ["toolName"],
  48. denyPriority: "beforeAsk",
  49. },
  50. resultBudget: { maxInlineBytes: 10_000, maxModelBytes: 10_000, strategy: "truncate" },
  51. timeout: { defaultMs: 1_000, maxMs: 1_000, allowCallOverride: false },
  52. cancellation: { supported: false, cleanup: "none", userVisibleMessage: "n/a" },
  53. trace: {
  54. required: true,
  55. propagateToAdapters: false,
  56. recordInput: "summary",
  57. recordOutput: "summary",
  58. },
  59. ...overrides,
  60. };
  61. }
  62. async function run(entry: ToolEntry, input: Record<string, unknown>, name: string) {
  63. const sessionId = createSessionId(name);
  64. const turnId = createTurnId(name);
  65. const traceContext = createRootTraceContext({ sessionId, turnId });
  66. const events: SessionEvent[] = [];
  67. const order: string[] = [];
  68. const registry = createToolRegistry();
  69. registry.register({
  70. ...entry,
  71. handler: async (...args) => {
  72. order.push("handler");
  73. return entry.handler(...args);
  74. },
  75. });
  76. const executor = createToolExecutor({
  77. emitEvent: async (event) => {
  78. if (event.type === SessionEventType.ToolCallStarted) order.push("started");
  79. events.push(event);
  80. },
  81. mode: "yolo",
  82. permissionBroker: {
  83. async requestPermission() {
  84. return { decision: "allow" as const };
  85. },
  86. },
  87. permissionService: new PermissionService(defaultPermissionConfig),
  88. registry,
  89. sessionId,
  90. turnId,
  91. traceContext,
  92. workingDirectory: "/probe/cwd",
  93. });
  94. await executor.execute(
  95. { id: createToolCallId(name), input, name: entry.metadata.name },
  96. { traceContext },
  97. );
  98. const started = events.find((event) => event.type === SessionEventType.ToolCallStarted);
  99. return { payload: started?.payload as ToolCallStartedPayload | undefined, order, events };
  100. }
  101. describe("ToolCallStarted carries the resolved side-effect capability", () => {
  102. it("declares the metadata flags on the payload, before the handler runs", async () => {
  103. const { payload, order } = await run(probeEntry({}), {}, "cap-meta");
  104. expect(payload).toMatchObject({
  105. toolName: "CapabilityProbe",
  106. readOnly: false,
  107. sideEffectScope: "workspace",
  108. });
  109. expect(isWorkspaceMutatingToolCall(payload!)).toBe(true);
  110. expect(order).toEqual(["started", "handler"]);
  111. });
  112. it("lets the per-call runtime capability override the metadata (the Bash read-only case)", async () => {
  113. const entry = probeEntry({
  114. resolvePermissionCapability: (input) =>
  115. (input as { command?: string }).command === "ls"
  116. ? { readOnly: true, sideEffectScope: "none" }
  117. : undefined,
  118. });
  119. const safe = await run(entry, { command: "ls" }, "cap-safe");
  120. expect(safe.payload).toMatchObject({ readOnly: true, sideEffectScope: "none" });
  121. expect(isWorkspaceMutatingToolCall(safe.payload!)).toBe(false);
  122. const unsafe = await run(entry, { command: "rm -rf build" }, "cap-unsafe");
  123. expect(unsafe.payload).toMatchObject({ readOnly: false, sideEffectScope: "workspace" });
  124. expect(isWorkspaceMutatingToolCall(unsafe.payload!)).toBe(true);
  125. });
  126. it("a read-only tool is not a write, whatever its scope", async () => {
  127. const entry = probeEntry({
  128. metadata: { ...probeEntry({}).metadata, readOnly: true, sideEffectScope: "none" },
  129. });
  130. const { payload } = await run(entry, {}, "cap-readonly");
  131. expect(payload).toMatchObject({ readOnly: true, sideEffectScope: "none" });
  132. expect(isWorkspaceMutatingToolCall(payload!)).toBe(false);
  133. });
  134. });
  135. describe("MCP execution attribution", () => {
  136. it.each([false, true])(
  137. "keeps actual plugin ownership on terminal events (failure=%s)",
  138. async (fails) => {
  139. const entry = probeEntry({});
  140. entry.metadata.mcpPresentation = {
  141. pluginId: "actual@market",
  142. serverName: "server",
  143. toolName: "tool",
  144. };
  145. entry.handler = async () => {
  146. if (fails) throw new Error("tool failed");
  147. // 注册表在执行期间变化,也不能丢失本次执行的归属。
  148. entry.metadata.mcpPresentation!.pluginId = "changed@market";
  149. return { ok: true };
  150. };
  151. const { events } = await run(entry, {}, "mcp-owner");
  152. const terminal = events.filter(
  153. (event) =>
  154. event.type === (fails ? SessionEventType.ToolCallError : SessionEventType.ToolCallResult),
  155. );
  156. expect(terminal).toHaveLength(1);
  157. expect(terminal[0].payload).toMatchObject({ pluginId: "actual@market" });
  158. },
  159. );
  160. });