model-execution.test.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. import http, { type Server } from "node:http";
  2. import type { AddressInfo } from "node:net";
  3. import { generateText, jsonSchema, Output } from "ai";
  4. import { describe, expect, it, vi } from "vitest";
  5. import { createAnthropicCompatFetch } from "../src/model/anthropic-stream-compat.js";
  6. import {
  7. ProviderBusinessError,
  8. createProviderBusinessErrorFetch,
  9. } from "../src/model/model-execution.js";
  10. import { TestProviderConfigFixture } from "./test-provider-config.js";
  11. describe("AI SDK Provider execution", () => {
  12. it("adds Authorization alongside x-api-key for Anthropic provider requests", async () => {
  13. const receivedHeaders: http.IncomingHttpHeaders[] = [];
  14. const endpointRoutingPort = {
  15. resolve: vi.fn(async (url: string) => ({ routed: false, url })),
  16. };
  17. const server = http.createServer((request, response) => {
  18. receivedHeaders.push(request.headers);
  19. request.resume();
  20. response.writeHead(200, { "content-type": "application/json" });
  21. response.end(
  22. JSON.stringify({
  23. id: "msg-test",
  24. type: "message",
  25. role: "assistant",
  26. model: "claude-test",
  27. content: [{ type: "text", text: "ok" }],
  28. stop_reason: "end_turn",
  29. stop_sequence: null,
  30. usage: { input_tokens: 1, output_tokens: 1 },
  31. }),
  32. );
  33. });
  34. try {
  35. const baseURL = await listenServer(server);
  36. const registry = new TestProviderConfigFixture({
  37. endpointRoutingPort,
  38. env: {},
  39. providers: {
  40. anthropic: {
  41. kind: "anthropic",
  42. baseURL,
  43. apiKey: "anthropic-key",
  44. },
  45. },
  46. });
  47. const resolved = registry.resolve("anthropic/claude-test");
  48. await expect(generateText({ model: resolved.model, prompt: "hello" })).resolves.toMatchObject(
  49. { text: "ok" },
  50. );
  51. expect(receivedHeaders[0]).toMatchObject({
  52. authorization: "Bearer anthropic-key",
  53. "x-api-key": "anthropic-key",
  54. "anthropic-version": "2023-06-01",
  55. });
  56. expect(endpointRoutingPort.resolve).toHaveBeenCalledWith(
  57. expect.any(String),
  58. expect.not.objectContaining({ apiKey: expect.any(String) }),
  59. );
  60. } finally {
  61. await closeServer(server);
  62. }
  63. });
  64. it("preserves separate Memory selector user messages in the final Anthropic body", async () => {
  65. const requestBodies: Record<string, unknown>[] = [];
  66. const server = http.createServer(async (request, response) => {
  67. let body = "";
  68. for await (const chunk of request) body += chunk.toString();
  69. requestBodies.push(JSON.parse(body) as Record<string, unknown>);
  70. response.writeHead(400, { "content-type": "application/json" });
  71. response.end(
  72. JSON.stringify({
  73. type: "error",
  74. error: { type: "invalid_request_error", message: "request captured" },
  75. }),
  76. );
  77. });
  78. try {
  79. const baseURL = await listenServer(server);
  80. const registry = new TestProviderConfigFixture({
  81. env: {},
  82. providers: {
  83. anthropic: {
  84. kind: "anthropic",
  85. baseURL,
  86. apiKey: "anthropic-key",
  87. },
  88. },
  89. });
  90. const resolved = registry.resolve("anthropic/claude-fable-5-cc", {
  91. maxOutputTokens: 256,
  92. });
  93. const responseSchema = {
  94. additionalProperties: false,
  95. properties: {
  96. selected_memories: { items: { type: "string" }, type: "array" },
  97. selected_knowledge_ids: { items: { type: "string" }, type: "array" },
  98. },
  99. required: ["selected_memories"],
  100. type: "object",
  101. } as const;
  102. await expect(
  103. generateText({
  104. model: resolved.model,
  105. messages: [
  106. { role: "user", content: "Available memories:\n- project.md" },
  107. { role: "user", content: "Select memories relevant to:\nproject policy" },
  108. ],
  109. maxOutputTokens: 256,
  110. maxRetries: 0,
  111. output: Output.object({ schema: jsonSchema(responseSchema) }),
  112. providerOptions: {
  113. anthropic: { structuredOutputMode: "outputFormat" },
  114. },
  115. }),
  116. ).rejects.toThrow("request captured");
  117. expect(requestBodies[0]?.messages).toEqual([
  118. {
  119. role: "user",
  120. content: [{ type: "text", text: "Available memories:\n- project.md" }],
  121. },
  122. {
  123. role: "user",
  124. content: [{ type: "text", text: "Select memories relevant to:\nproject policy" }],
  125. },
  126. ]);
  127. expect(requestBodies[0]?.output_config).toEqual({
  128. format: { type: "json_schema", schema: responseSchema },
  129. });
  130. expect(requestBodies[0]?.max_tokens).toBe(256);
  131. expect(requestBodies[0]).not.toHaveProperty("thinking");
  132. } finally {
  133. await closeServer(server);
  134. }
  135. });
  136. it("preserves retry headers on provider business errors", async () => {
  137. let originalResponse: Response | undefined;
  138. const fetch = createProviderBusinessErrorFetch({
  139. fetch: async () => {
  140. originalResponse = new Response(
  141. JSON.stringify({
  142. error: {
  143. code: "1305",
  144. message: "平台流量限制,请稍后重试",
  145. },
  146. request_id: "20260703111207fd2a863001c64c94",
  147. type: "error",
  148. }),
  149. {
  150. headers: {
  151. "content-type": "application/json",
  152. "retry-after": "41",
  153. "x-should-retry": "true",
  154. },
  155. status: 529,
  156. },
  157. );
  158. return originalResponse;
  159. },
  160. providerId: "zai",
  161. providerKind: "anthropic",
  162. });
  163. await expect(fetch("https://api.z.ai/api/anthropic/v1/messages")).rejects.toMatchObject({
  164. providerCode: "1305",
  165. responseHeaders: {
  166. "retry-after": "41",
  167. "x-should-retry": "true",
  168. },
  169. responseStatus: 529,
  170. });
  171. // 回归 BG26:解析 clone 后抛业务错误时,原始 body 也必须被取消/消费,避免连接池泄漏。
  172. expect(originalResponse?.bodyUsed).toBe(true);
  173. });
  174. it("preserves a stable TLS code when provider fetch rejects with a nested Node TLS error", async () => {
  175. const tlsCause = Object.assign(
  176. new Error(
  177. "self-signed certificate; if the root CA is installed locally, try running Node.js with --use-system-ca",
  178. ),
  179. { code: "DEPTH_ZERO_SELF_SIGNED_CERT" },
  180. );
  181. const fetch = createProviderBusinessErrorFetch({
  182. fetch: async () => {
  183. throw new TypeError("fetch failed", { cause: tlsCause });
  184. },
  185. providerId: "zai",
  186. providerKind: "anthropic",
  187. });
  188. await expect(fetch("https://api.z.ai/api/anthropic/v1/messages")).rejects.toMatchObject({
  189. cause: { cause: tlsCause },
  190. code: "MODEL_TLS_VALIDATION_FAILED",
  191. });
  192. });
  193. it("does not let pending response body cleanup block provider business errors", async () => {
  194. vi.useFakeTimers();
  195. try {
  196. let notifyCleanupStarted!: () => void;
  197. const cleanupStarted = new Promise<void>((resolve) => {
  198. notifyCleanupStarted = resolve;
  199. });
  200. const response = new Response(
  201. JSON.stringify({
  202. error: {
  203. code: "1305",
  204. message: "平台流量限制,请稍后重试",
  205. },
  206. }),
  207. {
  208. headers: { "content-type": "application/json" },
  209. status: 429,
  210. },
  211. );
  212. const nativeClone = response.clone.bind(response);
  213. vi.spyOn(response, "clone").mockImplementation(() => {
  214. const cloned = nativeClone();
  215. // Response.clone() 会替换原 response 的 body 分支,清理必须覆盖 clone 后的原始分支。
  216. vi.spyOn(response, "arrayBuffer").mockImplementation(() => {
  217. notifyCleanupStarted();
  218. return new Promise<never>(() => undefined);
  219. });
  220. return cloned;
  221. });
  222. const fetch = createProviderBusinessErrorFetch({
  223. fetch: async () => response,
  224. providerId: "zai",
  225. providerKind: "anthropic",
  226. });
  227. const request = fetch("https://api.z.ai/api/anthropic/v1/messages");
  228. const rejection = expect(request).rejects.toMatchObject({
  229. message: "平台流量限制,请稍后重试",
  230. name: "ProviderBusinessError",
  231. providerCode: "1305",
  232. responseStatus: 429,
  233. } satisfies Partial<ProviderBusinessError>);
  234. await cleanupStarted;
  235. await vi.advanceTimersByTimeAsync(1_000);
  236. await rejection;
  237. } finally {
  238. vi.useRealTimers();
  239. }
  240. });
  241. it("adds the Anthropic v1 API prefix when consuming explicit base URLs", () => {
  242. const registry = new TestProviderConfigFixture({
  243. env: {},
  244. providers: {
  245. anthropic: {
  246. kind: "anthropic",
  247. baseURL: "https://example.test/anthropic",
  248. apiKey: "secret",
  249. },
  250. anthropicV1: {
  251. kind: "anthropic",
  252. baseURL: "https://example.test/anthropic/v1/",
  253. apiKey: "secret",
  254. },
  255. },
  256. });
  257. const normalized = registry.resolve("anthropic/claude-test").model as unknown as {
  258. config: { baseURL: string };
  259. };
  260. const alreadyVersioned = registry.resolve("anthropicV1/claude-test").model as unknown as {
  261. config: { baseURL: string };
  262. };
  263. expect(normalized.config.baseURL).toBe("https://example.test/anthropic/v1");
  264. expect(alreadyVersioned.config.baseURL).toBe("https://example.test/anthropic/v1");
  265. });
  266. it("turns HTTP 200 success=false provider bodies into business errors", async () => {
  267. const fetch = createProviderBusinessErrorFetch({
  268. fetch: async () =>
  269. new Response(
  270. JSON.stringify({
  271. code: 500,
  272. msg: "404 NOT_FOUND",
  273. success: false,
  274. }),
  275. {
  276. headers: { "content-type": "application/json" },
  277. status: 200,
  278. },
  279. ),
  280. providerId: "zai",
  281. providerKind: "openai-compatible",
  282. });
  283. await expect(fetch("https://example.test/v1/chat/completions")).rejects.toMatchObject({
  284. code: "PROVIDER_BUSINESS_ERROR",
  285. message: "404 NOT_FOUND",
  286. name: "ProviderBusinessError",
  287. providerCode: 500,
  288. providerId: "zai",
  289. responseStatus: 200,
  290. statusCode: 500,
  291. } satisfies Partial<ProviderBusinessError>);
  292. });
  293. it("turns HTTP 200 SSE error events into business errors", async () => {
  294. const fetch = createProviderBusinessErrorFetch({
  295. fetch: async () =>
  296. sseResponse([
  297. sseFrame("error", {
  298. error: {
  299. code: "1311",
  300. message: "当前订阅套餐暂未开放GLM-5V-Turbo权限",
  301. },
  302. request_id: "20260505201906b147bc4aa7cd4e58",
  303. }),
  304. "data: [DONE]\n\n",
  305. ]),
  306. providerId: "zai",
  307. providerKind: "openai-compatible",
  308. });
  309. const response = await fetch("https://example.test/v1/chat/completions?stream=true");
  310. let error: unknown;
  311. try {
  312. await response.text();
  313. } catch (caught) {
  314. error = caught;
  315. }
  316. expect(error).toMatchObject({
  317. code: "PROVIDER_BUSINESS_ERROR",
  318. message: "当前订阅套餐暂未开放GLM-5V-Turbo权限",
  319. name: "ProviderBusinessError",
  320. providerCode: "1311",
  321. providerId: "zai",
  322. providerRequestId: "20260505201906b147bc4aa7cd4e58",
  323. responseStatus: 200,
  324. } satisfies Partial<ProviderBusinessError>);
  325. expect((error as ProviderBusinessError).statusCode).toBeUndefined();
  326. });
  327. it("keeps successful provider SSE responses readable", async () => {
  328. const fetch = createProviderBusinessErrorFetch({
  329. fetch: async () =>
  330. sseResponse([
  331. sseFrame("message", {
  332. choices: [{ delta: { content: "ok" } }],
  333. code: 0,
  334. }),
  335. "data: [DONE]\n\n",
  336. ]),
  337. providerId: "local",
  338. providerKind: "openai-compatible",
  339. });
  340. const response = await fetch("https://example.test/v1/chat/completions?stream=true");
  341. await expect(response.text()).resolves.toContain('"content":"ok"');
  342. });
  343. it("turns non-zero code or error_code provider bodies into business errors", async () => {
  344. const fetch = createProviderBusinessErrorFetch({
  345. fetch: async () =>
  346. new Response(
  347. JSON.stringify({
  348. error_code: "model_not_found",
  349. message: "model does not exist",
  350. }),
  351. {
  352. headers: { "content-type": "application/json" },
  353. status: 200,
  354. },
  355. ),
  356. providerId: "local",
  357. providerKind: "openai-compatible",
  358. });
  359. await expect(fetch("https://example.test/v1/chat/completions")).rejects.toMatchObject({
  360. message: "model does not exist",
  361. providerCode: "model_not_found",
  362. responseStatus: 200,
  363. statusCode: undefined,
  364. } satisfies Partial<ProviderBusinessError>);
  365. });
  366. it("turns HTTP 403 zcode-plan security verification failures into business errors", async () => {
  367. const body = JSON.stringify({ code: 3007, msg: "security verify failed" });
  368. const fetchWithJsonContentType = createProviderBusinessErrorFetch({
  369. fetch: async () =>
  370. new Response(body, {
  371. headers: { "content-type": "application/json" },
  372. status: 403,
  373. }),
  374. providerId: "account:zai-individual-coding-plan",
  375. providerKind: "openai-compatible",
  376. });
  377. const fetchWithoutContentType = createProviderBusinessErrorFetch({
  378. fetch: async () =>
  379. new Response(body, {
  380. headers: { "content-length": String(body.length) },
  381. status: 403,
  382. }),
  383. providerId: "account:zai-individual-coding-plan",
  384. providerKind: "openai-compatible",
  385. });
  386. await expect(
  387. fetchWithJsonContentType("https://example.test/v1/chat/completions"),
  388. ).rejects.toMatchObject({
  389. code: "PROVIDER_BUSINESS_ERROR",
  390. message: "security verify failed",
  391. providerCode: 3007,
  392. responseStatus: 403,
  393. } satisfies Partial<ProviderBusinessError>);
  394. await expect(
  395. fetchWithoutContentType("https://example.test/v1/chat/completions"),
  396. ).rejects.toMatchObject({
  397. code: "PROVIDER_BUSINESS_ERROR",
  398. message: "security verify failed",
  399. providerCode: 3007,
  400. responseStatus: 403,
  401. } satisfies Partial<ProviderBusinessError>);
  402. });
  403. it("keeps successful provider JSON responses readable", async () => {
  404. const body = {
  405. choices: [{ message: { content: "ok" } }],
  406. code: 0,
  407. success: true,
  408. };
  409. const fetch = createProviderBusinessErrorFetch({
  410. fetch: async () =>
  411. new Response(JSON.stringify(body), {
  412. headers: { "content-type": "application/json" },
  413. status: 200,
  414. }),
  415. providerId: "local",
  416. providerKind: "openai-compatible",
  417. });
  418. const response = await fetch("https://example.test/v1/chat/completions");
  419. await expect(response.json()).resolves.toEqual(body);
  420. });
  421. it("routes provider fetch through explicit ZCODE_HTTP_PROXY env", async () => {
  422. const proxyRequests: string[] = [];
  423. const upstream = http.createServer((request, response) => {
  424. response.writeHead(200, { "content-type": "application/json" });
  425. response.end(JSON.stringify({ path: request.url, success: true }));
  426. });
  427. const proxy = http.createServer((clientRequest, clientResponse) => {
  428. proxyRequests.push(clientRequest.url ?? "");
  429. if (!clientRequest.url) {
  430. clientResponse.writeHead(400);
  431. clientResponse.end();
  432. return;
  433. }
  434. const target = new URL(clientRequest.url);
  435. const upstreamRequest = http.request(
  436. {
  437. headers: clientRequest.headers,
  438. hostname: target.hostname,
  439. method: clientRequest.method,
  440. path: `${target.pathname}${target.search}`,
  441. port: target.port,
  442. },
  443. (upstreamResponse) => {
  444. clientResponse.writeHead(upstreamResponse.statusCode ?? 502, upstreamResponse.headers);
  445. upstreamResponse.pipe(clientResponse);
  446. },
  447. );
  448. upstreamRequest.once("error", (error) => {
  449. clientResponse.writeHead(502, { "content-type": "text/plain" });
  450. clientResponse.end(String(error));
  451. });
  452. clientRequest.pipe(upstreamRequest);
  453. });
  454. try {
  455. const upstreamBaseUrl = await listenServer(upstream);
  456. const proxyBaseUrl = await listenServer(proxy);
  457. const fetch = createProviderBusinessErrorFetch({
  458. env: {
  459. ZCODE_HTTP_PROXY: proxyBaseUrl,
  460. },
  461. providerId: "local",
  462. providerKind: "openai-compatible",
  463. });
  464. const response = await fetch(`${upstreamBaseUrl}/v1/chat/completions?stream=true`, {
  465. headers: { "content-type": "application/json" },
  466. method: "POST",
  467. body: JSON.stringify({ model: "glm-5.1" }),
  468. });
  469. await expect(response.json()).resolves.toEqual({
  470. path: "/v1/chat/completions?stream=true",
  471. success: true,
  472. });
  473. expect(proxyRequests).toEqual([`${upstreamBaseUrl}/v1/chat/completions?stream=true`]);
  474. } finally {
  475. await closeServer(proxy);
  476. await closeServer(upstream);
  477. }
  478. });
  479. it("bypasses provider proxy when explicit noProxy matches target host", async () => {
  480. const proxyRequests: string[] = [];
  481. const upstream = http.createServer((_request, response) => {
  482. response.writeHead(200, { "content-type": "application/json" });
  483. response.end(JSON.stringify({ direct: true, success: true }));
  484. });
  485. const proxy = http.createServer((request, response) => {
  486. proxyRequests.push(request.url ?? "");
  487. response.writeHead(502, { "content-type": "application/json" });
  488. response.end(JSON.stringify({ success: false }));
  489. });
  490. try {
  491. const upstreamBaseUrl = await listenServer(upstream);
  492. const proxyBaseUrl = await listenServer(proxy);
  493. const fetch = createProviderBusinessErrorFetch({
  494. env: {
  495. ZCODE_HTTP_PROXY: proxyBaseUrl,
  496. },
  497. noProxy: "127.0.0.1",
  498. providerId: "local",
  499. providerKind: "openai-compatible",
  500. });
  501. const response = await fetch(`${upstreamBaseUrl}/v1/chat/completions`, {
  502. headers: { "content-type": "application/json" },
  503. method: "POST",
  504. body: JSON.stringify({ model: "glm-5.1" }),
  505. });
  506. await expect(response.json()).resolves.toEqual({ direct: true, success: true });
  507. expect(proxyRequests).toEqual([]);
  508. } finally {
  509. await closeServer(proxy);
  510. await closeServer(upstream);
  511. }
  512. });
  513. });
  514. describe("createAnthropicCompatFetch", () => {
  515. it("filters assistant-side bare tool_result content blocks from Anthropic SSE", async () => {
  516. const fetch = createAnthropicCompatFetch(async () =>
  517. sseResponse([
  518. sseFrame("message_start", {
  519. type: "message_start",
  520. message: {
  521. id: "msg_1",
  522. type: "message",
  523. role: "assistant",
  524. model: "glm-5.1",
  525. content: [],
  526. stop_reason: null,
  527. stop_sequence: null,
  528. usage: { input_tokens: 0, output_tokens: 0 },
  529. },
  530. }),
  531. sseFrame("content_block_start", {
  532. type: "content_block_start",
  533. index: 1,
  534. content_block: { type: "text", text: "" },
  535. }),
  536. sseFrame("content_block_delta", {
  537. type: "content_block_delta",
  538. index: 1,
  539. delta: { type: "text_delta", text: "Output already summarized" },
  540. }),
  541. sseFrame("content_block_stop", { type: "content_block_stop", index: 1 }),
  542. sseFrame("content_block_start", {
  543. type: "content_block_start",
  544. index: 2,
  545. content_block: {
  546. type: "server_tool_use",
  547. id: "call_image",
  548. name: "analyze_image",
  549. input: {},
  550. },
  551. }),
  552. sseFrame("content_block_stop", { type: "content_block_stop", index: 2 }),
  553. sseFrame("content_block_start", {
  554. type: "content_block_start",
  555. index: 4,
  556. content_block: {
  557. type: "tool_result",
  558. tool_use_id: "call_image",
  559. content: '["您尚未登录"]',
  560. },
  561. }),
  562. sseFrame("content_block_stop", { type: "content_block_stop", index: 4 }),
  563. sseFrame("content_block_start", {
  564. type: "content_block_start",
  565. index: 5,
  566. content_block: { type: "text", text: "" },
  567. }),
  568. sseFrame("content_block_delta", {
  569. type: "content_block_delta",
  570. index: 5,
  571. delta: { type: "text_delta", text: "The image says 您尚未登录." },
  572. }),
  573. ]),
  574. );
  575. const response = await fetch("https://example.test/v1/messages");
  576. const text = await response.text();
  577. expect(text).toContain('"type":"server_tool_use"');
  578. expect(text).toContain("Output already summarized");
  579. expect(text).toContain("The image says");
  580. expect(text).not.toContain('"type":"tool_result"');
  581. expect(text).not.toContain('"index":4');
  582. });
  583. it("keeps typed Anthropic tool result blocks", async () => {
  584. const fetch = createAnthropicCompatFetch(async () =>
  585. sseResponse([
  586. sseFrame("content_block_start", {
  587. type: "content_block_start",
  588. index: 3,
  589. content_block: {
  590. type: "web_search_tool_result",
  591. tool_use_id: "srv_1",
  592. content: [
  593. {
  594. type: "web_search_result",
  595. url: "https://example.test",
  596. title: "Example",
  597. encrypted_content: "opaque",
  598. },
  599. ],
  600. },
  601. }),
  602. sseFrame("content_block_stop", { type: "content_block_stop", index: 3 }),
  603. ]),
  604. );
  605. const response = await fetch("https://example.test/v1/messages");
  606. const text = await response.text();
  607. expect(text).toContain('"type":"web_search_tool_result"');
  608. expect(text).toContain('"index":3');
  609. });
  610. it("synthesizes a signature delta for thinking signatures delivered at block start", async () => {
  611. const start = sseFrame("content_block_start", {
  612. type: "content_block_start",
  613. index: 0,
  614. content_block: { type: "thinking", thinking: "", signature: "sig_start" },
  615. });
  616. const thinking = sseFrame("content_block_delta", {
  617. type: "content_block_delta",
  618. index: 0,
  619. delta: { type: "thinking_delta", thinking: "internal trace" },
  620. });
  621. const stop = sseFrame("content_block_stop", { type: "content_block_stop", index: 0 });
  622. const fetch = createAnthropicCompatFetch(async () => sseResponse([start, thinking, stop]));
  623. const response = await fetch("https://example.test/v1/messages");
  624. await expect(response.text()).resolves.toBe(
  625. [
  626. start,
  627. thinking,
  628. sseFrame("content_block_delta", {
  629. type: "content_block_delta",
  630. index: 0,
  631. delta: { type: "signature_delta", signature: "sig_start" },
  632. }),
  633. stop,
  634. ].join(""),
  635. );
  636. });
  637. it("does not duplicate a native signature delta", async () => {
  638. const frames = [
  639. sseFrame("content_block_start", {
  640. type: "content_block_start",
  641. index: 0,
  642. content_block: { type: "thinking", thinking: "", signature: "sig_start" },
  643. }),
  644. sseFrame("content_block_delta", {
  645. type: "content_block_delta",
  646. index: 0,
  647. delta: { type: "signature_delta", signature: "sig_native" },
  648. }),
  649. sseFrame("content_block_stop", { type: "content_block_stop", index: 0 }),
  650. ];
  651. const fetch = createAnthropicCompatFetch(async () => sseResponse(frames));
  652. const response = await fetch("https://example.test/v1/messages");
  653. await expect(response.text()).resolves.toBe(frames.join(""));
  654. });
  655. it("synthesizes start-delivered signatures across fragmented CRLF frames", async () => {
  656. const separator = "\r\n\r\n";
  657. const start = sseFrame(
  658. "content_block_start",
  659. {
  660. type: "content_block_start",
  661. index: 0,
  662. content_block: { type: "thinking", thinking: "", signature: "sig_crlf" },
  663. },
  664. separator,
  665. );
  666. const stop = sseFrame(
  667. "content_block_stop",
  668. { type: "content_block_stop", index: 0 },
  669. separator,
  670. );
  671. const wire = `${start}${stop}`;
  672. const separatorSplit = start.indexOf(separator) + separator.length - 1;
  673. const fetch = createAnthropicCompatFetch(async () =>
  674. chunkedSseResponse([
  675. wire.slice(0, separatorSplit),
  676. wire.slice(separatorSplit, start.length + 7),
  677. wire.slice(start.length + 7),
  678. ]),
  679. );
  680. const response = await fetch("https://example.test/v1/messages");
  681. await expect(response.text()).resolves.toBe(
  682. [
  683. start,
  684. sseFrame(
  685. "content_block_delta",
  686. {
  687. type: "content_block_delta",
  688. index: 0,
  689. delta: { type: "signature_delta", signature: "sig_crlf" },
  690. },
  691. separator,
  692. ),
  693. stop,
  694. ].join(""),
  695. );
  696. });
  697. it("flushes a final stop frame without a trailing SSE separator", async () => {
  698. const start = sseFrame("content_block_start", {
  699. type: "content_block_start",
  700. index: 0,
  701. content_block: { type: "thinking", thinking: "", signature: "sig_final" },
  702. });
  703. const stop = `event: content_block_stop\ndata: ${JSON.stringify({
  704. type: "content_block_stop",
  705. index: 0,
  706. })}`;
  707. const fetch = createAnthropicCompatFetch(async () =>
  708. chunkedSseResponse([start, stop.slice(0, 11), stop.slice(11)]),
  709. );
  710. const response = await fetch("https://example.test/v1/messages");
  711. await expect(response.text()).resolves.toBe(
  712. [
  713. start,
  714. sseFrame("content_block_delta", {
  715. type: "content_block_delta",
  716. index: 0,
  717. delta: { type: "signature_delta", signature: "sig_final" },
  718. }),
  719. stop,
  720. ].join(""),
  721. );
  722. });
  723. it("drops unsigned thinking blocks from JSON message responses", async () => {
  724. const body = JSON.stringify({
  725. id: "msg_1",
  726. type: "message",
  727. role: "assistant",
  728. model: "glm-0606",
  729. content: [
  730. { type: "thinking", thinking: "internal trace" },
  731. { type: "text", text: "Visible answer" },
  732. ],
  733. stop_reason: "end_turn",
  734. stop_sequence: null,
  735. usage: { input_tokens: 1, output_tokens: 2 },
  736. });
  737. const fetch = createAnthropicCompatFetch(
  738. async () =>
  739. new Response(body, {
  740. headers: {
  741. "content-length": String(body.length),
  742. "content-type": "application/json",
  743. },
  744. }),
  745. );
  746. const response = await fetch("https://example.test/v1/messages");
  747. const parsed = (await response.json()) as {
  748. content: Array<{ type: string; text?: string; thinking?: string }>;
  749. };
  750. expect(parsed.content).toEqual([{ type: "text", text: "Visible answer" }]);
  751. expect(response.headers.get("content-length")).toBeNull();
  752. });
  753. it("keeps signed thinking blocks in JSON message responses", async () => {
  754. const body = JSON.stringify({
  755. content: [
  756. { type: "thinking", thinking: "trusted trace", signature: "sig_1" },
  757. { type: "text", text: "Visible answer" },
  758. ],
  759. });
  760. const fetch = createAnthropicCompatFetch(
  761. async () =>
  762. new Response(body, {
  763. headers: {
  764. "content-length": String(body.length),
  765. "content-type": "application/json",
  766. },
  767. }),
  768. );
  769. const response = await fetch("https://example.test/v1/messages");
  770. await expect(response.text()).resolves.toBe(body);
  771. expect(response.headers.get("content-length")).toBe(String(body.length));
  772. });
  773. it.each([
  774. ["an empty string signature", { signature: "" }],
  775. ["redacted data", { redactedData: "opaque-redacted-thinking" }],
  776. ])("keeps JSON thinking blocks carrying %s", async (_label, metadata) => {
  777. const body = JSON.stringify({
  778. content: [
  779. { type: "thinking", thinking: "trusted trace", ...metadata },
  780. { type: "text", text: "Visible answer" },
  781. ],
  782. });
  783. const fetch = createAnthropicCompatFetch(
  784. async () =>
  785. new Response(body, {
  786. headers: {
  787. "content-length": String(body.length),
  788. "content-type": "application/json",
  789. },
  790. }),
  791. );
  792. const response = await fetch("https://example.test/v1/messages");
  793. await expect(response.text()).resolves.toBe(body);
  794. expect(response.headers.get("content-length")).toBe(String(body.length));
  795. });
  796. it("does not rewrite unrelated JSON responses", async () => {
  797. const body = JSON.stringify({
  798. type: "content_block_start",
  799. content_block: { type: "tool_result" },
  800. });
  801. const fetch = createAnthropicCompatFetch(
  802. async () =>
  803. new Response(body, {
  804. headers: {
  805. "content-length": String(body.length),
  806. "content-type": "application/json",
  807. },
  808. }),
  809. );
  810. const response = await fetch("https://example.test/v1/messages");
  811. await expect(response.text()).resolves.toBe(body);
  812. expect(response.headers.get("content-length")).toBe(String(body.length));
  813. });
  814. it("keeps non-JSON SSE frames readable", async () => {
  815. const fetch = createAnthropicCompatFetch(async () =>
  816. sseResponse(["event: comment\ndata: not-json\n\n"]),
  817. );
  818. const response = await fetch("https://example.test/v1/messages");
  819. await expect(response.text()).resolves.toBe("event: comment\ndata: not-json\n\n");
  820. });
  821. });
  822. async function listenServer(server: Server): Promise<string> {
  823. await new Promise<void>((resolve, reject) => {
  824. server.once("error", reject);
  825. server.listen(0, "127.0.0.1", () => {
  826. server.off("error", reject);
  827. resolve();
  828. });
  829. });
  830. const address = server.address();
  831. if (!address || typeof address === "string") {
  832. throw new Error("Expected TCP server address");
  833. }
  834. return `http://127.0.0.1:${(address as AddressInfo).port}`;
  835. }
  836. async function closeServer(server: Server): Promise<void> {
  837. if (!server.listening) {
  838. return;
  839. }
  840. await new Promise<void>((resolve, reject) => {
  841. server.close((error) => {
  842. if (error) {
  843. reject(error);
  844. return;
  845. }
  846. resolve();
  847. });
  848. });
  849. }
  850. function sseFrame(event: string, data: unknown, separator = "\n\n"): string {
  851. const lineEnding = separator === "\r\n\r\n" ? "\r\n" : separator === "\r\r" ? "\r" : "\n";
  852. return `event: ${event}${lineEnding}data: ${JSON.stringify(data)}${separator}`;
  853. }
  854. function sseResponse(frames: string[]): Response {
  855. const body = frames.join("");
  856. return new Response(body, {
  857. headers: {
  858. "content-length": String(body.length),
  859. "content-type": "text/event-stream; charset=utf-8",
  860. },
  861. });
  862. }
  863. function chunkedSseResponse(chunks: string[]): Response {
  864. const encoder = new TextEncoder();
  865. return new Response(
  866. new ReadableStream<Uint8Array>({
  867. start(controller) {
  868. for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));
  869. controller.close();
  870. },
  871. }),
  872. {
  873. headers: {
  874. "content-type": "text/event-stream; charset=utf-8",
  875. },
  876. },
  877. );
  878. }