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

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