tool-input-validation-error.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. import { describe, expect, it } from "vitest";
  2. import { createErrorResult } from "../src/tool/executor/errors.js";
  3. import { validateInitialModelToolInput, validateInput } from "../src/tool/executor/validation.js";
  4. import { askUserQuestionToolEntry } from "../src/tool/handlers/ask-user-question.js";
  5. import { bashToolEntry } from "../src/tool/handlers/bash.js";
  6. import { jsToolEntry } from "../src/tool/handlers/node-repl.js";
  7. import { exitPlanModeToolEntry } from "../src/tool/handlers/plan-mode.js";
  8. import { readToolEntry } from "../src/tool/handlers/read.js";
  9. import { readSessionContextToolEntry } from "../src/tool/handlers/read-session-context.js";
  10. import { skillToolEntry } from "../src/tool/handlers/skill.js";
  11. import { todoWriteToolEntry } from "../src/tool/handlers/todo.js";
  12. import { formatToolInputValidationError } from "../src/tool/input-validation-model-content.js";
  13. import { prepareInitialToolExecutionInput } from "../src/tool/input-normalization.js";
  14. import { validateJsonSchemaValue } from "../src/tool/json-schema.js";
  15. import type { ToolEntry } from "../src/tool/types.js";
  16. describe("tool input validation provider content", () => {
  17. it("formats missing, unexpected, and wrong-type issues in the required order", () => {
  18. const validation = validateJsonSchemaValue(
  19. {
  20. extraOne: true,
  21. extraTwo: false,
  22. items: [{ count: "bad", nestedExtra: true }],
  23. },
  24. {
  25. additionalProperties: false,
  26. properties: {
  27. missingValue: { type: "string" },
  28. otherMissing: { type: "boolean" },
  29. items: {
  30. items: {
  31. additionalProperties: false,
  32. properties: {
  33. count: { type: "integer" },
  34. },
  35. required: ["count"],
  36. type: "object",
  37. },
  38. type: "array",
  39. },
  40. },
  41. required: ["missingValue", "otherMissing", "items"],
  42. type: "object",
  43. },
  44. );
  45. expect(validation.valid).toBe(false);
  46. expect(formatToolInputValidationError("ValidationTool", validation.issues)).toBe(
  47. [
  48. "ValidationTool failed due to the following issues:",
  49. "The required parameter `missingValue` is missing",
  50. "The required parameter `otherMissing` is missing",
  51. "An unexpected parameter `nestedExtra` was provided",
  52. "An unexpected parameter `extraOne` was provided",
  53. "An unexpected parameter `extraTwo` was provided",
  54. "The parameter `items[0].count` type is expected as `number` but provided as `string`",
  55. ].join("\n"),
  56. );
  57. });
  58. it("uses empty paths and unknown when the received type cannot be extracted", () => {
  59. expect(
  60. formatToolInputValidationError("RootTool", [
  61. {
  62. expected: "string",
  63. code: "invalid_type",
  64. path: [],
  65. message: "custom type mismatch",
  66. },
  67. ]),
  68. ).toBe(
  69. [
  70. "RootTool failed due to the following issue:",
  71. "The parameter `` type is expected as `string` but provided as `unknown`",
  72. ].join("\n"),
  73. );
  74. });
  75. it("omits unrecognized issue kinds when a recognized issue exists", () => {
  76. expect(
  77. formatToolInputValidationError("MixedTool", [
  78. {
  79. code: "invalid_value",
  80. values: ["fast", "safe"],
  81. path: ["mode"],
  82. message: 'Invalid option: expected one of "fast"|"safe"',
  83. },
  84. {
  85. expected: "string",
  86. code: "invalid_type",
  87. path: ["name"],
  88. message: "Invalid input: expected string, received undefined",
  89. },
  90. ]),
  91. ).toBe(
  92. [
  93. "MixedTool failed due to the following issue:",
  94. "The required parameter `name` is missing",
  95. ].join("\n"),
  96. );
  97. });
  98. it("serializes every non-parameter issue with source-compatible messages and layout", () => {
  99. const validation = validateJsonSchemaValue(
  100. {
  101. choice: true,
  102. count: 0,
  103. label: "",
  104. list: [],
  105. literal: "wrong",
  106. mode: "other",
  107. },
  108. {
  109. additionalProperties: false,
  110. properties: {
  111. mode: { enum: ["fast", "safe"] },
  112. label: { type: "string", minLength: 3 },
  113. count: { type: "number", minimum: 1 },
  114. list: { type: "array", minItems: 1 },
  115. literal: { const: "fixed" },
  116. choice: {
  117. oneOf: [{ type: "string" }, { type: "number" }],
  118. },
  119. },
  120. required: ["mode", "label", "count", "list", "literal", "choice"],
  121. type: "object",
  122. },
  123. );
  124. expect(validation.valid).toBe(false);
  125. expect(formatToolInputValidationError("ConstraintTool", validation.issues)).toBe(`[
  126. {
  127. "code": "invalid_value",
  128. "values": [
  129. "fast",
  130. "safe"
  131. ],
  132. "path": [
  133. "mode"
  134. ],
  135. "message": "Invalid option: expected one of \\"fast\\"|\\"safe\\""
  136. },
  137. {
  138. "origin": "string",
  139. "code": "too_small",
  140. "minimum": 3,
  141. "inclusive": true,
  142. "path": [
  143. "label"
  144. ],
  145. "message": "Too small: expected string to have >=3 characters"
  146. },
  147. {
  148. "origin": "number",
  149. "code": "too_small",
  150. "minimum": 1,
  151. "inclusive": true,
  152. "path": [
  153. "count"
  154. ],
  155. "message": "Too small: expected number to be >=1"
  156. },
  157. {
  158. "origin": "array",
  159. "code": "too_small",
  160. "minimum": 1,
  161. "inclusive": true,
  162. "path": [
  163. "list"
  164. ],
  165. "message": "Too small: expected array to have >=1 items"
  166. },
  167. {
  168. "code": "invalid_value",
  169. "values": [
  170. "fixed"
  171. ],
  172. "path": [
  173. "literal"
  174. ],
  175. "message": "Invalid input: expected \\"fixed\\""
  176. },
  177. {
  178. "code": "invalid_union",
  179. "errors": [
  180. [
  181. {
  182. "expected": "string",
  183. "code": "invalid_type",
  184. "path": [],
  185. "message": "Invalid input: expected string, received boolean"
  186. }
  187. ],
  188. [
  189. {
  190. "expected": "number",
  191. "code": "invalid_type",
  192. "path": [],
  193. "message": "Invalid input: expected number, received boolean"
  194. }
  195. ]
  196. ],
  197. "path": [
  198. "choice"
  199. ],
  200. "message": "Invalid input"
  201. }
  202. ]`);
  203. });
  204. it("keeps normalized enum type mismatches on the invalid-value JSON fallback", () => {
  205. const validation = validateJsonSchemaValue(
  206. {
  207. mode: 7,
  208. },
  209. {
  210. additionalProperties: false,
  211. properties: {
  212. mode: { type: "string", enum: ["fast", "safe"] },
  213. },
  214. required: ["mode"],
  215. type: "object",
  216. },
  217. );
  218. expect(formatToolInputValidationError("EnumTool", validation.issues)).toBe(`[
  219. {
  220. "code": "invalid_value",
  221. "values": [
  222. "fast",
  223. "safe"
  224. ],
  225. "path": [
  226. "mode"
  227. ],
  228. "message": "Invalid option: expected one of \\"fast\\"|\\"safe\\""
  229. }
  230. ]`);
  231. });
  232. it("preserves schema property order across present constraints and missing enums", () => {
  233. const validation = validateJsonSchemaValue(
  234. {
  235. todos: [
  236. {
  237. content: "",
  238. priority: "high",
  239. },
  240. ],
  241. },
  242. {
  243. additionalProperties: false,
  244. properties: {
  245. todos: {
  246. items: {
  247. additionalProperties: false,
  248. properties: {
  249. content: { type: "string", minLength: 1 },
  250. status: {
  251. type: "string",
  252. enum: ["pending", "in_progress", "completed"],
  253. },
  254. priority: {
  255. type: "string",
  256. enum: ["high", "medium", "low"],
  257. },
  258. },
  259. required: ["content", "status", "priority"],
  260. type: "object",
  261. },
  262. type: "array",
  263. },
  264. },
  265. required: ["todos"],
  266. type: "object",
  267. },
  268. );
  269. expect(formatToolInputValidationError("TodoWrite", validation.issues)).toBe(`[
  270. {
  271. "origin": "string",
  272. "code": "too_small",
  273. "minimum": 1,
  274. "inclusive": true,
  275. "path": [
  276. "todos",
  277. 0,
  278. "content"
  279. ],
  280. "message": "Too small: expected string to have >=1 characters"
  281. },
  282. {
  283. "code": "invalid_value",
  284. "values": [
  285. "pending",
  286. "in_progress",
  287. "completed"
  288. ],
  289. "path": [
  290. "todos",
  291. 0,
  292. "status"
  293. ],
  294. "message": "Invalid option: expected one of \\"pending\\"|\\"in_progress\\"|\\"completed\\""
  295. }
  296. ]`);
  297. });
  298. it("serializes bigint issue values as strings", () => {
  299. expect(
  300. formatToolInputValidationError("BigIntConstraintTool", [
  301. {
  302. code: "invalid_value",
  303. values: [1n],
  304. path: ["value"],
  305. message: "Invalid input: expected 1n",
  306. },
  307. ]),
  308. ).toBe(`[
  309. {
  310. "code": "invalid_value",
  311. "values": [
  312. "1"
  313. ],
  314. "path": [
  315. "value"
  316. ],
  317. "message": "Invalid input: expected 1n"
  318. }
  319. ]`);
  320. });
  321. it("attaches exact model content only to initial model input validation", () => {
  322. const entry = createValidationEntry("ValidationTool");
  323. const toolCall = {
  324. id: "call_initial_validation",
  325. input: {},
  326. name: "ValidationTool",
  327. };
  328. const initialError = validateInitialModelToolInput({}, entry);
  329. const initialResult = createErrorResult(toolCall, initialError!);
  330. expect(initialResult.error?.message).toBe("Tool input failed inputSchema validation");
  331. expect(initialResult.modelContent).toBe(
  332. [
  333. "<tool_use_error>InputValidationError: ValidationTool failed due to the following issue:",
  334. "The required parameter `value` is missing</tool_use_error>",
  335. ].join("\n"),
  336. );
  337. const laterError = validateInput({}, entry);
  338. expect(createErrorResult(toolCall, laterError!).modelContent).toBeUndefined();
  339. });
  340. it("keeps every provider issue when internal diagnostics exceed their limit", () => {
  341. const required = Array.from({ length: 25 }, (_, index) => `value${index.toString()}`);
  342. const entry = {
  343. inputSchema: {
  344. additionalProperties: false,
  345. properties: Object.fromEntries(required.map((name) => [name, { type: "string" }])),
  346. required,
  347. type: "object",
  348. },
  349. metadata: {
  350. name: "CompleteValidationTool",
  351. },
  352. } as ToolEntry;
  353. const error = validateInitialModelToolInput({}, entry);
  354. const result = createErrorResult(
  355. {
  356. id: "call_complete_validation",
  357. input: {},
  358. name: "CompleteValidationTool",
  359. },
  360. error!,
  361. );
  362. expect(result.modelContent?.match(/The required parameter/g)).toHaveLength(25);
  363. expect(result.modelContent).toContain("The required parameter `value24` is missing");
  364. });
  365. it("lets initial validation content take precedence over the Edit execution wrapper", () => {
  366. const entry = createValidationEntry("Edit");
  367. const error = validateInitialModelToolInput({}, entry);
  368. const result = createErrorResult(
  369. {
  370. id: "call_edit_validation",
  371. input: {},
  372. name: "Edit",
  373. },
  374. error!,
  375. );
  376. expect(result.modelContent).toBe(
  377. [
  378. "<tool_use_error>InputValidationError: Edit failed due to the following issue:",
  379. "The required parameter `value` is missing</tool_use_error>",
  380. ].join("\n"),
  381. );
  382. });
  383. });
  384. describe("production runtime schema validation issues", () => {
  385. it("does not report a defaulted field when another AskUserQuestion constraint fails", () => {
  386. const content = initialValidationModelContent(askUserQuestionToolEntry, {
  387. questions: [
  388. {
  389. header: "Choice",
  390. options: [],
  391. question: "Which option?",
  392. },
  393. ],
  394. });
  395. expect(content).toContain('"code": "too_small"');
  396. expect(content).toContain('"path": [\n "questions",\n 0,\n "options"\n ]');
  397. expect(content).not.toContain("multiSelect");
  398. });
  399. it("places nested item constraints before outer array constraints", () => {
  400. const questions = Array.from({ length: 5 }, (_, index) => validQuestion(index));
  401. questions[0] = { ...questions[0], options: [] };
  402. const content = initialValidationModelContent(askUserQuestionToolEntry, { questions });
  403. const nestedIssue = content.indexOf(
  404. '"path": [\n "questions",\n 0,\n "options"\n ]',
  405. );
  406. const outerIssue = content.indexOf('"path": [\n "questions"\n ]');
  407. expect(nestedIssue).toBeGreaterThanOrEqual(0);
  408. expect(outerIssue).toBeGreaterThan(nestedIssue);
  409. });
  410. it("keeps runtime custom issues instead of reconstructing a default-field error", () => {
  411. const question = validQuestion(0);
  412. const content = initialValidationModelContent(askUserQuestionToolEntry, {
  413. questions: [
  414. { ...question, multiSelect: undefined },
  415. { ...question, multiSelect: undefined },
  416. ],
  417. });
  418. expect(content).toBe(`<tool_use_error>InputValidationError: [
  419. {
  420. "code": "custom",
  421. "path": [
  422. "questions"
  423. ],
  424. "message": "Question texts must be unique"
  425. }
  426. ]</tool_use_error>`);
  427. });
  428. it("does not report fields accepted by runtime preprocessing when a sibling fails", () => {
  429. expect(
  430. initialValidationModelContent(bashToolEntry, {
  431. command: 1,
  432. run_in_background: "true",
  433. timeout: "10",
  434. }),
  435. ).toBe(
  436. [
  437. "<tool_use_error>InputValidationError: Bash failed due to the following issue:",
  438. "The parameter `command` type is expected as `string` but provided as `number`</tool_use_error>",
  439. ].join("\n"),
  440. );
  441. });
  442. it.each([
  443. {
  444. entry: jsToolEntry,
  445. input: { code: 1 },
  446. expected: [
  447. "The required parameter `title` is missing",
  448. "The parameter `code` type is expected as `string` but provided as `number`",
  449. ],
  450. },
  451. {
  452. entry: skillToolEntry,
  453. input: { args: 1, name: "existing-skill" },
  454. expected: [
  455. "The required parameter `skill` is missing",
  456. "An unexpected parameter `name` was provided",
  457. "The parameter `args` type is expected as `string` but provided as `number`",
  458. ],
  459. },
  460. {
  461. entry: readToolEntry,
  462. input: { file_path: 1, pages: "1" },
  463. expected: [
  464. "An unexpected parameter `pages` was provided",
  465. "The parameter `file_path` type is expected as `string` but provided as `number`",
  466. ],
  467. },
  468. ])(
  469. "keeps provider-only structural issues for $entry.metadata.name",
  470. ({ entry, input, expected }) => {
  471. const content = initialValidationModelContent(entry, input);
  472. for (const line of expected) {
  473. expect(content).toContain(line);
  474. }
  475. },
  476. );
  477. it("keeps a single invalid-value issue for production enum schemas", () => {
  478. const content = initialValidationModelContent(todoWriteToolEntry, {
  479. todos: [
  480. {
  481. content: "Check result",
  482. priority: "urgent",
  483. status: "pending",
  484. },
  485. ],
  486. });
  487. expect(content.match(/"code": "invalid_value"/gu)).toHaveLength(1);
  488. expect(content).not.toContain('"code": "invalid_type"');
  489. });
  490. it("keeps a field refinement before a later enum issue", () => {
  491. expect(
  492. initialValidationModelContent(exitPlanModeToolEntry, {
  493. allowedPrompts: [{ prompt: "", tool: "bad" }],
  494. plan: " ",
  495. }),
  496. ).toBe(`<tool_use_error>InputValidationError: [
  497. {
  498. "code": "custom",
  499. "path": [
  500. "plan"
  501. ],
  502. "message": "String must contain at least 1 character(s)"
  503. },
  504. {
  505. "code": "invalid_value",
  506. "values": [
  507. "Bash"
  508. ],
  509. "path": [
  510. "allowedPrompts",
  511. 0,
  512. "tool"
  513. ],
  514. "message": "Invalid input: expected \\"Bash\\""
  515. }
  516. ]</tool_use_error>`);
  517. });
  518. });
  519. function createValidationEntry(name: string): ToolEntry {
  520. return {
  521. inputSchema: {
  522. additionalProperties: false,
  523. properties: {
  524. value: { type: "string" },
  525. },
  526. required: ["value"],
  527. type: "object",
  528. },
  529. metadata: {
  530. name,
  531. },
  532. } as ToolEntry;
  533. }
  534. function initialValidationModelContent(entry: ToolEntry, input: unknown): string {
  535. const prepared = prepareInitialToolExecutionInput({ entry, input });
  536. const error = validateInitialModelToolInput(
  537. prepared.input,
  538. entry,
  539. prepared.runtimeValidationIssues,
  540. );
  541. const result = createErrorResult(
  542. {
  543. id: `call_${entry.metadata.name}`,
  544. input,
  545. name: entry.metadata.name,
  546. },
  547. error!,
  548. );
  549. expect(typeof result.modelContent).toBe("string");
  550. return result.modelContent as string;
  551. }
  552. function validQuestion(index: number): {
  553. header: string;
  554. multiSelect: boolean;
  555. options: Array<{ description: string; label: string }>;
  556. question: string;
  557. } {
  558. return {
  559. header: `Q${index.toString()}`,
  560. multiSelect: false,
  561. options: [
  562. { description: "First choice", label: "First" },
  563. { description: "Second choice", label: "Second" },
  564. ],
  565. question: `Question ${index.toString()}?`,
  566. };
  567. }