tool-input-normalization.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. createRootTraceContext,
  4. createSessionId,
  5. createToolCallId,
  6. createTurnId,
  7. markUnparsedToolInput,
  8. } from "@zcode/contracts";
  9. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  10. import { createManualPermissionBroker } from "../src/permission/broker.js";
  11. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  12. import { createToolExecutor } from "../src/tool/executor.js";
  13. import { createToolRegistry } from "../src/tool/registry.js";
  14. import type { ToolEntry, ToolExecutionContext, ToolHandler } from "../src/tool/types.js";
  15. describe("tool execution input normalization", () => {
  16. it("safe-parses stringified JSON before tool execution when adapter input is still a string", async () => {
  17. const sessionId = createSessionId("tool-input-string");
  18. const turnId = createTurnId("tool-turn");
  19. const traceContext = createRootTraceContext({ sessionId, turnId });
  20. const registry = createToolRegistry();
  21. let capturedInput: unknown;
  22. registry.register(
  23. createToolEntry({
  24. name: "StringInputTool",
  25. runtimeInputSchema: objectRuntimeSchema((value) =>
  26. typeof value.value === "string" ? { value: value.value } : undefined,
  27. ),
  28. handler: async (input) => {
  29. capturedInput = input;
  30. return "ok";
  31. },
  32. inputSchema: {
  33. type: "object",
  34. properties: {
  35. value: { type: "string" },
  36. },
  37. required: ["value"],
  38. additionalProperties: false,
  39. },
  40. }),
  41. );
  42. const executor = createToolExecutor({
  43. emitEvent: async () => {},
  44. permissionService: new PermissionService(defaultPermissionConfig),
  45. registry,
  46. sessionId,
  47. turnId,
  48. traceContext,
  49. });
  50. const result = await executor.execute(
  51. {
  52. id: createToolCallId("string-input"),
  53. input: '{"value":"from-string"}',
  54. name: "StringInputTool",
  55. },
  56. { traceContext },
  57. );
  58. expect(result.success).toBe(true);
  59. expect(capturedInput).toEqual({ value: "from-string" });
  60. });
  61. it("applies runtime schema defaults before hooks and handlers", async () => {
  62. const sessionId = createSessionId("tool-input-defaults");
  63. const turnId = createTurnId("tool-turn");
  64. const traceContext = createRootTraceContext({ sessionId, turnId });
  65. const registry = createToolRegistry();
  66. let hookSawInput: unknown;
  67. let handlerSawInput: unknown;
  68. registry.register(
  69. createToolEntry({
  70. name: "DefaultingTool",
  71. runtimeInputSchema: objectRuntimeSchema((value) => ({
  72. flag: typeof value.flag === "boolean" ? value.flag : false,
  73. })),
  74. handler: async (input) => {
  75. handlerSawInput = input;
  76. return "ok";
  77. },
  78. inputSchema: {
  79. type: "object",
  80. properties: {
  81. flag: { type: "boolean" },
  82. },
  83. additionalProperties: false,
  84. },
  85. }),
  86. );
  87. const hookRunner = createInMemoryHookRunner({
  88. hooks: [
  89. {
  90. event: "PreToolUse",
  91. matcher: "DefaultingTool",
  92. callback: async (input) => {
  93. hookSawInput = input.toolInput;
  94. return undefined;
  95. },
  96. },
  97. ],
  98. });
  99. const executor = createToolExecutor({
  100. emitEvent: async () => {},
  101. hookRunner,
  102. permissionService: new PermissionService(defaultPermissionConfig),
  103. registry,
  104. sessionId,
  105. turnId,
  106. traceContext,
  107. });
  108. const result = await executor.execute(
  109. {
  110. id: createToolCallId("defaulting-input"),
  111. input: {},
  112. name: "DefaultingTool",
  113. },
  114. { traceContext },
  115. );
  116. expect(result.success).toBe(true);
  117. expect(hookSawInput).toEqual({ flag: false });
  118. expect(handlerSawInput).toEqual({ flag: false });
  119. });
  120. it("returns exact initial validation content for an adapter-normalized empty object", async () => {
  121. const sessionId = createSessionId("tool-input-malformed");
  122. const turnId = createTurnId("tool-turn");
  123. const traceContext = createRootTraceContext({ sessionId, turnId });
  124. const registry = createToolRegistry();
  125. let handlerRan = false;
  126. registry.register(
  127. createToolEntry({
  128. name: "AskUserQuestion",
  129. runtimeInputSchema: objectRuntimeSchema((value) =>
  130. Array.isArray(value.questions) ? { questions: value.questions } : undefined,
  131. ),
  132. handler: async () => {
  133. handlerRan = true;
  134. return "ok";
  135. },
  136. inputSchema: {
  137. type: "object",
  138. properties: {
  139. questions: { type: "array" },
  140. },
  141. required: ["questions"],
  142. additionalProperties: false,
  143. },
  144. }),
  145. );
  146. const executor = createToolExecutor({
  147. emitEvent: async () => {},
  148. permissionService: new PermissionService(defaultPermissionConfig),
  149. registry,
  150. sessionId,
  151. turnId,
  152. traceContext,
  153. });
  154. const result = await executor.execute(
  155. {
  156. id: createToolCallId("malformed-input"),
  157. input: {},
  158. name: "AskUserQuestion",
  159. },
  160. { traceContext },
  161. );
  162. expect(result.success).toBe(false);
  163. expect(result).toMatchObject({
  164. toolCallId: createToolCallId("malformed-input"),
  165. toolName: "AskUserQuestion",
  166. });
  167. expect(result.error?.message).toBe("Tool input failed inputSchema validation");
  168. expect(result.modelContent).toBe(
  169. [
  170. "<tool_use_error>InputValidationError: AskUserQuestion failed due to the following issue:",
  171. "The required parameter `questions` is missing</tool_use_error>",
  172. ].join("\n"),
  173. );
  174. expect(handlerRan).toBe(false);
  175. });
  176. it("returns the unparsed-JSON error instead of running a tool that accepts {}", async () => {
  177. const sessionId = createSessionId("tool-input-unparsed");
  178. const turnId = createTurnId("tool-turn");
  179. const traceContext = createRootTraceContext({ sessionId, turnId });
  180. const registry = createToolRegistry();
  181. let handlerRan = false;
  182. registry.register(
  183. createToolEntry({
  184. aliases: ["unparsed_alias"],
  185. name: "OptionalInputTool",
  186. runtimeInputSchema: objectRuntimeSchema(() => ({})),
  187. handler: async () => {
  188. handlerRan = true;
  189. return "ran";
  190. },
  191. inputSchema: { type: "object", properties: { value: { type: "string" } } },
  192. }),
  193. );
  194. const executor = createToolExecutor({
  195. emitEvent: async () => {},
  196. permissionService: new PermissionService(defaultPermissionConfig),
  197. registry,
  198. sessionId,
  199. turnId,
  200. traceContext,
  201. });
  202. const raw = '{"value":"C:\\path"}';
  203. const result = await executor.execute(
  204. {
  205. id: createToolCallId("unparsed-input"),
  206. input: markUnparsedToolInput(raw),
  207. name: "unparsed_alias",
  208. },
  209. { traceContext },
  210. );
  211. expect(handlerRan).toBe(false);
  212. expect(result.success).toBe(false);
  213. expect(result.error?.message).toBe("Tool input could not be parsed as JSON");
  214. expect(result.modelContent).toBe(
  215. [
  216. "<tool_use_error>InputValidationError: OptionalInputTool was called with input that could not be parsed as JSON.",
  217. `You sent (first ${raw.length} of ${raw.length} bytes): ${raw}`,
  218. "Common causes: unescaped backslashes in file paths (use / or \\\\), unescaped control characters, or truncated output. Retry with valid JSON.</tool_use_error>",
  219. ].join("\n"),
  220. );
  221. });
  222. it("uses the canonical tool name in initial validation content", async () => {
  223. const sessionId = createSessionId("tool-input-alias-validation");
  224. const turnId = createTurnId("tool-turn");
  225. const traceContext = createRootTraceContext({ sessionId, turnId });
  226. const registry = createToolRegistry();
  227. registry.register(
  228. createToolEntry({
  229. aliases: ["validation_alias"],
  230. name: "CanonicalValidationTool",
  231. runtimeInputSchema: objectRuntimeSchema((value) =>
  232. typeof value.value === "string" ? { value: value.value } : undefined,
  233. ),
  234. handler: async () => "ok",
  235. inputSchema: {
  236. type: "object",
  237. properties: {
  238. value: { type: "string" },
  239. },
  240. required: ["value"],
  241. additionalProperties: false,
  242. },
  243. }),
  244. );
  245. const executor = createToolExecutor({
  246. emitEvent: async () => {},
  247. permissionService: new PermissionService(defaultPermissionConfig),
  248. registry,
  249. sessionId,
  250. turnId,
  251. traceContext,
  252. });
  253. const result = await executor.execute(
  254. {
  255. id: createToolCallId("alias-validation"),
  256. input: {},
  257. name: "validation_alias",
  258. },
  259. { traceContext },
  260. );
  261. expect(result.success).toBe(false);
  262. expect(result.toolName).toBe("CanonicalValidationTool");
  263. expect(result.modelContent).toContain(
  264. "InputValidationError: CanonicalValidationTool failed due to the following issue:",
  265. );
  266. });
  267. // 规则见根目录 docs/model-tool-call-validation.md:JSON Schema 通过、runtime schema 失败时,
  268. // 在 validateInput、hook 与权限之前返回 InputValidationError。
  269. it("rejects a runtime-only parser issue before validateInput, hooks, and the handler", async () => {
  270. const sessionId = createSessionId("tool-input-runtime-only-issue");
  271. const turnId = createTurnId("tool-turn");
  272. const traceContext = createRootTraceContext({ sessionId, turnId });
  273. const registry = createToolRegistry();
  274. let handlerRan = false;
  275. let validateInputRan = false;
  276. let hookRan = false;
  277. registry.register({
  278. ...createToolEntry({
  279. name: "RuntimeOnlyValidationTool",
  280. runtimeInputSchema: {
  281. safeParse: () => ({
  282. success: false,
  283. error: {
  284. issues: [{ code: "custom", path: ["value"], message: "runtime-only issue" }],
  285. },
  286. }),
  287. },
  288. handler: async () => {
  289. handlerRan = true;
  290. return "ok";
  291. },
  292. inputSchema: {
  293. type: "object",
  294. properties: {
  295. value: { type: "string" },
  296. },
  297. required: ["value"],
  298. additionalProperties: false,
  299. },
  300. }),
  301. validateInput: () => {
  302. validateInputRan = true;
  303. return { result: true };
  304. },
  305. });
  306. const executor = createToolExecutor({
  307. emitEvent: async () => {},
  308. hookRunner: createInMemoryHookRunner({
  309. hooks: [
  310. {
  311. event: "PreToolUse",
  312. matcher: "RuntimeOnlyValidationTool",
  313. callback: async () => {
  314. hookRan = true;
  315. return {};
  316. },
  317. },
  318. ],
  319. }),
  320. permissionService: new PermissionService(defaultPermissionConfig),
  321. registry,
  322. sessionId,
  323. turnId,
  324. traceContext,
  325. });
  326. const result = await executor.execute(
  327. {
  328. id: createToolCallId("runtime-only-issue"),
  329. input: { value: "accepted-by-json-schema" },
  330. name: "RuntimeOnlyValidationTool",
  331. },
  332. { traceContext },
  333. );
  334. expect(result.success).toBe(false);
  335. expect(result.modelContent).toBe(`<tool_use_error>InputValidationError: [
  336. {
  337. "code": "custom",
  338. "path": [
  339. "value"
  340. ],
  341. "message": "runtime-only issue"
  342. }
  343. ]</tool_use_error>`);
  344. expect(validateInputRan).toBe(false);
  345. expect(hookRan).toBe(false);
  346. expect(handlerRan).toBe(false);
  347. });
  348. it("keeps the original flow when the runtime parser reports no readable issues", async () => {
  349. const sessionId = createSessionId("tool-input-runtime-no-issues");
  350. const turnId = createTurnId("tool-turn");
  351. const traceContext = createRootTraceContext({ sessionId, turnId });
  352. const registry = createToolRegistry();
  353. let handlerSawInput: unknown;
  354. registry.register(
  355. createToolEntry({
  356. name: "RuntimeNoIssuesTool",
  357. runtimeInputSchema: objectRuntimeSchema(() => undefined),
  358. handler: async (input) => {
  359. handlerSawInput = input;
  360. return "ok";
  361. },
  362. inputSchema: {
  363. type: "object",
  364. properties: {
  365. value: { type: "string" },
  366. },
  367. required: ["value"],
  368. additionalProperties: false,
  369. },
  370. }),
  371. );
  372. const executor = createToolExecutor({
  373. emitEvent: async () => {},
  374. permissionService: new PermissionService(defaultPermissionConfig),
  375. registry,
  376. sessionId,
  377. turnId,
  378. traceContext,
  379. });
  380. const input = { value: "accepted-by-json-schema" };
  381. const result = await executor.execute(
  382. {
  383. id: createToolCallId("runtime-no-issues"),
  384. input,
  385. name: "RuntimeNoIssuesTool",
  386. },
  387. { traceContext },
  388. );
  389. expect(result.success).toBe(true);
  390. expect(handlerSawInput).toEqual(input);
  391. });
  392. it("re-normalizes hook-updated stringified input before permission and handler execution", async () => {
  393. const sessionId = createSessionId("tool-input-hook-update");
  394. const turnId = createTurnId("tool-turn");
  395. const traceContext = createRootTraceContext({ sessionId, turnId });
  396. const registry = createToolRegistry();
  397. let handlerSawInput: unknown;
  398. registry.register(
  399. createToolEntry({
  400. name: "HookUpdatedInputTool",
  401. runtimeInputSchema: objectRuntimeSchema((value) =>
  402. typeof value.value === "string" ? { value: value.value } : undefined,
  403. ),
  404. handler: async (input) => {
  405. handlerSawInput = input;
  406. return "ok";
  407. },
  408. inputSchema: {
  409. type: "object",
  410. properties: {
  411. value: { type: "string" },
  412. },
  413. required: ["value"],
  414. additionalProperties: false,
  415. },
  416. }),
  417. );
  418. const hookRunner = createInMemoryHookRunner({
  419. hooks: [
  420. {
  421. event: "PreToolUse",
  422. matcher: "HookUpdatedInputTool",
  423. callback: async () => ({
  424. hookSpecificOutput: {
  425. hookEventName: "PreToolUse",
  426. updatedInput: '{"value":"from-hook"}',
  427. },
  428. }),
  429. },
  430. ],
  431. });
  432. const executor = createToolExecutor({
  433. emitEvent: async () => {},
  434. hookRunner,
  435. permissionService: new PermissionService(defaultPermissionConfig),
  436. registry,
  437. sessionId,
  438. turnId,
  439. traceContext,
  440. });
  441. const result = await executor.execute(
  442. {
  443. id: createToolCallId("hook-updated-input"),
  444. input: { value: "initial" },
  445. name: "HookUpdatedInputTool",
  446. },
  447. { traceContext },
  448. );
  449. expect(result.success).toBe(true);
  450. expect(handlerSawInput).toEqual({ value: "from-hook" });
  451. });
  452. it("re-normalizes broker-modified stringified input before handler execution", async () => {
  453. const sessionId = createSessionId("tool-input-broker-update");
  454. const turnId = createTurnId("tool-turn");
  455. const traceContext = createRootTraceContext({ sessionId, turnId });
  456. const registry = createToolRegistry();
  457. const permissionBroker = createManualPermissionBroker({
  458. onRequest: (request) => {
  459. permissionBroker.resolvePermission(request.requestId, {
  460. decision: "modify",
  461. modifiedInput: '{"value":"from-broker"}',
  462. });
  463. },
  464. });
  465. let handlerSawInput: unknown;
  466. registry.register(
  467. createToolEntry({
  468. name: "BrokerUpdatedInputTool",
  469. needsApproval: true,
  470. runtimeInputSchema: objectRuntimeSchema((value) =>
  471. typeof value.value === "string" ? { value: value.value } : undefined,
  472. ),
  473. handler: async (input) => {
  474. handlerSawInput = input;
  475. return "ok";
  476. },
  477. inputSchema: {
  478. type: "object",
  479. properties: {
  480. value: { type: "string" },
  481. },
  482. required: ["value"],
  483. additionalProperties: false,
  484. },
  485. }),
  486. );
  487. const executor = createToolExecutor({
  488. emitEvent: async () => {},
  489. permissionBroker,
  490. permissionService: new PermissionService(defaultPermissionConfig),
  491. registry,
  492. sessionId,
  493. turnId,
  494. traceContext,
  495. });
  496. const result = await executor.execute(
  497. {
  498. id: createToolCallId("broker-updated-input"),
  499. input: { value: "initial" },
  500. name: "BrokerUpdatedInputTool",
  501. },
  502. { traceContext },
  503. );
  504. expect(result.success).toBe(true);
  505. expect(handlerSawInput).toEqual({ value: "from-broker" });
  506. });
  507. it("does not apply initial validation content to broker-modified input", async () => {
  508. const sessionId = createSessionId("tool-input-broker-invalid");
  509. const turnId = createTurnId("tool-turn");
  510. const traceContext = createRootTraceContext({ sessionId, turnId });
  511. const registry = createToolRegistry();
  512. const permissionBroker = createManualPermissionBroker({
  513. onRequest: (request) => {
  514. permissionBroker.resolvePermission(request.requestId, {
  515. decision: "modify",
  516. modifiedInput: {},
  517. });
  518. },
  519. });
  520. registry.register(
  521. createToolEntry({
  522. name: "BrokerInvalidInputTool",
  523. needsApproval: true,
  524. runtimeInputSchema: objectRuntimeSchema((value) =>
  525. typeof value.value === "string" ? { value: value.value } : undefined,
  526. ),
  527. handler: async () => "should-not-run",
  528. inputSchema: {
  529. type: "object",
  530. properties: {
  531. value: { type: "string" },
  532. },
  533. required: ["value"],
  534. additionalProperties: false,
  535. },
  536. }),
  537. );
  538. const executor = createToolExecutor({
  539. emitEvent: async () => {},
  540. permissionBroker,
  541. permissionService: new PermissionService(defaultPermissionConfig),
  542. registry,
  543. sessionId,
  544. turnId,
  545. traceContext,
  546. });
  547. const result = await executor.execute(
  548. {
  549. id: createToolCallId("broker-invalid-input"),
  550. input: { value: "initial" },
  551. name: "BrokerInvalidInputTool",
  552. },
  553. { traceContext },
  554. );
  555. expect(result.success).toBe(false);
  556. expect(result.error?.message).toBe("Tool input failed inputSchema validation");
  557. expect(result.modelContent).toBeUndefined();
  558. });
  559. });
  560. function createToolEntry(options: {
  561. aliases?: readonly string[];
  562. name: string;
  563. handler: ToolHandler;
  564. inputSchema: ToolEntry["inputSchema"];
  565. needsApproval?: boolean;
  566. runtimeInputSchema: unknown;
  567. }): ToolEntry {
  568. const needsApproval = options.needsApproval ?? false;
  569. return {
  570. aliases: options.aliases,
  571. capability: `${options.name} test capability`,
  572. metadata: {
  573. concurrentSafe: true,
  574. destructive: false,
  575. name: options.name,
  576. needsApproval,
  577. readOnly: true,
  578. riskLevel: needsApproval ? "medium" : "low",
  579. sideEffectScope: "none",
  580. timeoutMs: 30000,
  581. },
  582. handler: async (input: unknown, context: ToolExecutionContext) =>
  583. options.handler(input, context),
  584. inputSchema: options.inputSchema,
  585. outputSchema: {
  586. type: "string",
  587. },
  588. permission: {
  589. permission: "test",
  590. reason: "test tool",
  591. riskLevel: needsApproval ? "medium" : "low",
  592. sideEffectScope: "none",
  593. needsApproval,
  594. patternSources: ["none"],
  595. denyPriority: "beforeAsk",
  596. },
  597. resultBudget: {
  598. maxInlineBytes: 100_000,
  599. maxModelBytes: 100_000,
  600. strategy: "truncate",
  601. },
  602. runtimeInputSchema: options.runtimeInputSchema,
  603. timeout: {
  604. defaultMs: 30000,
  605. maxMs: 30000,
  606. allowCallOverride: false,
  607. },
  608. cancellation: {
  609. supported: true,
  610. cleanup: "none",
  611. userVisibleMessage: "Test tool was cancelled",
  612. },
  613. trace: {
  614. required: true,
  615. propagateToAdapters: true,
  616. recordInput: "summary",
  617. recordOutput: "summary",
  618. },
  619. };
  620. }
  621. function objectRuntimeSchema<T extends Record<string, unknown>>(
  622. normalize: (value: Record<string, unknown>) => T | undefined,
  623. ): { safeParse: (value: unknown) => { success: true; data: T } | { success: false } } {
  624. return {
  625. safeParse(value) {
  626. if (!value || typeof value !== "object" || Array.isArray(value)) {
  627. return { success: false };
  628. }
  629. const normalized = normalize(value as Record<string, unknown>);
  630. if (!normalized) {
  631. return { success: false };
  632. }
  633. return {
  634. success: true,
  635. data: normalized,
  636. };
  637. },
  638. };
  639. }