reasoning-history-normalization.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import { describe, expect, it } from "vitest";
  2. import type { ModelInputMessage } from "@zcode/contracts";
  3. import {
  4. isThinkingSignatureRejection,
  5. normalizeReasoningHistory,
  6. removeRejectedReasoning,
  7. } from "../src/model/reasoning-history-normalization.js";
  8. describe("reasoning history normalization", () => {
  9. it("preserves signed and redacted reasoning for the same model identity", () => {
  10. const messages: ModelInputMessage[] = [
  11. assistantWithReasoning(
  12. [
  13. reasoning("signed", { signature: "sig_1" }),
  14. reasoning("redacted", { redactedData: "redacted_1" }),
  15. { type: "text", text: "answer" },
  16. ],
  17. modelIdentity("provider-a/model-a"),
  18. ),
  19. { role: "user", content: "next" },
  20. ];
  21. expect(normalizeReasoningHistory(messages, modelIdentity("provider-a/model-a"))).toBe(messages);
  22. });
  23. it("removes signed and redacted reasoning across model identities but preserves unsigned blocks", () => {
  24. const messages: ModelInputMessage[] = [
  25. assistantWithReasoning(
  26. [
  27. reasoning("signed", { signature: "sig_1" }),
  28. reasoning("unsigned"),
  29. reasoning("empty signature", { signature: "" }),
  30. reasoning("redacted", { redactedData: "redacted_1" }),
  31. { type: "text", text: "answer" },
  32. ],
  33. modelIdentity("provider-a/shared-model"),
  34. ),
  35. { role: "user", content: "next" },
  36. ];
  37. expect(normalizeReasoningHistory(messages, modelIdentity("provider-b/shared-model"))).toEqual([
  38. {
  39. role: "assistant",
  40. ...modelIdentity("provider-a/shared-model"),
  41. content: [
  42. reasoning("unsigned"),
  43. reasoning("empty signature", { signature: "" }),
  44. { type: "text", text: "answer" },
  45. ],
  46. },
  47. { role: "user", content: "next" },
  48. ]);
  49. });
  50. it("preserves a non-final assistant envelope when cross-model stripping makes it empty", () => {
  51. const messages: ModelInputMessage[] = [
  52. assistantWithReasoning(
  53. [reasoning("signed", { signature: "sig_1" })],
  54. modelIdentity("provider-a/model-a"),
  55. ),
  56. { role: "user", content: "next" },
  57. ];
  58. expect(normalizeReasoningHistory(messages, modelIdentity("provider-b/model-b"))).toEqual([
  59. {
  60. role: "assistant",
  61. ...modelIdentity("provider-a/model-a"),
  62. content: [{ type: "text", text: "(no content)" }],
  63. },
  64. { role: "user", content: "next" },
  65. ]);
  66. });
  67. it("removes a whitespace-only assistant exposed by stripping and merges adjacent users", () => {
  68. const messages: ModelInputMessage[] = [
  69. { role: "user", content: "first" },
  70. assistantWithReasoning(
  71. [reasoning("signed", { signature: "sig_1" }), { type: "text", text: " \n" }],
  72. modelIdentity("provider-a/model-a"),
  73. ),
  74. { role: "user", content: "second" },
  75. ];
  76. expect(normalizeReasoningHistory(messages, modelIdentity("provider-b/model-b"))).toEqual([
  77. {
  78. role: "user",
  79. content: [
  80. { type: "text", text: "first\n" },
  81. { type: "text", text: "second" },
  82. ],
  83. },
  84. ]);
  85. });
  86. it("does not merge a tool-result user carrier after removing a whitespace assistant", () => {
  87. const messages: ModelInputMessage[] = [
  88. {
  89. role: "user",
  90. content: "tool result",
  91. toolCallId: "call_1",
  92. toolName: "Read",
  93. },
  94. { role: "assistant", content: [{ type: "text", text: " " }] },
  95. { role: "user", content: "next" },
  96. ];
  97. expect(normalizeReasoningHistory(messages)).toEqual([
  98. {
  99. role: "user",
  100. content: "tool result",
  101. toolCallId: "call_1",
  102. toolName: "Read",
  103. },
  104. { role: "user", content: "next" },
  105. ]);
  106. });
  107. it("does not merge into a later tool-result user carrier", () => {
  108. const messages: ModelInputMessage[] = [
  109. { role: "user", content: "first" },
  110. { role: "assistant", content: [{ type: "text", text: " " }] },
  111. {
  112. role: "user",
  113. content: "tool result",
  114. toolCallId: "call_1",
  115. toolName: "Read",
  116. },
  117. ];
  118. expect(normalizeReasoningHistory(messages)).toEqual([
  119. { role: "user", content: "first" },
  120. {
  121. role: "user",
  122. content: "tool result",
  123. toolCallId: "call_1",
  124. toolName: "Read",
  125. },
  126. ]);
  127. });
  128. it.each([
  129. {
  130. expected: { type: "ephemeral" as const },
  131. first: { type: "ephemeral" as const, ttl: "1h" as const },
  132. name: "prefers the later user cache control",
  133. second: { type: "ephemeral" as const },
  134. },
  135. {
  136. expected: { type: "ephemeral" as const, ttl: "1h" as const },
  137. first: { type: "ephemeral" as const, ttl: "1h" as const },
  138. name: "falls back to the earlier user cache control",
  139. second: undefined,
  140. },
  141. ])("$name when whitespace cleanup merges users", ({ expected, first, second }) => {
  142. const messages: ModelInputMessage[] = [
  143. { role: "user", content: "first", cacheControl: first },
  144. { role: "assistant", content: [{ type: "text", text: " " }] },
  145. {
  146. role: "user",
  147. content: "second",
  148. ...(second ? { cacheControl: second } : {}),
  149. },
  150. ];
  151. const normalized = normalizeReasoningHistory(messages);
  152. expect(normalized).toEqual([
  153. {
  154. role: "user",
  155. content: [
  156. { type: "text", text: "first\n" },
  157. { type: "text", text: "second" },
  158. ],
  159. cacheControl: expected,
  160. },
  161. ]);
  162. expect(normalized[0]?.cacheControl).not.toBe(first);
  163. if (second) expect(normalized[0]?.cacheControl).not.toBe(second);
  164. });
  165. it("preserves mixed string and block user content without inventing a text separator", () => {
  166. const image = {
  167. type: "image" as const,
  168. dataUrl: "data:image/png;base64,aW1hZ2U=",
  169. mediaType: "image/png",
  170. };
  171. const messages: ModelInputMessage[] = [
  172. { role: "user", content: "first" },
  173. { role: "assistant", content: [{ type: "text", text: " " }] },
  174. { role: "user", content: [image] },
  175. ];
  176. expect(normalizeReasoningHistory(messages)).toEqual([
  177. {
  178. role: "user",
  179. content: [{ type: "text", text: "first" }, image],
  180. },
  181. ]);
  182. });
  183. it("does not infer a model mismatch when assistant provenance is missing", () => {
  184. const messages: ModelInputMessage[] = [
  185. {
  186. role: "assistant",
  187. content: [reasoning("signed", { signature: "sig_1" }), { type: "text", text: "answer" }],
  188. },
  189. { role: "user", content: "next" },
  190. ];
  191. expect(normalizeReasoningHistory(messages, modelIdentity("provider-b/model-b"))).toBe(messages);
  192. });
  193. it("removes orphan reasoning-only assistant messages", () => {
  194. const messages: ModelInputMessage[] = [
  195. { role: "user", content: "first" },
  196. { role: "assistant", content: [reasoning("orphan")] },
  197. { role: "user", content: "second" },
  198. ];
  199. expect(normalizeReasoningHistory(messages)).toEqual([
  200. { role: "user", content: "first" },
  201. { role: "user", content: "second" },
  202. ]);
  203. });
  204. it("removes a final reasoning-only assistant before trailing cleanup", () => {
  205. const messages: ModelInputMessage[] = [
  206. { role: "user", content: "question" },
  207. { role: "assistant", content: [reasoning("orphan")] },
  208. ];
  209. expect(normalizeReasoningHistory(messages)).toEqual([{ role: "user", content: "question" }]);
  210. });
  211. it("removes only the final assistant's consecutive trailing reasoning", () => {
  212. const messages: ModelInputMessage[] = [
  213. { role: "user", content: "question" },
  214. {
  215. role: "assistant",
  216. content: [
  217. reasoning("kept"),
  218. { type: "text", text: "answer" },
  219. reasoning("trailing one"),
  220. reasoning("trailing two"),
  221. ],
  222. },
  223. ];
  224. expect(normalizeReasoningHistory(messages)).toEqual([
  225. { role: "user", content: "question" },
  226. {
  227. role: "assistant",
  228. content: [reasoning("kept"), { type: "text", text: "answer" }],
  229. },
  230. ]);
  231. });
  232. it("keeps tool calls when trailing reasoning leaves assistant content empty", () => {
  233. const messages: ModelInputMessage[] = [
  234. { role: "user", content: "question" },
  235. {
  236. role: "assistant",
  237. content: [reasoning("trailing")],
  238. toolCalls: [{ id: "call_1", name: "Read", input: { file_path: "README.md" } }],
  239. },
  240. ];
  241. expect(normalizeReasoningHistory(messages)).toEqual([
  242. { role: "user", content: "question" },
  243. {
  244. role: "assistant",
  245. content: [],
  246. toolCalls: [{ id: "call_1", name: "Read", input: { file_path: "README.md" } }],
  247. },
  248. ]);
  249. });
  250. it("does not mutate canonical history and preserves the original reference when unchanged", () => {
  251. const messages: ModelInputMessage[] = [
  252. { role: "assistant", content: [{ type: "text", text: "answer" }] },
  253. { role: "user", content: "next" },
  254. ];
  255. const snapshot = structuredClone(messages);
  256. expect(normalizeReasoningHistory(messages)).toBe(messages);
  257. expect(messages).toEqual(snapshot);
  258. });
  259. it("removes only signed and redacted reasoning after a signature rejection", () => {
  260. const messages: ModelInputMessage[] = [
  261. {
  262. role: "assistant",
  263. content: [
  264. reasoning("signed", { signature: "sig_1" }),
  265. reasoning("unsigned"),
  266. reasoning("redacted", { redactedData: "redacted_1" }),
  267. { type: "text", text: "answer" },
  268. ],
  269. },
  270. { role: "user", content: "next" },
  271. ];
  272. const snapshot = structuredClone(messages);
  273. expect(removeRejectedReasoning(messages)).toEqual([
  274. {
  275. role: "assistant",
  276. content: [reasoning("unsigned"), { type: "text", text: "answer" }],
  277. },
  278. { role: "user", content: "next" },
  279. ]);
  280. expect(messages).toEqual(snapshot);
  281. expect(
  282. removeRejectedReasoning([
  283. { role: "assistant", content: [reasoning("unsigned"), { type: "text", text: "answer" }] },
  284. { role: "user", content: "next" },
  285. ]),
  286. ).toEqual([
  287. { role: "assistant", content: [reasoning("unsigned"), { type: "text", text: "answer" }] },
  288. { role: "user", content: "next" },
  289. ]);
  290. });
  291. it("adds the [Thinking removed] placeholder when only unsigned reasoning remains", () => {
  292. const messages: ModelInputMessage[] = [
  293. {
  294. role: "assistant",
  295. content: [
  296. reasoning("signed", { signature: "sig_1" }),
  297. reasoning("unsigned"),
  298. { type: "text", text: " " },
  299. ],
  300. },
  301. { role: "user", content: "next" },
  302. ];
  303. expect(removeRejectedReasoning(messages)).toEqual([
  304. {
  305. role: "assistant",
  306. content: [reasoning("unsigned"), { type: "text", text: "[Thinking removed]" }],
  307. },
  308. { role: "user", content: "next" },
  309. ]);
  310. });
  311. it("does not add a rejection placeholder when a tool call remains", () => {
  312. const messages: ModelInputMessage[] = [
  313. {
  314. role: "assistant",
  315. content: [reasoning("signed", { signature: "sig_1" }), { type: "text", text: " " }],
  316. toolCalls: [{ id: "call_1", name: "Read", input: { file_path: "README.md" } }],
  317. },
  318. { role: "user", content: "next" },
  319. ];
  320. expect(removeRejectedReasoning(messages)).toEqual([
  321. {
  322. role: "assistant",
  323. content: [],
  324. toolCalls: [{ id: "call_1", name: "Read", input: { file_path: "README.md" } }],
  325. },
  326. { role: "user", content: "next" },
  327. ]);
  328. });
  329. });
  330. describe("thinking signature rejection", () => {
  331. it.each([
  332. "signature in thinking block is invalid",
  333. "thinking block cannot be modified",
  334. "`thinking` has an invalid signature",
  335. "redacted_thinking cannot be modified",
  336. ])("accepts the supported HTTP 400 message: %s", (message) => {
  337. expect(isThinkingSignatureRejection(apiError(message, 400))).toBe(true);
  338. });
  339. it.each([
  340. apiError("signature in thinking block is invalid", 500),
  341. apiError("unrelated invalid request", 400),
  342. apiError("thinking budget is invalid", 400),
  343. ])("rejects unrelated errors", (error) => {
  344. expect(isThinkingSignatureRejection(error)).toBe(false);
  345. });
  346. });
  347. function assistantWithReasoning(
  348. content: Extract<ModelInputMessage["content"], unknown[]>,
  349. model: Pick<ModelInputMessage, "providerId" | "modelId">,
  350. ): ModelInputMessage {
  351. return { role: "assistant", content, ...model };
  352. }
  353. function modelIdentity(input: string): Pick<ModelInputMessage, "providerId" | "modelId"> {
  354. const separator = input.indexOf("/");
  355. return {
  356. providerId: input.slice(0, separator) as never,
  357. modelId: input.slice(separator + 1) as never,
  358. };
  359. }
  360. function reasoning(
  361. text: string,
  362. anthropic?: Record<string, unknown>,
  363. ): Extract<ModelInputMessage["content"], unknown[]>[number] {
  364. return {
  365. type: "reasoning",
  366. text,
  367. ...(anthropic ? { providerOptions: { anthropic } } : {}),
  368. };
  369. }
  370. function apiError(message: string, statusCode: number): Error & { statusCode: number } {
  371. return Object.assign(new Error(message), { statusCode });
  372. }