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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. import { describe, expect, it } from "vitest";
  2. import { z } from "zod";
  3. import { createErrorResult } from "../src/tool/executor/errors.js";
  4. import { validateInitialModelToolInput, validateInput } from "../src/tool/executor/validation.js";
  5. import { askUserQuestionToolEntry } from "../src/tool/handlers/ask-user-question.js";
  6. import { bashToolEntry } from "../src/tool/handlers/bash.js";
  7. import { listWorkflowRunsToolEntry } from "../src/tool/handlers/list-workflow-runs.js";
  8. import { jsToolEntry } from "../src/tool/handlers/node-repl.js";
  9. import { exitPlanModeToolEntry } from "../src/tool/handlers/plan-mode.js";
  10. import { readToolEntry } from "../src/tool/handlers/read.js";
  11. import { skillToolEntry } from "../src/tool/handlers/skill.js";
  12. import { todoWriteToolEntry } from "../src/tool/handlers/todo.js";
  13. import { webFetchToolEntry } from "../src/tool/handlers/webfetch.js";
  14. import { workflowToolEntry } from "../src/tool/handlers/workflow.js";
  15. import { formatToolInputValidationError } from "../src/tool/input-validation-model-content.js";
  16. import { prepareInitialToolExecutionInput } from "../src/tool/input-normalization.js";
  17. import { validateJsonSchemaValue } from "../src/tool/json-schema.js";
  18. import type { ToolEntry } from "../src/tool/types.js";
  19. describe("tool input validation provider content", () => {
  20. it("formats missing, unexpected, and wrong-type issues in the required order", () => {
  21. const validation = validateJsonSchemaValue(
  22. {
  23. extraOne: true,
  24. extraTwo: false,
  25. items: [{ count: "bad", nestedExtra: true }],
  26. },
  27. {
  28. additionalProperties: false,
  29. properties: {
  30. missingValue: { type: "string" },
  31. otherMissing: { type: "boolean" },
  32. items: {
  33. items: {
  34. additionalProperties: false,
  35. properties: {
  36. count: { type: "integer" },
  37. },
  38. required: ["count"],
  39. type: "object",
  40. },
  41. type: "array",
  42. },
  43. },
  44. required: ["missingValue", "otherMissing", "items"],
  45. type: "object",
  46. },
  47. );
  48. expect(validation.valid).toBe(false);
  49. expect(formatToolInputValidationError("ValidationTool", validation.issues)).toBe(
  50. [
  51. "ValidationTool failed due to the following issues:",
  52. "The required parameter `missingValue` is missing",
  53. "The required parameter `otherMissing` is missing",
  54. "An unexpected parameter `items[0].nestedExtra` was provided",
  55. "An unexpected parameter `extraOne` was provided",
  56. "An unexpected parameter `extraTwo` was provided",
  57. "The parameter `items[0].count` type is expected as `number` but provided as `string`",
  58. ].join("\n"),
  59. );
  60. });
  61. it("uses empty paths and unknown when the received type cannot be extracted", () => {
  62. expect(
  63. formatToolInputValidationError("RootTool", [
  64. {
  65. expected: "string",
  66. code: "invalid_type",
  67. path: [],
  68. message: "custom type mismatch",
  69. },
  70. ]),
  71. ).toBe(
  72. [
  73. "RootTool failed due to the following issue:",
  74. "The parameter `` type is expected as `string` but provided as `unknown`",
  75. ].join("\n"),
  76. );
  77. });
  78. it("lists the other issue kinds after the recognized ones", () => {
  79. expect(
  80. formatToolInputValidationError("MixedTool", [
  81. {
  82. code: "invalid_value",
  83. values: ["fast", "safe"],
  84. path: ["mode"],
  85. message: 'Invalid option: expected one of "fast"|"safe"',
  86. },
  87. {
  88. expected: "string",
  89. code: "invalid_type",
  90. path: ["name"],
  91. message: "Invalid input: expected string, received undefined",
  92. },
  93. ]),
  94. ).toBe(
  95. [
  96. "MixedTool failed due to the following issues:",
  97. "The required parameter `name` is missing",
  98. 'The parameter `mode` is invalid: Invalid option: expected one of "fast"|"safe"',
  99. ].join("\n"),
  100. );
  101. });
  102. it("words other issues by path, union and empty message, and caps them at 20 lines", () => {
  103. const others = Array.from({ length: 22 }, (_, index) => ({
  104. code: "too_small",
  105. origin: "number",
  106. minimum: 1,
  107. inclusive: true,
  108. path: [`n${index}`],
  109. message: "Too small: expected number to be >=1",
  110. }));
  111. const lines = formatToolInputValidationError("OtherTool", [
  112. { code: "unrecognized_keys", keys: ["extra"], path: ["outer"], message: "Unrecognized key" },
  113. { code: "invalid_union", errors: [], path: ["choice"], message: "Invalid input" },
  114. { code: "custom", path: [], message: "Invalid input: provide one of a or b" },
  115. { code: "custom", path: ["long"], message: "x".repeat(510) },
  116. ...others,
  117. ]).split("\n");
  118. expect(lines.slice(0, 5)).toEqual([
  119. "OtherTool failed due to the following issues:",
  120. "An unexpected parameter `outer.extra` was provided",
  121. "The parameter `choice` matches none of the accepted forms",
  122. "The input is invalid: provide one of a or b",
  123. `The parameter \`long\` is invalid: ${"x".repeat(500)}\u2026 [+10 chars]`,
  124. ]);
  125. // 只列前 20 条 other:上面 3 条 + n0..n16,剩下 n17..n21 共 5 条。
  126. expect(lines.at(-2)).toBe(
  127. "The parameter `n16` is invalid: Too small: expected number to be >=1",
  128. );
  129. expect(lines.at(-1)).toBe("(5 more issues not listed)");
  130. expect(lines).toHaveLength(1 + 1 + 20 + 1);
  131. });
  132. it("serializes every non-parameter issue with source-compatible messages and layout", () => {
  133. const validation = validateJsonSchemaValue(
  134. {
  135. choice: true,
  136. count: 0,
  137. label: "",
  138. list: [],
  139. literal: "wrong",
  140. mode: "other",
  141. },
  142. {
  143. additionalProperties: false,
  144. properties: {
  145. mode: { enum: ["fast", "safe"] },
  146. label: { type: "string", minLength: 3 },
  147. count: { type: "number", minimum: 1 },
  148. list: { type: "array", minItems: 1 },
  149. literal: { const: "fixed" },
  150. choice: {
  151. oneOf: [{ type: "string" }, { type: "number" }],
  152. },
  153. },
  154. required: ["mode", "label", "count", "list", "literal", "choice"],
  155. type: "object",
  156. },
  157. );
  158. expect(validation.valid).toBe(false);
  159. expect(formatToolInputValidationError("ConstraintTool", validation.issues)).toBe(`[
  160. {
  161. "code": "invalid_value",
  162. "values": [
  163. "fast",
  164. "safe"
  165. ],
  166. "path": [
  167. "mode"
  168. ],
  169. "message": "Invalid option: expected one of \\"fast\\"|\\"safe\\""
  170. },
  171. {
  172. "origin": "string",
  173. "code": "too_small",
  174. "minimum": 3,
  175. "inclusive": true,
  176. "path": [
  177. "label"
  178. ],
  179. "message": "Too small: expected string to have >=3 characters"
  180. },
  181. {
  182. "origin": "number",
  183. "code": "too_small",
  184. "minimum": 1,
  185. "inclusive": true,
  186. "path": [
  187. "count"
  188. ],
  189. "message": "Too small: expected number to be >=1"
  190. },
  191. {
  192. "origin": "array",
  193. "code": "too_small",
  194. "minimum": 1,
  195. "inclusive": true,
  196. "path": [
  197. "list"
  198. ],
  199. "message": "Too small: expected array to have >=1 items"
  200. },
  201. {
  202. "code": "invalid_value",
  203. "values": [
  204. "fixed"
  205. ],
  206. "path": [
  207. "literal"
  208. ],
  209. "message": "Invalid input: expected \\"fixed\\""
  210. },
  211. {
  212. "code": "invalid_union",
  213. "errors": [
  214. [
  215. {
  216. "expected": "string",
  217. "code": "invalid_type",
  218. "path": [],
  219. "message": "Invalid input: expected string, received boolean"
  220. }
  221. ],
  222. [
  223. {
  224. "expected": "number",
  225. "code": "invalid_type",
  226. "path": [],
  227. "message": "Invalid input: expected number, received boolean"
  228. }
  229. ]
  230. ],
  231. "path": [
  232. "choice"
  233. ],
  234. "message": "Invalid input"
  235. }
  236. ]`);
  237. });
  238. it("keeps normalized enum type mismatches on the invalid-value JSON fallback", () => {
  239. const validation = validateJsonSchemaValue(
  240. {
  241. mode: 7,
  242. },
  243. {
  244. additionalProperties: false,
  245. properties: {
  246. mode: { type: "string", enum: ["fast", "safe"] },
  247. },
  248. required: ["mode"],
  249. type: "object",
  250. },
  251. );
  252. expect(formatToolInputValidationError("EnumTool", validation.issues)).toBe(`[
  253. {
  254. "code": "invalid_value",
  255. "values": [
  256. "fast",
  257. "safe"
  258. ],
  259. "path": [
  260. "mode"
  261. ],
  262. "message": "Invalid option: expected one of \\"fast\\"|\\"safe\\""
  263. }
  264. ]`);
  265. });
  266. it("preserves schema property order across present constraints and missing enums", () => {
  267. const validation = validateJsonSchemaValue(
  268. {
  269. todos: [
  270. {
  271. content: "",
  272. priority: "high",
  273. },
  274. ],
  275. },
  276. {
  277. additionalProperties: false,
  278. properties: {
  279. todos: {
  280. items: {
  281. additionalProperties: false,
  282. properties: {
  283. content: { type: "string", minLength: 1 },
  284. status: {
  285. type: "string",
  286. enum: ["pending", "in_progress", "completed"],
  287. },
  288. priority: {
  289. type: "string",
  290. enum: ["high", "medium", "low"],
  291. },
  292. },
  293. required: ["content", "status", "priority"],
  294. type: "object",
  295. },
  296. type: "array",
  297. },
  298. },
  299. required: ["todos"],
  300. type: "object",
  301. },
  302. );
  303. expect(formatToolInputValidationError("TodoWrite", validation.issues)).toBe(`[
  304. {
  305. "origin": "string",
  306. "code": "too_small",
  307. "minimum": 1,
  308. "inclusive": true,
  309. "path": [
  310. "todos",
  311. 0,
  312. "content"
  313. ],
  314. "message": "Too small: expected string to have >=1 characters"
  315. },
  316. {
  317. "code": "invalid_value",
  318. "values": [
  319. "pending",
  320. "in_progress",
  321. "completed"
  322. ],
  323. "path": [
  324. "todos",
  325. 0,
  326. "status"
  327. ],
  328. "message": "Invalid option: expected one of \\"pending\\"|\\"in_progress\\"|\\"completed\\""
  329. }
  330. ]`);
  331. });
  332. it("serializes bigint issue values as strings", () => {
  333. expect(
  334. formatToolInputValidationError("BigIntConstraintTool", [
  335. {
  336. code: "invalid_value",
  337. values: [1n],
  338. path: ["value"],
  339. message: "Invalid input: expected 1n",
  340. },
  341. ]),
  342. ).toBe(`[
  343. {
  344. "code": "invalid_value",
  345. "values": [
  346. "1"
  347. ],
  348. "path": [
  349. "value"
  350. ],
  351. "message": "Invalid input: expected 1n"
  352. }
  353. ]`);
  354. });
  355. it("attaches exact model content only to initial model input validation", () => {
  356. const entry = createValidationEntry("ValidationTool");
  357. const toolCall = {
  358. id: "call_initial_validation",
  359. input: {},
  360. name: "ValidationTool",
  361. };
  362. const initialError = validateInitialModelToolInput({}, entry);
  363. const initialResult = createErrorResult(toolCall, initialError!);
  364. expect(initialResult.error?.message).toBe("Tool input failed inputSchema validation");
  365. expect(initialResult.modelContent).toBe(
  366. [
  367. "<tool_use_error>InputValidationError: ValidationTool failed due to the following issue:",
  368. "The required parameter `value` is missing</tool_use_error>",
  369. ].join("\n"),
  370. );
  371. const laterError = validateInput({}, entry);
  372. expect(createErrorResult(toolCall, laterError!).modelContent).toBeUndefined();
  373. });
  374. it("keeps every provider issue when internal diagnostics exceed their limit", () => {
  375. const required = Array.from({ length: 25 }, (_, index) => `value${index.toString()}`);
  376. const entry = {
  377. inputSchema: {
  378. additionalProperties: false,
  379. properties: Object.fromEntries(required.map((name) => [name, { type: "string" }])),
  380. required,
  381. type: "object",
  382. },
  383. metadata: {
  384. name: "CompleteValidationTool",
  385. },
  386. } as ToolEntry;
  387. const error = validateInitialModelToolInput({}, entry);
  388. const result = createErrorResult(
  389. {
  390. id: "call_complete_validation",
  391. input: {},
  392. name: "CompleteValidationTool",
  393. },
  394. error!,
  395. );
  396. expect(result.modelContent?.match(/The required parameter/g)).toHaveLength(25);
  397. expect(result.modelContent).toContain("The required parameter `value24` is missing");
  398. });
  399. it("lets initial validation content take precedence over the Edit execution wrapper", () => {
  400. const entry = createValidationEntry("Edit");
  401. const error = validateInitialModelToolInput({}, entry);
  402. const result = createErrorResult(
  403. {
  404. id: "call_edit_validation",
  405. input: {},
  406. name: "Edit",
  407. },
  408. error!,
  409. );
  410. expect(result.modelContent).toBe(
  411. [
  412. "<tool_use_error>InputValidationError: Edit failed due to the following issue:",
  413. "The required parameter `value` is missing</tool_use_error>",
  414. ].join("\n"),
  415. );
  416. });
  417. });
  418. describe("production runtime schema validation issues", () => {
  419. it("does not report a defaulted field when another AskUserQuestion constraint fails", () => {
  420. const content = initialValidationModelContent(askUserQuestionToolEntry, {
  421. questions: [
  422. {
  423. header: "Choice",
  424. options: [],
  425. question: "Which option?",
  426. },
  427. ],
  428. });
  429. expect(content).toContain('"code": "too_small"');
  430. expect(content).toContain('"path": [\n "questions",\n 0,\n "options"\n ]');
  431. expect(content).not.toContain("multiSelect");
  432. });
  433. it("places nested item constraints before outer array constraints", () => {
  434. const questions = Array.from({ length: 5 }, (_, index) => validQuestion(index));
  435. questions[0] = { ...questions[0], options: [] };
  436. const content = initialValidationModelContent(askUserQuestionToolEntry, { questions });
  437. const nestedIssue = content.indexOf(
  438. '"path": [\n "questions",\n 0,\n "options"\n ]',
  439. );
  440. const outerIssue = content.indexOf('"path": [\n "questions"\n ]');
  441. expect(nestedIssue).toBeGreaterThanOrEqual(0);
  442. expect(outerIssue).toBeGreaterThan(nestedIssue);
  443. });
  444. it("keeps runtime custom issues instead of reconstructing a default-field error", () => {
  445. const question = validQuestion(0);
  446. const content = initialValidationModelContent(askUserQuestionToolEntry, {
  447. questions: [
  448. { ...question, multiSelect: undefined },
  449. { ...question, multiSelect: undefined },
  450. ],
  451. });
  452. expect(content).toBe(`<tool_use_error>InputValidationError: [
  453. {
  454. "code": "custom",
  455. "path": [
  456. "questions"
  457. ],
  458. "message": "Question texts must be unique"
  459. }
  460. ]</tool_use_error>`);
  461. });
  462. it("does not report fields accepted by runtime preprocessing when a sibling fails", () => {
  463. expect(
  464. initialValidationModelContent(bashToolEntry, {
  465. command: 1,
  466. run_in_background: "true",
  467. timeout: "10",
  468. }),
  469. ).toBe(
  470. [
  471. "<tool_use_error>InputValidationError: Bash failed due to the following issue:",
  472. "The parameter `command` type is expected as `string` but provided as `number`</tool_use_error>",
  473. ].join("\n"),
  474. );
  475. });
  476. it.each([
  477. {
  478. entry: jsToolEntry,
  479. input: { code: 1 },
  480. expected: [
  481. "The required parameter `title` is missing",
  482. "The parameter `code` type is expected as `string` but provided as `number`",
  483. ],
  484. },
  485. {
  486. entry: skillToolEntry,
  487. input: { args: 1, name: "existing-skill" },
  488. expected: [
  489. "The required parameter `skill` is missing",
  490. "An unexpected parameter `name` was provided",
  491. "The parameter `args` type is expected as `string` but provided as `number`",
  492. ],
  493. },
  494. {
  495. entry: readToolEntry,
  496. input: { file_path: 1, pages: "1" },
  497. expected: [
  498. "An unexpected parameter `pages` was provided",
  499. "The parameter `file_path` type is expected as `string` but provided as `number`",
  500. ],
  501. },
  502. ])(
  503. "keeps provider-only structural issues for $entry.metadata.name",
  504. ({ entry, input, expected }) => {
  505. const content = initialValidationModelContent(entry, input);
  506. for (const line of expected) {
  507. expect(content).toContain(line);
  508. }
  509. },
  510. );
  511. it("keeps a single invalid-value issue for production enum schemas", () => {
  512. const content = initialValidationModelContent(todoWriteToolEntry, {
  513. todos: [
  514. {
  515. content: "Check result",
  516. priority: "urgent",
  517. status: "pending",
  518. },
  519. ],
  520. });
  521. expect(content.match(/"code": "invalid_value"/gu)).toHaveLength(1);
  522. expect(content).not.toContain('"code": "invalid_type"');
  523. });
  524. it("keeps a field refinement before a later enum issue", () => {
  525. expect(
  526. initialValidationModelContent(exitPlanModeToolEntry, {
  527. allowedPrompts: [{ prompt: "", tool: "bad" }],
  528. plan: " ",
  529. }),
  530. ).toBe(`<tool_use_error>InputValidationError: [
  531. {
  532. "code": "custom",
  533. "path": [
  534. "plan"
  535. ],
  536. "message": "String must contain at least 1 character(s)"
  537. },
  538. {
  539. "code": "invalid_value",
  540. "values": [
  541. "Bash"
  542. ],
  543. "path": [
  544. "allowedPrompts",
  545. 0,
  546. "tool"
  547. ],
  548. "message": "Invalid input: expected \\"Bash\\""
  549. }
  550. ]</tool_use_error>`);
  551. });
  552. });
  553. // 规则见根目录 docs/model-tool-call-validation.md:JSON Schema 通过、runtime schema 失败时也返回
  554. // InputValidationError,runtime-only issue 不丢弃;需要友好文字的检查留给 validateInput。
  555. describe("runtime-only issues after the JSON Schema passes", () => {
  556. it("reports an invalid URL before permission instead of a raw ZodError", () => {
  557. expect(initialValidationModelContent(webFetchToolEntry, { url: "not a url", prompt: "x" }))
  558. .toBe(`<tool_use_error>InputValidationError: [
  559. {
  560. "code": "invalid_format",
  561. "format": "url",
  562. "path": [
  563. "url"
  564. ],
  565. "message": "Invalid URL"
  566. }
  567. ]</tool_use_error>`);
  568. });
  569. it("keeps Zod 4 issues in their own structure instead of an empty list", () => {
  570. const entry = zodFourEntry(
  571. "SessionIdFixture",
  572. z.object({
  573. sessionId: z.string().regex(/^sess_[a-z]+$/, "Session id must look like sess_…"),
  574. }),
  575. { sessionId: { type: "string" } },
  576. );
  577. expect(initialValidationModelContent(entry, { sessionId: "dummy" })).toBe(
  578. `<tool_use_error>InputValidationError: [
  579. {
  580. "origin": "string",
  581. "code": "invalid_format",
  582. "format": "regex",
  583. "pattern": "/^sess_[a-z]+$/",
  584. "path": [
  585. "sessionId"
  586. ],
  587. "message": "Session id must look like sess_…"
  588. }
  589. ]</tool_use_error>`,
  590. );
  591. });
  592. it("keeps a Zod 4 trimmed length issue", () => {
  593. const entry = zodFourEntry("TitleFixture", z.object({ title: z.string().trim().min(1) }), {
  594. title: { type: "string" },
  595. });
  596. expect(initialValidationModelContent(entry, { title: " " })).toBe(
  597. `<tool_use_error>InputValidationError: [
  598. {
  599. "origin": "string",
  600. "code": "too_small",
  601. "minimum": 1,
  602. "inclusive": true,
  603. "path": [
  604. "title"
  605. ],
  606. "message": "Too small: expected string to have >=1 characters"
  607. }
  608. ]</tool_use_error>`,
  609. );
  610. });
  611. it("formats a record value type issue as a parameter line", () => {
  612. const question = validQuestion(0);
  613. expect(
  614. initialValidationModelContent(askUserQuestionToolEntry, {
  615. questions: [question],
  616. answers: { [question.question]: 1 },
  617. }),
  618. ).toBe(
  619. [
  620. "<tool_use_error>InputValidationError: AskUserQuestion failed due to the following issue:",
  621. `The parameter \`answers.${question.question}\` type is expected as \`string\` but provided as \`number\`</tool_use_error>`,
  622. ].join("\n"),
  623. );
  624. });
  625. // 枚举收到错误类型时,runtime 报 invalid_value,原样输出。runtime 接受的值(limit 会被钳到 [1, 50])
  626. // 不报错,即使 JSON Schema 认为它越界。
  627. it("keeps the runtime invalid value for an enum type mismatch", () => {
  628. expect(
  629. initialValidationModelContent(listWorkflowRunsToolEntry, { limit: 0, statuses: [123] }),
  630. ).toBe(`<tool_use_error>InputValidationError: [
  631. {
  632. "code": "invalid_value",
  633. "values": [
  634. "completed",
  635. "errored",
  636. "pending",
  637. "running",
  638. "stopped"
  639. ],
  640. "path": [
  641. "statuses",
  642. 0
  643. ],
  644. "message": "Invalid option: expected one of \\"completed\\"|\\"errored\\"|\\"pending\\"|\\"running\\"|\\"stopped\\""
  645. }
  646. ]</tool_use_error>`);
  647. });
  648. it("keeps a runtime-only Zod 4 issue when the JSON Schema also fails", () => {
  649. const entry = zodFourEntry(
  650. "SessionPageFixture",
  651. z.object({
  652. sessionId: z.string().regex(/^sess_[a-z]+$/, "Session id must look like sess_…"),
  653. limit: z.number().int().min(1).max(200),
  654. }),
  655. { sessionId: { type: "string" }, limit: { type: "integer", minimum: 1, maximum: 200 } },
  656. );
  657. expect(initialValidationModelContent(entry, { sessionId: "dummy", limit: 0 })).toBe(
  658. `<tool_use_error>InputValidationError: [
  659. {
  660. "origin": "string",
  661. "code": "invalid_format",
  662. "format": "regex",
  663. "pattern": "/^sess_[a-z]+$/",
  664. "path": [
  665. "sessionId"
  666. ],
  667. "message": "Session id must look like sess_…"
  668. },
  669. {
  670. "origin": "number",
  671. "code": "too_small",
  672. "minimum": 1,
  673. "inclusive": true,
  674. "path": [
  675. "limit"
  676. ],
  677. "message": "Too small: expected number to be >=1"
  678. }
  679. ]</tool_use_error>`,
  680. );
  681. });
  682. it("keeps the runtime union issue when the JSON Schema also fails the union", () => {
  683. const schema = z.object({ mode: z.union([z.literal("fast"), z.number()]) });
  684. // JSON 的第二个分支故意与 runtime 不同(array 对 number):换成 JSON issues 时输出会不同。
  685. const entry = zodFourEntry("ModeFixture", schema, {
  686. mode: { anyOf: [{ type: "string", const: "fast" }, { type: "array" }] },
  687. });
  688. const runtimeIssues = schema.safeParse({ mode: true }).error!.issues;
  689. expect(initialValidationModelContent(entry, { mode: true })).toBe(
  690. `<tool_use_error>InputValidationError: ${JSON.stringify(runtimeIssues, null, 2)}</tool_use_error>`,
  691. );
  692. });
  693. it("writes custom issues as code, path, message even without an explicit path", () => {
  694. expect(initialValidationModelContent(workflowToolEntry, {})).toBe(
  695. `<tool_use_error>InputValidationError: [
  696. {
  697. "code": "custom",
  698. "path": [],
  699. "message": "Workflow requires scriptPath, script, name, or resumeFromRunId."
  700. }
  701. ]</tool_use_error>`,
  702. );
  703. });
  704. });
  705. function zodFourEntry(
  706. name: string,
  707. runtimeInputSchema: z.ZodType,
  708. properties: Record<string, unknown>,
  709. ): ToolEntry {
  710. return {
  711. inputSchema: {
  712. additionalProperties: false,
  713. properties,
  714. required: Object.keys(properties),
  715. type: "object",
  716. },
  717. metadata: { name },
  718. runtimeInputSchema,
  719. } as ToolEntry;
  720. }
  721. function createValidationEntry(name: string): ToolEntry {
  722. return {
  723. inputSchema: {
  724. additionalProperties: false,
  725. properties: {
  726. value: { type: "string" },
  727. },
  728. required: ["value"],
  729. type: "object",
  730. },
  731. metadata: {
  732. name,
  733. },
  734. } as ToolEntry;
  735. }
  736. function initialValidationModelContent(entry: ToolEntry, input: unknown): string {
  737. const prepared = prepareInitialToolExecutionInput({ entry, input });
  738. const error = validateInitialModelToolInput(
  739. prepared.input,
  740. entry,
  741. prepared.runtimeValidationIssues,
  742. );
  743. const result = createErrorResult(
  744. {
  745. id: `call_${entry.metadata.name}`,
  746. input,
  747. name: entry.metadata.name,
  748. },
  749. error!,
  750. );
  751. expect(typeof result.modelContent).toBe("string");
  752. return result.modelContent as string;
  753. }
  754. function validQuestion(index: number): {
  755. header: string;
  756. multiSelect: boolean;
  757. options: Array<{ description: string; label: string }>;
  758. question: string;
  759. } {
  760. return {
  761. header: `Q${index.toString()}`,
  762. multiSelect: false,
  763. options: [
  764. { description: "First choice", label: "First" },
  765. { description: "Second choice", label: "Second" },
  766. ],
  767. question: `Question ${index.toString()}?`,
  768. };
  769. }