tool-unsettled-call.test.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. CoreErrorType,
  4. createRootTraceContext,
  5. createSessionId,
  6. createToolCallId,
  7. createTurnId,
  8. } from "@zcode/contracts";
  9. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  10. import { createToolExecutor } from "../src/tool/executor.js";
  11. import { createToolRegistry } from "../src/tool/registry.js";
  12. import { modelContentForToolResult } from "../src/runtime/helpers/tool-result.js";
  13. import type { ToolEntry, ToolExecutionContext } from "../src/tool/types.js";
  14. /**
  15. * 规格 0.15:调用在 handler 返回之前超时或取消时,工具可以把对账说明追加到错误文本。
  16. *
  17. * 会话控制的写工具靠回执把请求身份交给模型;可回执送不回来时,模型只看到 "timed out",拿不到
  18. * 身份就只能另起新请求,于是重复建会话或重复发消息。执行器在这两种错误上调用
  19. * `describeUnsettledCall`,让身份随同一条错误送到模型手里。
  20. */
  21. const NOTE = "requestId=R1; pass it as retryOf to retry this exact request.";
  22. function entry(input: {
  23. name: string;
  24. timeoutMs: number;
  25. handler: (context: ToolExecutionContext) => Promise<unknown>;
  26. describeUnsettledCall?: ToolEntry["describeUnsettledCall"];
  27. }): ToolEntry {
  28. return {
  29. capability: "test",
  30. metadata: {
  31. name: input.name,
  32. description: "test tool",
  33. readOnly: false,
  34. destructive: false,
  35. concurrentSafe: false,
  36. timeoutMs: input.timeoutMs,
  37. maxOutputBytes: 1000,
  38. sideEffectScope: "none",
  39. riskLevel: "low",
  40. needsApproval: false,
  41. },
  42. handler: (_input: unknown, context: ToolExecutionContext) => input.handler(context),
  43. inputSchema: { type: "object", properties: {} },
  44. outputSchema: { type: "object", properties: {} },
  45. ...(input.describeUnsettledCall ? { describeUnsettledCall: input.describeUnsettledCall } : {}),
  46. } as unknown as ToolEntry;
  47. }
  48. /** 永不返回的 handler:只有超时或取消能结束它。 */
  49. const hang = (context: ToolExecutionContext) =>
  50. new Promise<never>((_resolve, reject) => {
  51. context.abortSignal.addEventListener("abort", () => reject(context.abortSignal.reason));
  52. });
  53. async function run(tool: ToolEntry, options: { signal?: AbortSignal } = {}) {
  54. const sessionId = createSessionId("unsettled-call");
  55. const turnId = createTurnId("unsettled-call");
  56. const traceContext = createRootTraceContext({ sessionId, turnId });
  57. const registry = createToolRegistry();
  58. registry.register(tool);
  59. const executor = createToolExecutor({
  60. emitEvent: async () => undefined,
  61. permissionService: new PermissionService(defaultPermissionConfig),
  62. registry,
  63. sessionId,
  64. turnId,
  65. traceContext,
  66. });
  67. const callId = createToolCallId("unsettled-call");
  68. const result = await executor.execute(
  69. { id: callId, input: { probe: true }, name: tool.metadata.name },
  70. { traceContext, ...options },
  71. );
  72. return { result, callId, text: String(modelContentForToolResult(result)) };
  73. }
  74. describe("describeUnsettledCall", () => {
  75. it("appends the note to a timeout and passes the call's input and id", async () => {
  76. const seen: unknown[] = [];
  77. const { result, callId, text } = await run(
  78. entry({
  79. name: "TimesOut",
  80. timeoutMs: 20,
  81. handler: hang,
  82. describeUnsettledCall: (input, toolCallId) => {
  83. seen.push({ input, toolCallId });
  84. return NOTE;
  85. },
  86. }),
  87. );
  88. expect(result.success).toBe(false);
  89. expect(result.error?.type).toBe(CoreErrorType.ToolTimeout);
  90. expect(text).toContain("timed out after 20ms");
  91. expect(text).toContain(NOTE);
  92. expect(seen).toEqual([{ input: { probe: true }, toolCallId: callId }]);
  93. });
  94. it("appends the note when the call is cancelled mid-execution", async () => {
  95. const controller = new AbortController();
  96. const pending = run(
  97. entry({
  98. name: "Cancelled",
  99. timeoutMs: 60_000,
  100. handler: (context) => {
  101. // handler 已在执行(请求可能已提交)之后才取消——这正是需要身份的时刻。
  102. setTimeout(() => controller.abort(), 10);
  103. return hang(context);
  104. },
  105. describeUnsettledCall: () => NOTE,
  106. }),
  107. { signal: controller.signal },
  108. );
  109. const { result, text } = await pending;
  110. expect(result.success).toBe(false);
  111. expect(result.error?.type).toBe(CoreErrorType.ToolCancelled);
  112. expect(text).toContain(NOTE);
  113. });
  114. it("leaves a timeout untouched for tools that do not declare it", async () => {
  115. const { result, text } = await run(
  116. entry({ name: "PlainTimeout", timeoutMs: 20, handler: hang }),
  117. );
  118. expect(result.error?.type).toBe(CoreErrorType.ToolTimeout);
  119. expect(text).not.toContain("requestId");
  120. });
  121. // 只作用于超时与取消:handler 自己抛出的错误发生在它能返回结构化结果的位置,
  122. // 会话控制把提交之后的异常转成了带 requestId 的回执,这里不该再追加一遍。
  123. it("does not touch errors the handler throws itself", async () => {
  124. const { result, text } = await run(
  125. entry({
  126. name: "Throws",
  127. timeoutMs: 60_000,
  128. handler: async () => {
  129. throw new Error("owner refused");
  130. },
  131. describeUnsettledCall: () => NOTE,
  132. }),
  133. );
  134. expect(result.success).toBe(false);
  135. expect(text).toContain("owner refused");
  136. expect(text).not.toContain(NOTE);
  137. });
  138. it("skips the note when the tool returns nothing to add", async () => {
  139. const { text } = await run(
  140. entry({
  141. name: "NothingToAdd",
  142. timeoutMs: 20,
  143. handler: hang,
  144. describeUnsettledCall: () => undefined,
  145. }),
  146. );
  147. expect(text).toContain("timed out after 20ms");
  148. expect(text).not.toContain("requestId");
  149. });
  150. });