tool-input-normalization.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. import { describe, expect, it, vi } from "vitest";
  2. import { ModelErrorCode } from "@zcode/contracts";
  3. import type { AiSdkModelRuntime } from "../src/model/runner.js";
  4. import {
  5. TestAiSdkModelAdapter as AiSdkModelAdapter,
  6. TestProviderConfigFixture,
  7. } from "./test-provider-config.js";
  8. import { normalizeModelToolInput } from "../src/model/tool-input-normalization.js";
  9. import { executeAdapterGenerateText, executeAdapterStreamText } from "./test-adapter-model.js";
  10. describe("model tool input normalization", () => {
  11. const feedbackMalformedCases = [
  12. {
  13. input:
  14. '{"file_path":"F:\\\\clash-verge-fix.bat","content":"@echo off\\nsetlocal EnableExtensions',
  15. ticket: "ZCT-2072501999367512064",
  16. toolName: "Write",
  17. },
  18. {
  19. input: '{"content":"# PenglaiAgent v0.3.5 深度审计报告\\n**High**: H1',
  20. ticket: "ZCT-2072869553480470528",
  21. toolName: "Write",
  22. },
  23. {
  24. input: '{"content":"# 第二章、第三章 投标文件组织提纲\\n| 4 | 桥梁数量 |',
  25. ticket: "ZCT-2072928903530250240",
  26. toolName: "Write",
  27. },
  28. {
  29. input: '{"content":"<!DOCTYPE html>\\n<html lang=\\"zh-CN\\">\\n<th',
  30. ticket: "ZCT-2072970699099508736",
  31. toolName: "Write",
  32. },
  33. {
  34. input:
  35. '{"questions":[{"options":[{"description":"相当于把 2.5D 当作"3D 视角"的初始预设。"}]}]}',
  36. ticket: "ZCT-2072321679810314240",
  37. toolName: "AskUserQuestion",
  38. },
  39. {
  40. input: '{"questions":[{"description":"bad\\u"}]}',
  41. ticket: "ZCT-2072582003671117824",
  42. toolName: "AskUserQuestion",
  43. },
  44. ];
  45. it("safe-parses stringified tool inputs returned from generateText", async () => {
  46. const runtime: AiSdkModelRuntime = {
  47. async generateText() {
  48. return {
  49. finishReason: "tool-calls",
  50. text: "",
  51. toolCalls: [
  52. {
  53. toolCallId: "call_bash",
  54. toolName: "Bash",
  55. input: '{"command":"python3 -c \\"print(1)\\""}',
  56. },
  57. ],
  58. totalUsage: usage(2, 1),
  59. usage: usage(2, 1),
  60. } as never;
  61. },
  62. streamText() {
  63. throw new Error("not used");
  64. },
  65. };
  66. const adapter = new AiSdkModelAdapter({
  67. registry: registry(),
  68. runtime,
  69. });
  70. const result = await executeAdapterGenerateText(adapter, {
  71. providerId: "test" as never,
  72. modelId: "model-a" as never,
  73. messages: [{ role: "user", content: "Run a command" }],
  74. });
  75. expect(result.toolCalls).toEqual([
  76. {
  77. id: "call_bash",
  78. name: "Bash",
  79. input: {
  80. command: 'python3 -c "print(1)"',
  81. },
  82. },
  83. ]);
  84. });
  85. it("accepts a byte-order mark before otherwise valid tool input JSON", async () => {
  86. const result = await generateTextWithToolInput({
  87. input: '\uFEFF{"command":"pwd"}',
  88. toolCallId: "call_bom",
  89. toolName: "Bash",
  90. });
  91. expect(result.toolCalls).toEqual([
  92. {
  93. id: "call_bom",
  94. input: { command: "pwd" },
  95. name: "Bash",
  96. },
  97. ]);
  98. });
  99. it("degrades JSON null to an empty object through the malformed input path", () => {
  100. const warn = vi.fn();
  101. expect(
  102. normalizeModelToolInput("null", {
  103. logger: testLogger(warn),
  104. source: "streamText",
  105. toolName: "Read",
  106. }),
  107. ).toEqual({});
  108. expect(warn).toHaveBeenCalledOnce();
  109. expect(warn).toHaveBeenCalledWith(
  110. "Model tool input JSON normalization failed",
  111. expect.objectContaining({
  112. inputLength: 4,
  113. parseErrorType: "TypeError",
  114. recovery: "empty_object",
  115. source: "streamText",
  116. status: "failed",
  117. toolName: "Read",
  118. }),
  119. );
  120. });
  121. it("degrades upstream-normalized null without inventing a raw input length", () => {
  122. const warn = vi.fn();
  123. expect(
  124. normalizeModelToolInput(null, {
  125. logger: testLogger(warn),
  126. source: "streamText",
  127. toolName: "Read",
  128. }),
  129. ).toEqual({});
  130. expect(warn).toHaveBeenCalledOnce();
  131. const [, context] = warn.mock.calls[0] ?? [];
  132. expect(context).toEqual(
  133. expect.objectContaining({
  134. inputType: "null",
  135. parseErrorType: "TypeError",
  136. recovery: "empty_object",
  137. source: "streamText",
  138. status: "failed",
  139. toolName: "Read",
  140. }),
  141. );
  142. expect(context).not.toHaveProperty("inputLength");
  143. });
  144. it.each([
  145. { input: undefined, name: "missing input" },
  146. { input: "", name: "empty string" },
  147. ])("degrades $name to an empty object without a parse warning", ({ input }) => {
  148. const warn = vi.fn();
  149. expect(
  150. normalizeModelToolInput(input, {
  151. logger: testLogger(warn),
  152. source: "streamText",
  153. toolName: "Read",
  154. }),
  155. ).toEqual({});
  156. expect(warn).not.toHaveBeenCalled();
  157. });
  158. it("keeps legacy generateText args fallback when input is missing", async () => {
  159. const runtime: AiSdkModelRuntime = {
  160. async generateText() {
  161. return {
  162. finishReason: "tool-calls",
  163. text: "",
  164. toolCalls: [
  165. {
  166. args: { file_path: "README.md" },
  167. toolCallId: "call_legacy_args",
  168. toolName: "Read",
  169. },
  170. ],
  171. totalUsage: usage(2, 1),
  172. usage: usage(2, 1),
  173. } as never;
  174. },
  175. streamText() {
  176. throw new Error("not used");
  177. },
  178. };
  179. const adapter = new AiSdkModelAdapter({ registry: registry(), runtime });
  180. const result = await executeAdapterGenerateText(adapter, {
  181. providerId: "test" as never,
  182. modelId: "model-a" as never,
  183. messages: [{ role: "user", content: "Read a file" }],
  184. });
  185. expect(result.toolCalls).toEqual([
  186. {
  187. id: "call_legacy_args",
  188. input: { file_path: "README.md" },
  189. name: "Read",
  190. },
  191. ]);
  192. });
  193. it("degrades partial generateText JSON to an empty object without repairing it", async () => {
  194. const runtime: AiSdkModelRuntime = {
  195. async generateText() {
  196. return {
  197. finishReason: "tool-calls",
  198. text: "",
  199. toolCalls: [
  200. {
  201. toolCallId: "call_bad",
  202. toolName: "Bash",
  203. input: '{"command":',
  204. },
  205. ],
  206. totalUsage: usage(2, 1),
  207. usage: usage(2, 1),
  208. } as never;
  209. },
  210. streamText() {
  211. throw new Error("not used");
  212. },
  213. };
  214. const adapter = new AiSdkModelAdapter({
  215. registry: registry(),
  216. runtime,
  217. });
  218. const result = await executeAdapterGenerateText(adapter, {
  219. providerId: "test" as never,
  220. modelId: "model-a" as never,
  221. messages: [{ role: "user", content: "Run a command" }],
  222. });
  223. expect(result.toolCalls).toEqual([
  224. {
  225. id: "call_bad",
  226. name: "Bash",
  227. input: {},
  228. },
  229. ]);
  230. });
  231. it("recovers an unparseable generateText tool call without retaining the raw input", async () => {
  232. const malformedInput = '{"command":"bad\\u"}';
  233. const warn = vi.fn();
  234. const runtime: AiSdkModelRuntime = {
  235. async generateText() {
  236. return {
  237. finishReason: "tool-calls",
  238. text: "",
  239. toolCalls: [
  240. {
  241. toolCallId: "call_bad_escape",
  242. toolName: "Bash",
  243. input: malformedInput,
  244. },
  245. ],
  246. totalUsage: usage(2, 1),
  247. usage: usage(2, 1),
  248. } as never;
  249. },
  250. streamText() {
  251. throw new Error("not used");
  252. },
  253. };
  254. const adapter = new AiSdkModelAdapter({
  255. logger: testLogger(warn),
  256. registry: registry(),
  257. runtime,
  258. });
  259. const result = await executeAdapterGenerateText(adapter, {
  260. providerId: "test" as never,
  261. modelId: "model-a" as never,
  262. messages: [{ role: "user", content: "Run a command" }],
  263. });
  264. expect(result.toolCalls).toEqual([
  265. {
  266. id: "call_bad_escape",
  267. input: {},
  268. name: "Bash",
  269. },
  270. ]);
  271. const normalizationWarnings = warn.mock.calls.filter(
  272. ([message]) => message === "Model tool input JSON normalization failed",
  273. );
  274. expect(normalizationWarnings).toHaveLength(1);
  275. expect(normalizationWarnings[0]).toEqual([
  276. "Model tool input JSON normalization failed",
  277. expect.objectContaining({
  278. inputLength: malformedInput.length,
  279. parseErrorType: "SyntaxError",
  280. recovery: "empty_object",
  281. source: "generateText",
  282. status: "failed",
  283. toolName: "Bash",
  284. }),
  285. ]);
  286. expect(JSON.stringify(result.toolCalls)).not.toContain(malformedInput);
  287. expect(JSON.stringify(warn.mock.calls)).not.toContain(malformedInput);
  288. });
  289. it.each(feedbackMalformedCases)(
  290. "strictly degrades malformed tool input observed in feedback $ticket",
  291. async ({ input, ticket, toolName }) => {
  292. const result = await generateTextWithToolInput({
  293. input,
  294. toolName,
  295. toolCallId: `call_${ticket}`,
  296. });
  297. expect(result.toolCalls).toEqual([
  298. {
  299. id: `call_${ticket}`,
  300. name: toolName,
  301. input: {},
  302. },
  303. ]);
  304. expect(JSON.stringify(result.toolCalls)).not.toContain(input);
  305. },
  306. );
  307. it("safe-parses stringified tool inputs in streamed tool_call events", async () => {
  308. const runtime: AiSdkModelRuntime = {
  309. async generateText() {
  310. throw new Error("not used");
  311. },
  312. streamText() {
  313. return {
  314. fullStream: stream([
  315. { type: "start" },
  316. {
  317. type: "tool-call",
  318. toolCallId: "call_read",
  319. toolName: "Read",
  320. input: '{"file_path":"README.md"}',
  321. },
  322. {
  323. type: "finish",
  324. finishReason: "tool-calls",
  325. rawFinishReason: undefined,
  326. totalUsage: usage(2, 1),
  327. },
  328. ]),
  329. } as never;
  330. },
  331. };
  332. const adapter = new AiSdkModelAdapter({
  333. registry: registry(),
  334. runtime,
  335. });
  336. const events = [];
  337. for await (const event of executeAdapterStreamText(adapter, {
  338. providerId: "test" as never,
  339. modelId: "model-a" as never,
  340. messages: [{ role: "user", content: "Read README" }],
  341. })) {
  342. events.push(event);
  343. }
  344. expect(events).toEqual([
  345. { type: "start" },
  346. {
  347. type: "tool_call",
  348. toolCall: {
  349. id: "call_read",
  350. name: "Read",
  351. input: { file_path: "README.md" },
  352. },
  353. },
  354. {
  355. type: "finish",
  356. finishReason: "tool-calls",
  357. providerMetadata: undefined,
  358. usage: {
  359. inputTokens: 2,
  360. outputTokens: 1,
  361. totalTokens: 3,
  362. cacheReadTokens: undefined,
  363. cacheWriteTokens: undefined,
  364. reasoningTokens: undefined,
  365. },
  366. },
  367. ]);
  368. });
  369. it("recovers a malformed atomic streamed tool_call as an empty object", async () => {
  370. const malformedInput =
  371. '{"questions":[{"options":[{"description":"相当于把 2.5D 当作"3D 视角"的初始预设。"}]}]}';
  372. const warn = vi.fn();
  373. const runtime: AiSdkModelRuntime = {
  374. async generateText() {
  375. throw new Error("not used");
  376. },
  377. streamText() {
  378. return {
  379. fullStream: stream([
  380. { type: "start" },
  381. {
  382. type: "tool-call",
  383. toolCallId: "call_ask_malformed",
  384. toolName: "AskUserQuestion",
  385. input: malformedInput,
  386. },
  387. {
  388. type: "finish",
  389. finishReason: "tool-calls",
  390. rawFinishReason: undefined,
  391. totalUsage: usage(2, 1),
  392. },
  393. ]),
  394. } as never;
  395. },
  396. };
  397. const adapter = new AiSdkModelAdapter({
  398. logger: testLogger(warn),
  399. registry: registry(),
  400. runtime,
  401. });
  402. const events = [];
  403. for await (const event of executeAdapterStreamText(adapter, {
  404. providerId: "test" as never,
  405. modelId: "model-a" as never,
  406. messages: [{ role: "user", content: "Read README" }],
  407. })) {
  408. events.push(event);
  409. }
  410. expect(events).toEqual([
  411. { type: "start" },
  412. {
  413. type: "tool_call",
  414. toolCall: {
  415. id: "call_ask_malformed",
  416. name: "AskUserQuestion",
  417. input: {},
  418. },
  419. },
  420. {
  421. type: "finish",
  422. finishReason: "tool-calls",
  423. providerMetadata: undefined,
  424. usage: {
  425. inputTokens: 2,
  426. outputTokens: 1,
  427. totalTokens: 3,
  428. cacheReadTokens: undefined,
  429. cacheWriteTokens: undefined,
  430. reasoningTokens: undefined,
  431. },
  432. },
  433. ]);
  434. expect(warn).toHaveBeenCalledTimes(1);
  435. expect(warn).toHaveBeenCalledWith(
  436. "Model tool input JSON normalization failed",
  437. expect.objectContaining({
  438. inputLength: malformedInput.length,
  439. source: "streamText",
  440. toolName: "AskUserQuestion",
  441. }),
  442. );
  443. expect(JSON.stringify(events)).not.toContain(malformedInput);
  444. expect(JSON.stringify(warn.mock.calls)).not.toContain(malformedInput);
  445. });
  446. it.each(["", " "])("preserves recoverable generateText tool name %j", async (toolName) => {
  447. const runtime: AiSdkModelRuntime = {
  448. async generateText() {
  449. return {
  450. finishReason: "tool-calls",
  451. text: "",
  452. toolCalls: [
  453. {
  454. toolCallId: "call_empty",
  455. toolName,
  456. input: { offset: 48 },
  457. },
  458. ],
  459. totalUsage: usage(2, 1),
  460. usage: usage(2, 1),
  461. } as never;
  462. },
  463. streamText() {
  464. throw new Error("not used");
  465. },
  466. };
  467. const adapter = new AiSdkModelAdapter({
  468. registry: registry(),
  469. runtime,
  470. });
  471. await expect(
  472. executeAdapterGenerateText(adapter, {
  473. providerId: "test" as never,
  474. modelId: "model-a" as never,
  475. messages: [{ role: "user", content: "Read more" }],
  476. }),
  477. ).resolves.toMatchObject({
  478. toolCalls: [
  479. {
  480. id: "call_empty",
  481. input: { offset: 48 },
  482. name: toolName,
  483. },
  484. ],
  485. });
  486. });
  487. it.each([undefined, null, 42, { invalid: true }])(
  488. "rejects generateText tool name %j",
  489. async (toolName) => {
  490. const runtime: AiSdkModelRuntime = {
  491. async generateText() {
  492. return {
  493. finishReason: "tool-calls",
  494. text: "",
  495. toolCalls: [
  496. {
  497. toolCallId: "call_invalid_name",
  498. toolName,
  499. input: {},
  500. },
  501. ],
  502. totalUsage: usage(2, 1),
  503. usage: usage(2, 1),
  504. } as never;
  505. },
  506. streamText() {
  507. throw new Error("not used");
  508. },
  509. };
  510. const adapter = new AiSdkModelAdapter({ registry: registry(), runtime });
  511. await expect(
  512. executeAdapterGenerateText(adapter, {
  513. providerId: "test" as never,
  514. modelId: "model-a" as never,
  515. messages: [{ role: "user", content: "Read more" }],
  516. }),
  517. ).rejects.toMatchObject({
  518. code: ModelErrorCode.InvalidModelResponse,
  519. message: "Model returned an invalid tool call: tool name is empty.",
  520. });
  521. },
  522. );
  523. it("keeps the existing generated tool-call id fallback", async () => {
  524. const runtime: AiSdkModelRuntime = {
  525. async generateText() {
  526. return {
  527. finishReason: "tool-calls",
  528. text: "",
  529. toolCalls: [
  530. {
  531. toolName: "Read",
  532. input: {},
  533. },
  534. ],
  535. totalUsage: usage(2, 1),
  536. usage: usage(2, 1),
  537. } as never;
  538. },
  539. streamText() {
  540. throw new Error("not used");
  541. },
  542. };
  543. const adapter = new AiSdkModelAdapter({
  544. registry: registry(),
  545. runtime,
  546. });
  547. const result = await executeAdapterGenerateText(adapter, {
  548. providerId: "test" as never,
  549. modelId: "model-a" as never,
  550. messages: [{ role: "user", content: "Read more" }],
  551. });
  552. expect(result.toolCalls?.[0]).toMatchObject({ input: {}, name: "Read" });
  553. expect(result.toolCalls?.[0]?.id).toEqual(expect.any(String));
  554. expect(result.toolCalls?.[0]?.id.length).toBeGreaterThan(0);
  555. });
  556. it.each(["", " "])("preserves streamed tool name %j", async (toolName) => {
  557. const runtime: AiSdkModelRuntime = {
  558. async generateText() {
  559. throw new Error("not used");
  560. },
  561. streamText() {
  562. return {
  563. fullStream: stream([
  564. { type: "start" },
  565. {
  566. type: "tool-call",
  567. toolCallId: "call_empty",
  568. toolName,
  569. input: { offset: 48 },
  570. },
  571. ]),
  572. } as never;
  573. },
  574. };
  575. const adapter = new AiSdkModelAdapter({
  576. registry: registry(),
  577. runtime,
  578. });
  579. const events = [];
  580. for await (const event of executeAdapterStreamText(adapter, {
  581. providerId: "test" as never,
  582. modelId: "model-a" as never,
  583. messages: [{ role: "user", content: "Read more" }],
  584. })) {
  585. events.push(event);
  586. }
  587. expect(events).toContainEqual({
  588. type: "tool_call",
  589. toolCall: {
  590. id: "call_empty",
  591. input: { offset: 48 },
  592. name: toolName,
  593. providerExecuted: undefined,
  594. },
  595. });
  596. });
  597. it.each(["generateText", "streamText"])(
  598. "rejects provider-executed empty names from %s",
  599. async (source) => {
  600. const runtime: AiSdkModelRuntime = {
  601. async generateText() {
  602. return {
  603. finishReason: "tool-calls",
  604. text: "",
  605. toolCalls: [
  606. {
  607. providerExecuted: true,
  608. toolCallId: "call_provider_empty",
  609. toolName: "",
  610. input: {},
  611. },
  612. ],
  613. totalUsage: usage(2, 1),
  614. usage: usage(2, 1),
  615. } as never;
  616. },
  617. streamText() {
  618. return {
  619. fullStream: stream([
  620. { type: "start" },
  621. {
  622. type: "tool-call",
  623. providerExecuted: true,
  624. toolCallId: "call_provider_empty",
  625. toolName: "",
  626. input: {},
  627. },
  628. ]),
  629. } as never;
  630. },
  631. };
  632. const adapter = new AiSdkModelAdapter({ registry: registry(), runtime });
  633. const request = {
  634. providerId: "test" as never,
  635. modelId: "model-a" as never,
  636. messages: [{ role: "user" as const, content: "Search" }],
  637. };
  638. const call =
  639. source === "generateText"
  640. ? executeAdapterGenerateText(adapter, request)
  641. : (async () => {
  642. for await (const _event of executeAdapterStreamText(adapter, request)) {
  643. // drain
  644. }
  645. })();
  646. await expect(call).rejects.toMatchObject({
  647. code: ModelErrorCode.InvalidModelResponse,
  648. message: "Model returned an invalid tool call: tool name is empty.",
  649. });
  650. },
  651. );
  652. });
  653. function registry(): TestProviderConfigFixture {
  654. return new TestProviderConfigFixture({
  655. providers: {
  656. test: {
  657. kind: "custom",
  658. createLanguageModel: (modelId) => ({ modelId }) as never,
  659. },
  660. },
  661. });
  662. }
  663. function usage(inputTokens: number, outputTokens: number) {
  664. return {
  665. inputTokens,
  666. outputTokens,
  667. totalTokens: inputTokens + outputTokens,
  668. inputTokenDetails: {
  669. noCacheTokens: inputTokens,
  670. cacheReadTokens: undefined,
  671. cacheWriteTokens: undefined,
  672. },
  673. outputTokenDetails: {
  674. textTokens: outputTokens,
  675. reasoningTokens: undefined,
  676. },
  677. };
  678. }
  679. async function* stream(chunks: unknown[]) {
  680. for (const chunk of chunks) {
  681. yield chunk;
  682. }
  683. }
  684. async function generateTextWithToolInput(options: {
  685. input: unknown;
  686. toolCallId: string;
  687. toolName: string;
  688. }) {
  689. const runtime: AiSdkModelRuntime = {
  690. async generateText() {
  691. return {
  692. finishReason: "tool-calls",
  693. text: "",
  694. toolCalls: [
  695. {
  696. input: options.input,
  697. toolCallId: options.toolCallId,
  698. toolName: options.toolName,
  699. },
  700. ],
  701. totalUsage: usage(2, 1),
  702. usage: usage(2, 1),
  703. } as never;
  704. },
  705. streamText() {
  706. throw new Error("not used");
  707. },
  708. };
  709. const adapter = new AiSdkModelAdapter({
  710. registry: registry(),
  711. runtime,
  712. });
  713. return executeAdapterGenerateText(adapter, {
  714. providerId: "test" as never,
  715. modelId: "model-a" as never,
  716. messages: [{ role: "user", content: "Run a command" }],
  717. });
  718. }
  719. function testLogger(warn: ReturnType<typeof vi.fn>) {
  720. return {
  721. child: vi.fn(),
  722. debug: vi.fn(),
  723. error: vi.fn(),
  724. info: vi.fn(),
  725. warn,
  726. } as never;
  727. }