model-tool-call-validation.test.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createMessageId,
  4. createPartId,
  5. createRootTraceContext,
  6. createSessionId,
  7. createToolCallId,
  8. createTurnId,
  9. } from "@zcode/contracts";
  10. import type { Logger, ModelSelection, ToolCall } from "../src/runtime/deps.js";
  11. import {
  12. normalizeModelToolCallsForRuntime,
  13. requireRuntimeToolCallName,
  14. } from "../src/runtime/helpers/model-tool-call-validation.js";
  15. import { persistPendingToolPart } from "../src/runtime/methods/tool-part-persistence.js";
  16. describe("model tool call validation", () => {
  17. it("trims model tool names before runtime execution", () => {
  18. const context = createValidationContext();
  19. const toolCalls = normalizeModelToolCallsForRuntime(
  20. [
  21. {
  22. id: "call_read",
  23. input: {},
  24. name: " Read ",
  25. },
  26. ],
  27. context,
  28. );
  29. expect(toolCalls).toEqual([
  30. {
  31. id: "call_read",
  32. input: {},
  33. name: "Read",
  34. },
  35. ]);
  36. });
  37. it.each(["", " "])("preserves recoverable model tool name %j", (name) => {
  38. const logger = createTestLogger();
  39. const context = createValidationContext({ logger });
  40. expect(
  41. normalizeModelToolCallsForRuntime(
  42. [
  43. {
  44. id: "call_empty",
  45. input: {},
  46. name,
  47. },
  48. ],
  49. context,
  50. ),
  51. ).toEqual([{ id: "call_empty", input: {}, name }]);
  52. expect(logger.warn).not.toHaveBeenCalled();
  53. });
  54. it.each([
  55. { id: "call_provider_empty", name: "", providerExecuted: true },
  56. { id: "", name: "", providerExecuted: false },
  57. { id: "call_missing", name: undefined, providerExecuted: false },
  58. { id: "call_null", name: null, providerExecuted: false },
  59. { id: "call_number", name: 42, providerExecuted: false },
  60. { id: "call_object", name: {}, providerExecuted: false },
  61. ])("rejects non-recoverable model tool identity %#", (toolCall) => {
  62. const logger = createTestLogger();
  63. const context = createValidationContext({ logger });
  64. expect(() =>
  65. normalizeModelToolCallsForRuntime([{ ...toolCall, input: {} }] as never, context),
  66. ).toThrow("Model returned an invalid tool call: tool name is empty.");
  67. expect(logger.warn).toHaveBeenCalledWith(
  68. "Model returned invalid tool call",
  69. expect.objectContaining({
  70. event: "model.invalid_tool_call",
  71. model: "test-provider/test-model",
  72. source: "test",
  73. status: "failed",
  74. toolCallId: toolCall.id,
  75. toolCallIndex: 0,
  76. }),
  77. );
  78. });
  79. it("keeps the execution-only tool-name guard strict for an empty name", () => {
  80. expect(() =>
  81. requireRuntimeToolCallName(
  82. { id: "call_empty_execution_guard", name: "" },
  83. createValidationContext(),
  84. ),
  85. ).toThrow("Model returned an invalid tool call: tool name is empty.");
  86. });
  87. it("persists empty provider names behind the non-empty storage projection", async () => {
  88. const logger = createTestLogger();
  89. const sessionId = createSessionId("empty-tool-persist");
  90. const turnId = createTurnId("empty-tool-persist");
  91. const traceContext = createRootTraceContext({ sessionId, turnId });
  92. const persistPart = vi.fn();
  93. await persistPendingToolPart(
  94. {
  95. getSessionModelSelection: () => createModelSelection(),
  96. logger,
  97. persistPart,
  98. sessionId,
  99. } as never,
  100. {
  101. assistantMessageId: createMessageId("assistant-empty-tool"),
  102. input: {},
  103. partID: createPartId("empty-tool"),
  104. toolCall: {
  105. id: createToolCallId("empty-tool"),
  106. input: {},
  107. name: "",
  108. status: "scheduled",
  109. } satisfies ToolCall,
  110. traceContext,
  111. },
  112. );
  113. expect(persistPart).toHaveBeenCalledWith(
  114. expect.objectContaining({
  115. metadata: { providerToolName: "" },
  116. state: expect.objectContaining({
  117. raw: JSON.stringify({ tool: "empty_tool_name", input: {} }),
  118. status: "pending",
  119. }),
  120. tool: "empty_tool_name",
  121. }),
  122. traceContext,
  123. );
  124. });
  125. it("persists MCP presentation before completion for stopped-call hydration", async () => {
  126. const persistPart = vi.fn();
  127. const sessionId = createSessionId("mcp-pending-persist");
  128. const traceContext = createRootTraceContext({
  129. sessionId,
  130. turnId: createTurnId("mcp-pending-persist"),
  131. });
  132. const display = {
  133. kind: "mcp_tool" as const,
  134. serverName: "firebase",
  135. toolName: "read_resources",
  136. };
  137. await persistPendingToolPart(
  138. {
  139. getSessionModelSelection: () => createModelSelection(),
  140. persistPart,
  141. sessionId,
  142. } as never,
  143. {
  144. assistantMessageId: createMessageId("assistant-mcp-pending"),
  145. input: {},
  146. metadata: { schemaVersion: 1, display },
  147. partID: createPartId("mcp-pending"),
  148. toolCall: {
  149. id: createToolCallId("mcp-pending"),
  150. input: {},
  151. name: "opaque-provider-name",
  152. status: "scheduled",
  153. } satisfies ToolCall,
  154. traceContext,
  155. },
  156. );
  157. expect(persistPart).toHaveBeenCalledWith(
  158. expect.objectContaining({ metadata: { schemaVersion: 1, display } }),
  159. traceContext,
  160. );
  161. });
  162. });
  163. function createValidationContext(options: { logger?: Logger } = {}) {
  164. const sessionId = createSessionId("tool-validation");
  165. const turnId = createTurnId("tool-validation");
  166. return {
  167. logger: options.logger,
  168. model: createModelSelection(),
  169. source: "test",
  170. traceContext: createRootTraceContext({ sessionId, turnId }),
  171. };
  172. }
  173. function createModelSelection(): ModelSelection {
  174. return {
  175. modelId: "test-model" as ModelSelection["modelId"],
  176. providerId: "test-provider" as ModelSelection["providerId"],
  177. };
  178. }
  179. function createTestLogger(): Logger {
  180. return {
  181. child: vi.fn(() => createTestLogger()),
  182. debug: vi.fn(),
  183. error: vi.fn(),
  184. info: vi.fn(),
  185. warn: vi.fn(),
  186. };
  187. }