reasoning-history-normalization.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. import { describe, expect, it } from "vitest";
  2. import type { ModelInputMessage, ModelMessageContentBlock } from "@zcode/contracts";
  3. import {
  4. isThinkingSignatureRejection,
  5. normalizeReasoningHistory,
  6. removeRejectedReasoning,
  7. thinkingSignatureRejectionEvidence,
  8. } from "../src/model/reasoning-history-normalization.js";
  9. describe("reasoning history normalization", () => {
  10. it("preserves signed and redacted reasoning for the same model identity", () => {
  11. const messages: ModelInputMessage[] = [
  12. assistantWithReasoning(
  13. [
  14. reasoning("signed", { signature: "sig_1" }),
  15. reasoning("redacted", { redactedData: "redacted_1" }),
  16. { type: "text", text: "answer" },
  17. ],
  18. modelIdentity("provider-a/model-a"),
  19. ),
  20. { role: "user", content: "next" },
  21. ];
  22. expect(normalizeReasoningHistory(messages, modelIdentity("provider-a/model-a"))).toBe(messages);
  23. });
  24. it("removes signed and redacted reasoning across model identities but preserves unsigned blocks", () => {
  25. const messages: ModelInputMessage[] = [
  26. assistantWithReasoning(
  27. [
  28. reasoning("signed", { signature: "sig_1" }),
  29. reasoning("unsigned"),
  30. reasoning("empty signature", { signature: "" }),
  31. reasoning("redacted", { redactedData: "redacted_1" }),
  32. { type: "text", text: "answer" },
  33. ],
  34. modelIdentity("provider-a/shared-model"),
  35. ),
  36. { role: "user", content: "next" },
  37. ];
  38. expect(normalizeReasoningHistory(messages, modelIdentity("provider-b/shared-model"))).toEqual([
  39. {
  40. role: "assistant",
  41. ...modelIdentity("provider-a/shared-model"),
  42. content: [
  43. reasoning("unsigned"),
  44. reasoning("empty signature", { signature: "" }),
  45. { type: "text", text: "answer" },
  46. ],
  47. },
  48. { role: "user", content: "next" },
  49. ]);
  50. });
  51. it("preserves a non-final assistant envelope when cross-model stripping makes it empty", () => {
  52. const messages: ModelInputMessage[] = [
  53. assistantWithReasoning(
  54. [reasoning("signed", { signature: "sig_1" })],
  55. modelIdentity("provider-a/model-a"),
  56. ),
  57. { role: "user", content: "next" },
  58. ];
  59. expect(normalizeReasoningHistory(messages, modelIdentity("provider-b/model-b"))).toEqual([
  60. {
  61. role: "assistant",
  62. ...modelIdentity("provider-a/model-a"),
  63. content: [{ type: "text", text: "(no content)" }],
  64. },
  65. { role: "user", content: "next" },
  66. ]);
  67. });
  68. // 删除回复只在 core 投影的第一步做;adapter 删掉会让 core 放好的 system 直接接 user。
  69. it("fills a whitespace-only assistant exposed by stripping with (no content)", () => {
  70. const messages: ModelInputMessage[] = [
  71. { role: "user", content: "first" },
  72. assistantWithReasoning(
  73. [reasoning("signed", { signature: "sig_1" }), { type: "text", text: " \n" }],
  74. modelIdentity("provider-a/model-a"),
  75. ),
  76. { role: "user", content: "second" },
  77. ];
  78. expect(normalizeReasoningHistory(messages, modelIdentity("provider-b/model-b"))).toEqual([
  79. { role: "user", content: "first" },
  80. {
  81. role: "assistant",
  82. ...modelIdentity("provider-a/model-a"),
  83. content: [{ type: "text", text: "(no content)" }],
  84. },
  85. { role: "user", content: "second" },
  86. ]);
  87. });
  88. it.each([
  89. ["reasoning-only", [reasoning("orphan")]],
  90. ["(no content)", [{ type: "text", text: "(no content)" }]],
  91. ] satisfies [string, ModelMessageContentBlock[]][])(
  92. "keeps a %s reply and its neighbouring users",
  93. (_kind, content) => {
  94. const messages: ModelInputMessage[] = [
  95. { role: "user", content: "first" },
  96. { role: "system", content: "announcement" },
  97. { role: "assistant", content },
  98. { role: "user", content: "second" },
  99. ];
  100. expect(normalizeReasoningHistory(messages)).toBe(messages);
  101. },
  102. );
  103. it("does not infer a model mismatch when assistant provenance is missing", () => {
  104. const messages: ModelInputMessage[] = [
  105. {
  106. role: "assistant",
  107. content: [reasoning("signed", { signature: "sig_1" }), { type: "text", text: "answer" }],
  108. },
  109. { role: "user", content: "next" },
  110. ];
  111. expect(normalizeReasoningHistory(messages, modelIdentity("provider-b/model-b"))).toBe(messages);
  112. });
  113. it("removes only the final assistant's consecutive trailing reasoning", () => {
  114. const messages: ModelInputMessage[] = [
  115. { role: "user", content: "question" },
  116. {
  117. role: "assistant",
  118. content: [
  119. reasoning("kept"),
  120. { type: "text", text: "answer" },
  121. reasoning("trailing one"),
  122. reasoning("trailing two"),
  123. ],
  124. },
  125. ];
  126. expect(normalizeReasoningHistory(messages)).toEqual([
  127. { role: "user", content: "question" },
  128. {
  129. role: "assistant",
  130. content: [reasoning("kept"), { type: "text", text: "answer" }],
  131. },
  132. ]);
  133. });
  134. it("keeps tool calls when trailing reasoning leaves assistant content empty", () => {
  135. const messages: ModelInputMessage[] = [
  136. { role: "user", content: "question" },
  137. {
  138. role: "assistant",
  139. content: [reasoning("trailing")],
  140. toolCalls: [{ id: "call_1", name: "Read", input: { file_path: "README.md" } }],
  141. },
  142. ];
  143. expect(normalizeReasoningHistory(messages)).toEqual([
  144. { role: "user", content: "question" },
  145. {
  146. role: "assistant",
  147. content: [],
  148. toolCalls: [{ id: "call_1", name: "Read", input: { file_path: "README.md" } }],
  149. },
  150. ]);
  151. });
  152. it("does not mutate canonical history and preserves the original reference when unchanged", () => {
  153. const messages: ModelInputMessage[] = [
  154. { role: "assistant", content: [{ type: "text", text: "answer" }] },
  155. { role: "user", content: "next" },
  156. ];
  157. const snapshot = structuredClone(messages);
  158. expect(normalizeReasoningHistory(messages)).toBe(messages);
  159. expect(messages).toEqual(snapshot);
  160. });
  161. it("removes only signed and redacted reasoning after a signature rejection", () => {
  162. const messages: ModelInputMessage[] = [
  163. {
  164. role: "assistant",
  165. content: [
  166. reasoning("signed", { signature: "sig_1" }),
  167. reasoning("unsigned"),
  168. reasoning("redacted", { redactedData: "redacted_1" }),
  169. { type: "text", text: "answer" },
  170. ],
  171. },
  172. { role: "user", content: "next" },
  173. ];
  174. const snapshot = structuredClone(messages);
  175. expect(removeRejectedReasoning(messages)).toEqual([
  176. {
  177. role: "assistant",
  178. content: [reasoning("unsigned"), { type: "text", text: "answer" }],
  179. },
  180. { role: "user", content: "next" },
  181. ]);
  182. expect(messages).toEqual(snapshot);
  183. expect(
  184. removeRejectedReasoning([
  185. { role: "assistant", content: [reasoning("unsigned"), { type: "text", text: "answer" }] },
  186. { role: "user", content: "next" },
  187. ]),
  188. ).toEqual([
  189. { role: "assistant", content: [reasoning("unsigned"), { type: "text", text: "answer" }] },
  190. { role: "user", content: "next" },
  191. ]);
  192. });
  193. it("adds the [Thinking removed] placeholder when only unsigned reasoning remains", () => {
  194. const messages: ModelInputMessage[] = [
  195. {
  196. role: "assistant",
  197. content: [
  198. reasoning("signed", { signature: "sig_1" }),
  199. reasoning("unsigned"),
  200. { type: "text", text: " " },
  201. ],
  202. },
  203. { role: "user", content: "next" },
  204. ];
  205. expect(removeRejectedReasoning(messages)).toEqual([
  206. {
  207. role: "assistant",
  208. content: [reasoning("unsigned"), { type: "text", text: "[Thinking removed]" }],
  209. },
  210. { role: "user", content: "next" },
  211. ]);
  212. });
  213. it("does not add a rejection placeholder when a tool call remains", () => {
  214. const messages: ModelInputMessage[] = [
  215. {
  216. role: "assistant",
  217. content: [reasoning("signed", { signature: "sig_1" }), { type: "text", text: " " }],
  218. toolCalls: [{ id: "call_1", name: "Read", input: { file_path: "README.md" } }],
  219. },
  220. { role: "user", content: "next" },
  221. ];
  222. expect(removeRejectedReasoning(messages)).toEqual([
  223. {
  224. role: "assistant",
  225. content: [],
  226. toolCalls: [{ id: "call_1", name: "Read", input: { file_path: "README.md" } }],
  227. },
  228. { role: "user", content: "next" },
  229. ]);
  230. });
  231. it("keeps reasoning removed by a successful repair out of later requests", () => {
  232. const target = modelIdentity("provider-a/model-a");
  233. const beforeRepair: ModelInputMessage[] = [
  234. { role: "user", content: "first" },
  235. assistantWithReasoning(
  236. [
  237. reasoning("signed", { signature: "sig_1" }),
  238. reasoning("unsigned"),
  239. { type: "text", text: " " },
  240. ],
  241. target,
  242. ),
  243. { role: "user", content: "second" },
  244. {
  245. role: "assistant",
  246. content: [reasoning("redacted", { redactedData: "redacted_1" })],
  247. toolCalls: [{ id: "call_1", name: "Read", input: { file_path: "README.md" } }],
  248. ...target,
  249. },
  250. { role: "user", content: "read", toolCallId: "call_1", toolName: "Read" },
  251. ];
  252. const repairedRetry = removeRejectedReasoning(normalizeReasoningHistory(beforeRepair, target));
  253. const marked: ModelInputMessage = {
  254. ...assistantWithReasoning(
  255. [reasoning("after repair", { signature: "sig_2" }), { type: "text", text: "done" }],
  256. target,
  257. ),
  258. signedReasoningReset: true,
  259. };
  260. const later: ModelInputMessage[] = [
  261. ...beforeRepair,
  262. marked,
  263. { role: "user", content: "third" },
  264. assistantWithReasoning(
  265. [reasoning("later", { signature: "sig_3" }), { type: "text", text: "ok" }],
  266. target,
  267. ),
  268. { role: "user", content: "fourth" },
  269. ];
  270. const snapshot = structuredClone(later);
  271. const projected = normalizeReasoningHistory(later, target);
  272. // 标记之前的前缀必须和修复那次重发的前缀逐字节相同,后续请求才不会再被拒,缓存也能接上。
  273. expect(JSON.stringify(projected.slice(0, beforeRepair.length))).toBe(
  274. JSON.stringify(repairedRetry),
  275. );
  276. expect(projected[1]!.content).toEqual([
  277. reasoning("unsigned"),
  278. { type: "text", text: "[Thinking removed]" },
  279. ]);
  280. expect(projected.slice(beforeRepair.length)).toEqual(later.slice(beforeRepair.length));
  281. expect(later).toEqual(snapshot);
  282. });
  283. it("uses the last repair marker and leaves history without a marker unchanged", () => {
  284. const target = modelIdentity("provider-a/model-a");
  285. const signedAnswer = (text: string, signature: string) =>
  286. assistantWithReasoning(
  287. [reasoning(text, { signature }), { type: "text", text: `${text} answer` }],
  288. target,
  289. );
  290. const unmarked: ModelInputMessage[] = [
  291. { role: "user", content: "first" },
  292. signedAnswer("one", "sig_1"),
  293. { role: "user", content: "second" },
  294. ];
  295. expect(normalizeReasoningHistory(unmarked, target)).toBe(unmarked);
  296. const messages: ModelInputMessage[] = [
  297. ...unmarked,
  298. { ...signedAnswer("two", "sig_2"), signedReasoningReset: true },
  299. { role: "user", content: "third" },
  300. { ...signedAnswer("three", "sig_3"), signedReasoningReset: true },
  301. { role: "user", content: "fourth" },
  302. ];
  303. const projected = normalizeReasoningHistory(messages, target);
  304. expect(projected[1]!.content).toEqual([{ type: "text", text: "one answer" }]);
  305. expect(projected[3]!.content).toEqual([{ type: "text", text: "two answer" }]);
  306. expect(projected[5]).toBe(messages[5]);
  307. });
  308. });
  309. describe("ordered assistant entries", () => {
  310. const signed = (text: string, blockIndex: number) => ({
  311. ...reasoning(text, { signature: `sig_${text}` }),
  312. blockIndex,
  313. });
  314. const text = (value: string, blockIndex: number) => ({
  315. type: "text" as const,
  316. text: value,
  317. blockIndex,
  318. });
  319. const call = (id: string, blockIndex: number) => ({ id, name: "Read", input: {}, blockIndex });
  320. function ordered(
  321. content: ModelMessageContentBlock[],
  322. toolCalls?: ReturnType<typeof call>[],
  323. ): ModelInputMessage {
  324. return { role: "assistant", content, ...(toolCalls ? { toolCalls } : {}) };
  325. }
  326. // 按 transform 的排列展开成请求顺序,便于断言块序列。
  327. function requestOrder(message: ModelInputMessage | undefined): string[] {
  328. const content = Array.isArray(message?.content) ? message.content : [];
  329. return [
  330. ...content.map((block) => ({
  331. blockIndex: "blockIndex" in block ? block.blockIndex! : -1,
  332. label: block.type === "text" || block.type === "reasoning" ? block.text : block.type,
  333. })),
  334. ...(message?.toolCalls ?? []).map((toolCall) => ({
  335. blockIndex: toolCall.blockIndex!,
  336. label: toolCall.id,
  337. })),
  338. ]
  339. .sort((left, right) => left.blockIndex - right.blockIndex)
  340. .map((entry) => entry.label);
  341. }
  342. function normalizeFirst(message: ModelInputMessage): ModelInputMessage | undefined {
  343. return normalizeReasoningHistory([message, { role: "user", content: "next" }])[0];
  344. }
  345. it.each([
  346. [
  347. "text after a tool",
  348. [signed("A", 0), text("P", 1), text("Q", 3)],
  349. [call("t1", 2)],
  350. ["A", "P", "Q", "t1"],
  351. ],
  352. [
  353. "reasoning after text and a tool",
  354. [signed("A", 0), text("P", 1), signed("B", 3)],
  355. [call("t1", 2), call("t2", 4)],
  356. ["A", "P", "B", "t1", "t2"],
  357. ],
  358. ])("moves tool_use to the end for %s", (_name, content, toolCalls, expected) => {
  359. expect(requestOrder(normalizeFirst(ordered(content, toolCalls)))).toEqual(expected);
  360. });
  361. it("keeps the original order for reasoning -> tool_use -> reasoning", () => {
  362. const message = ordered([signed("A", 0), signed("B", 2)], [call("t1", 1), call("t2", 3)]);
  363. const messages = [message, { role: "user" as const, content: "next" }];
  364. expect(normalizeReasoningHistory(messages)).toBe(messages);
  365. });
  366. it("does not change entries whose tools are already last", () => {
  367. const message = ordered([signed("A", 0), text("P", 1)], [call("t1", 2), call("t2", 3)]);
  368. const messages = [message, { role: "user" as const, content: "next" }];
  369. expect(normalizeReasoningHistory(messages)).toBe(messages);
  370. });
  371. it("removes whitespace text unless it sits between two reasoning blocks", () => {
  372. expect(
  373. requestOrder(
  374. normalizeFirst(
  375. ordered([signed("A", 0), text(" ", 1), signed("B", 2), text("\n", 3), text("P", 4)]),
  376. ),
  377. ),
  378. ).toEqual(["A", " ", "B", "P"]);
  379. });
  380. it("keeps whitespace text when filtering would leave only reasoning", () => {
  381. const message = ordered([signed("A", 0), text(" ", 1)]);
  382. const messages = [message, { role: "user" as const, content: "next" }];
  383. expect(normalizeReasoningHistory(messages)).toBe(messages);
  384. });
  385. it("does not merge text blocks", () => {
  386. const result = normalizeFirst(ordered([signed("A", 0), text("P", 1), text("Q", 2)]));
  387. expect(result?.content).toEqual([signed("A", 0), text("P", 1), text("Q", 2)]);
  388. });
  389. // 形态的缩写与 E2E I76 相同:A/B 思考,P/Q/R 文字,W 纯空白文字,1/2 工具。
  390. it.each([
  391. ["A P B Q 1", "A P B Q 1"],
  392. ["A P 1 Q", "A P Q 1"],
  393. ["A 1 B 2", "A 1 B 2"],
  394. ["A P 1 B 2", "A P B 1 2"],
  395. ["P 1 A 2 B", "P A 1 2 B"],
  396. ["A W B P 1", "A W B P 1"],
  397. ["P A W B 1", "P A B 1"],
  398. ["A P W 1", "A P 1"],
  399. ["W A P 1", "A P 1"],
  400. ["A P B Q", "A P B Q"],
  401. ["P A", "P A"],
  402. ["1 A", "A 1"],
  403. ["1 P 2", "P 1 2"],
  404. ["P 1 Q 2 R", "P Q R 1 2"],
  405. ["A 1 B P 2", "A 1 B P 2"],
  406. ["A 1 P B 2", "A P B 1 2"],
  407. ])("folds %s block by block into %s", (shape, expected) => {
  408. const content: ModelMessageContentBlock[] = [];
  409. const toolCalls: ReturnType<typeof call>[] = [];
  410. shape.split(" ").forEach((code, index) => {
  411. if (code === "A" || code === "B") content.push(signed(code, index));
  412. else if (code === "W") content.push(text("\n\n", index));
  413. else if (/\d/.test(code)) toolCalls.push(call(code, index));
  414. else content.push(text(code, index));
  415. });
  416. const message = ordered(content, toolCalls.length > 0 ? toolCalls : undefined);
  417. const order = requestOrder(normalizeFirst(message)).map((label) =>
  418. label === "\n\n" ? "W" : label,
  419. );
  420. expect(order.join(" ")).toBe(expected);
  421. });
  422. it("removes trailing reasoning by request order without re-running the rules", () => {
  423. const messages = normalizeReasoningHistory([
  424. { role: "user", content: "start" },
  425. ordered([text("P", 0), text(" ", 1), signed("A", 2)]),
  426. ]);
  427. expect(requestOrder(messages.at(-1))).toEqual(["P"]);
  428. });
  429. it("removes every trailing reasoning block left by the fold", () => {
  430. // 加入空白时它是最后一块,被删除;之后 A、B 都在末尾,一起删除。
  431. const messages = normalizeReasoningHistory([
  432. { role: "user", content: "start" },
  433. ordered([text("P", 0), signed("A", 1), text("\n\n", 2), signed("B", 3)]),
  434. ]);
  435. expect(requestOrder(messages.at(-1))).toEqual(["P"]);
  436. });
  437. // 有序条目和旧条目用同一条「没有可见内容」规则;删除只在 core 投影里做,
  438. // adapter 收到只有思考和空白的回复时原样保留(规格「没有可见内容的回复」)。
  439. it.each([
  440. ["leading reasoning and whitespace", [signed("A", 0), text("\n\n", 1)]],
  441. ["leading reasoning and the empty placeholder", [signed("A", 0), text("(no content)", 1)]],
  442. ["reasoning after the text", [text("\n\n", 0), signed("A", 1)]],
  443. ["visible text", [signed("A", 0), text("P", 1)]],
  444. ])("keeps an ordered reply with %s", (_name, content) => {
  445. const messages = [
  446. { role: "user" as const, content: "first" },
  447. ordered(content),
  448. { role: "user" as const, content: "second" },
  449. ];
  450. expect(normalizeReasoningHistory(messages)).toBe(messages);
  451. });
  452. it("keeps legacy reasoning and whitespace replies", () => {
  453. const message: ModelInputMessage = {
  454. role: "assistant",
  455. content: [reasoning("A", { signature: "sig_A" }), { type: "text", text: "\n\n" }],
  456. };
  457. const messages = [
  458. { role: "user" as const, content: "first" },
  459. message,
  460. { role: "user" as const, content: "second" },
  461. ];
  462. expect(normalizeReasoningHistory(messages)).toBe(messages);
  463. });
  464. it("keeps reasoning that is followed by a tool_use in request order", () => {
  465. const message = ordered([text("P", 0), signed("A", 1)], [call("t1", 2)]);
  466. const messages: ModelInputMessage[] = [{ role: "user", content: "start" }, message];
  467. expect(requestOrder(normalizeReasoningHistory(messages).at(-1))).toEqual(["P", "A", "t1"]);
  468. });
  469. it("leaves legacy entries on the legacy rules", () => {
  470. const message: ModelInputMessage = {
  471. role: "assistant",
  472. content: [reasoning("A", { signature: "sig_A" }), { type: "text", text: " " }],
  473. toolCalls: [{ id: "t1", name: "Read", input: {} }],
  474. };
  475. const messages = [message, { role: "user" as const, content: "next" }];
  476. expect(normalizeReasoningHistory(messages)).toBe(messages);
  477. });
  478. it("does not mutate canonical history when rewriting block indexes", () => {
  479. const message = ordered([signed("A", 0), text("P", 1), text("Q", 3)], [call("t1", 2)]);
  480. const snapshot = structuredClone(message);
  481. normalizeFirst(message);
  482. expect(message).toEqual(snapshot);
  483. });
  484. it("gives the [Thinking removed] placeholder the next blockIndex", () => {
  485. const [repaired] = removeRejectedReasoning([ordered([signed("A", 4)])]);
  486. expect(repaired?.content).toEqual([text("[Thinking removed]", 5)]);
  487. });
  488. it("re-applies the rules after signature repair", () => {
  489. const [repaired] = removeRejectedReasoning([
  490. ordered([signed("A", 0), text("P", 1), text("Q", 3)], [call("t1", 2)]),
  491. ]);
  492. expect(requestOrder(repaired)).toEqual(["P", "Q", "t1"]);
  493. });
  494. it("keeps the legacy placeholder without a blockIndex", () => {
  495. const [repaired] = removeRejectedReasoning([
  496. { role: "assistant", content: [reasoning("A", { signature: "sig_A" })] },
  497. ]);
  498. expect(repaired?.content).toEqual([{ type: "text", text: "[Thinking removed]" }]);
  499. });
  500. // 签名修复标记之前的有序条目:之后的请求删掉签名思考时,必须和修复那次重发的前缀逐字节相同,
  501. // 否则又会被拒或缓存断开。两处都调用 removeRejectedReasoning,有序条目都重新执行逐块规则。
  502. it("keeps ordered entries before a repair marker equal to the repaired retry", () => {
  503. const beforeRepair: ModelInputMessage[] = [
  504. { role: "user", content: "first" },
  505. ordered([signed("A", 0), text("P", 1), signed("B", 2), text("Q", 3)]),
  506. { role: "user", content: "second" },
  507. ordered([signed("C", 0), text("R", 1), text("S", 3)], [call("t1", 2)]),
  508. { role: "user", content: "read", toolCallId: "t1", toolName: "Read" },
  509. ];
  510. const repairedRetry = removeRejectedReasoning(normalizeReasoningHistory(beforeRepair));
  511. const later: ModelInputMessage[] = [
  512. ...beforeRepair,
  513. { ...ordered([signed("D", 0), text("done", 1)]), signedReasoningReset: true },
  514. { role: "user", content: "third" },
  515. ];
  516. const snapshot = structuredClone(later);
  517. const projected = normalizeReasoningHistory(later);
  518. expect(JSON.stringify(projected.slice(0, beforeRepair.length))).toBe(
  519. JSON.stringify(repairedRetry),
  520. );
  521. expect(requestOrder(projected[1])).toEqual(["P", "Q"]);
  522. expect(requestOrder(projected[3])).toEqual(["R", "S", "t1"]);
  523. expect(projected.slice(beforeRepair.length)).toEqual(later.slice(beforeRepair.length));
  524. expect(later).toEqual(snapshot);
  525. });
  526. });
  527. describe("thinking signature rejection", () => {
  528. it.each([
  529. "signature in thinking block is invalid",
  530. "thinking block cannot be modified",
  531. "`thinking` has an invalid signature",
  532. "redacted_thinking cannot be modified",
  533. // 经网关转发的真实报错:反引号把 "invalid signature" 隔开,原来的子串匹配认不出。
  534. 'InvokeModelWithResponseStream: operation error Bedrock Runtime: InvokeModelWithResponseStream, https response error StatusCode: 400, RequestID: 3cbb4231, ValidationException: messages.1.content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation. Remove the block, or set `thinking.block_binding.prefix_mismatch_behavior` to "drop_block".',
  535. "messages.3.content.0: The thinking block is bound to a different conversation.",
  536. "messages.3.content.0: This thinking block was not created in this conversation.",
  537. ])("accepts the supported HTTP 400 message: %s", (message) => {
  538. expect(isThinkingSignatureRejection(apiError(message, 400))).toBe(true);
  539. });
  540. it.each([
  541. apiError("signature in thinking block is invalid", 500),
  542. apiError("Invalid `signature` in `thinking` block.", 500),
  543. apiError("unrelated invalid request", 400),
  544. apiError("thinking budget is invalid", 400),
  545. apiError("`tool_use` ids must be unique", 400),
  546. ])("rejects unrelated errors", (error) => {
  547. expect(isThinkingSignatureRejection(error)).toBe(false);
  548. });
  549. it("keeps the first 2000 characters of the provider message and the prefix mismatch header", () => {
  550. const message = `Invalid \`signature\` in \`thinking\` block. ${"x".repeat(3000)}`;
  551. expect(
  552. thinkingSignatureRejectionEvidence(apiError(message, 400), {
  553. "Anthropic-Thinking-Prefix-Mismatch": "block=messages.1.content.0",
  554. }),
  555. ).toEqual({
  556. providerMessage: message.slice(0, 2000),
  557. thinkingPrefixMismatch: "block=messages.1.content.0",
  558. });
  559. // 没有该响应头时不写字段。
  560. expect(thinkingSignatureRejectionEvidence(apiError("short", 400), {})).toEqual({
  561. providerMessage: "short",
  562. });
  563. });
  564. });
  565. function assistantWithReasoning(
  566. content: Extract<ModelInputMessage["content"], unknown[]>,
  567. model: Pick<ModelInputMessage, "providerId" | "modelId">,
  568. ): ModelInputMessage {
  569. return { role: "assistant", content, ...model };
  570. }
  571. function modelIdentity(input: string): Pick<ModelInputMessage, "providerId" | "modelId"> {
  572. const separator = input.indexOf("/");
  573. return {
  574. providerId: input.slice(0, separator) as never,
  575. modelId: input.slice(separator + 1) as never,
  576. };
  577. }
  578. function reasoning(
  579. text: string,
  580. anthropic?: Record<string, unknown>,
  581. ): Extract<ModelInputMessage["content"], unknown[]>[number] {
  582. return {
  583. type: "reasoning",
  584. text,
  585. ...(anthropic ? { providerOptions: { anthropic } } : {}),
  586. };
  587. }
  588. function apiError(message: string, statusCode: number): Error & { statusCode: number } {
  589. return Object.assign(new Error(message), { statusCode });
  590. }