model-execution.test.ts 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  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. observeProviderFetch,
  10. } from "../src/model/model-execution.js";
  11. import { TestProviderConfigFixture } from "./test-provider-config.js";
  12. describe("AI SDK Provider execution", () => {
  13. it("旁路观测包装实际网络出口,不替换响应内容", async () => {
  14. const requests: string[] = [];
  15. const server = http.createServer((request, response) => {
  16. request.resume();
  17. response.writeHead(200, { "content-type": "application/json" });
  18. response.end(
  19. JSON.stringify({
  20. id: "m",
  21. type: "message",
  22. role: "assistant",
  23. model: "test",
  24. content: [{ type: "text", text: "observed" }],
  25. stop_reason: "end_turn",
  26. stop_sequence: null,
  27. usage: { input_tokens: 1, output_tokens: 1 },
  28. }),
  29. );
  30. });
  31. try {
  32. const baseURL = await listenServer(server);
  33. const fixture = new TestProviderConfigFixture(
  34. { env: {}, providers: { example: { kind: "anthropic", baseURL, apiKey: "test" } } },
  35. {
  36. observeTransport: (network) => async (url, init) => {
  37. requests.push(String(url));
  38. const response = await network(url, init);
  39. expect(response.bodyUsed).toBe(false);
  40. return response;
  41. },
  42. },
  43. );
  44. const result = await generateText({
  45. model: fixture.resolve("example/test").model,
  46. prompt: "hello",
  47. });
  48. expect(result.text).toBe("observed");
  49. expect(requests).toHaveLength(1);
  50. expect(requests[0]).toContain(baseURL);
  51. } finally {
  52. await new Promise<void>((resolve) => server.close(() => resolve()));
  53. }
  54. });
  55. it("本地 fetch 诊断关联 requestId,只记录响应头边界且不消费正文", async () => {
  56. const info = vi.fn();
  57. const response = new Response("private response");
  58. const network = vi.fn(async () => response);
  59. const fetch = observeProviderFetch(
  60. network,
  61. {
  62. info,
  63. debug: vi.fn(),
  64. warn: vi.fn(),
  65. error: vi.fn(),
  66. child: vi.fn(),
  67. },
  68. "provider",
  69. );
  70. const headers = {
  71. "x-request-id": "attempt-1",
  72. "x-query-id": "command",
  73. "x-zcode-query-source": "main_turn",
  74. authorization: "secret",
  75. };
  76. expect(await fetch("https://example.com/messages", { headers })).toBe(response);
  77. expect(response.bodyUsed).toBe(false);
  78. expect(info.mock.calls.map((call) => call[1]?.event)).toEqual([
  79. "ttft.model.fetch_started",
  80. "ttft.model.response_headers",
  81. ]);
  82. expect(info.mock.calls[1]?.[1]).toMatchObject({
  83. requestId: "attempt-1",
  84. queryId: "command",
  85. statusCode: 200,
  86. });
  87. expect(JSON.stringify(info.mock.calls)).not.toContain("secret");
  88. expect(JSON.stringify(info.mock.calls)).not.toContain("private response");
  89. });
  90. it("adds Authorization alongside x-api-key for Anthropic provider requests", async () => {
  91. const receivedHeaders: http.IncomingHttpHeaders[] = [];
  92. const endpointRoutingPort = {
  93. resolve: vi.fn(async (url: string) => ({ routed: false, url })),
  94. };
  95. const server = http.createServer((request, response) => {
  96. receivedHeaders.push(request.headers);
  97. request.resume();
  98. response.writeHead(200, { "content-type": "application/json" });
  99. response.end(
  100. JSON.stringify({
  101. id: "msg-test",
  102. type: "message",
  103. role: "assistant",
  104. model: "claude-test",
  105. content: [{ type: "text", text: "ok" }],
  106. stop_reason: "end_turn",
  107. stop_sequence: null,
  108. usage: { input_tokens: 1, output_tokens: 1 },
  109. }),
  110. );
  111. });
  112. try {
  113. const baseURL = await listenServer(server);
  114. const registry = new TestProviderConfigFixture({
  115. endpointRoutingPort,
  116. env: {},
  117. providers: {
  118. anthropic: {
  119. kind: "anthropic",
  120. baseURL,
  121. apiKey: "anthropic-key",
  122. },
  123. },
  124. });
  125. const resolved = registry.resolve("anthropic/claude-test");
  126. await expect(generateText({ model: resolved.model, prompt: "hello" })).resolves.toMatchObject(
  127. { text: "ok" },
  128. );
  129. expect(receivedHeaders[0]).toMatchObject({
  130. authorization: "Bearer anthropic-key",
  131. "x-api-key": "anthropic-key",
  132. "anthropic-version": "2023-06-01",
  133. });
  134. expect(endpointRoutingPort.resolve).toHaveBeenCalledWith(
  135. expect.any(String),
  136. expect.not.objectContaining({ apiKey: expect.any(String) }),
  137. );
  138. } finally {
  139. await closeServer(server);
  140. }
  141. });
  142. it("preserves separate Memory selector user messages in the final Anthropic body", async () => {
  143. const requestBodies: Record<string, unknown>[] = [];
  144. const server = http.createServer(async (request, response) => {
  145. let body = "";
  146. for await (const chunk of request) body += chunk.toString();
  147. requestBodies.push(JSON.parse(body) as Record<string, unknown>);
  148. response.writeHead(400, { "content-type": "application/json" });
  149. response.end(
  150. JSON.stringify({
  151. type: "error",
  152. error: { type: "invalid_request_error", message: "request captured" },
  153. }),
  154. );
  155. });
  156. try {
  157. const baseURL = await listenServer(server);
  158. const registry = new TestProviderConfigFixture({
  159. env: {},
  160. providers: {
  161. anthropic: {
  162. kind: "anthropic",
  163. baseURL,
  164. apiKey: "anthropic-key",
  165. },
  166. },
  167. });
  168. const resolved = registry.resolve("anthropic/claude-fable-5-cc", {
  169. maxOutputTokens: 256,
  170. });
  171. const responseSchema = {
  172. additionalProperties: false,
  173. properties: {
  174. selected_memories: { items: { type: "string" }, type: "array" },
  175. selected_knowledge_ids: { items: { type: "string" }, type: "array" },
  176. },
  177. required: ["selected_memories"],
  178. type: "object",
  179. } as const;
  180. await expect(
  181. generateText({
  182. model: resolved.model,
  183. messages: [
  184. { role: "user", content: "Available memories:\n- project.md" },
  185. { role: "user", content: "Select memories relevant to:\nproject policy" },
  186. ],
  187. maxOutputTokens: 256,
  188. maxRetries: 0,
  189. output: Output.object({ schema: jsonSchema(responseSchema) }),
  190. providerOptions: {
  191. anthropic: { structuredOutputMode: "outputFormat" },
  192. },
  193. }),
  194. ).rejects.toThrow("request captured");
  195. expect(requestBodies[0]?.messages).toEqual([
  196. {
  197. role: "user",
  198. content: [{ type: "text", text: "Available memories:\n- project.md" }],
  199. },
  200. {
  201. role: "user",
  202. content: [{ type: "text", text: "Select memories relevant to:\nproject policy" }],
  203. },
  204. ]);
  205. expect(requestBodies[0]?.output_config).toEqual({
  206. format: { type: "json_schema", schema: responseSchema },
  207. });
  208. expect(requestBodies[0]?.max_tokens).toBe(256);
  209. expect(requestBodies[0]).not.toHaveProperty("thinking");
  210. } finally {
  211. await closeServer(server);
  212. }
  213. });
  214. it("preserves retry headers on provider business errors", async () => {
  215. let originalResponse: Response | undefined;
  216. const fetch = createProviderBusinessErrorFetch({
  217. fetch: async () => {
  218. originalResponse = new Response(
  219. JSON.stringify({
  220. error: {
  221. code: "1305",
  222. message: "平台流量限制,请稍后重试",
  223. },
  224. request_id: "20260703111207fd2a863001c64c94",
  225. type: "error",
  226. }),
  227. {
  228. headers: {
  229. "content-type": "application/json",
  230. "retry-after": "41",
  231. "x-should-retry": "true",
  232. },
  233. status: 529,
  234. },
  235. );
  236. return originalResponse;
  237. },
  238. providerId: "zai",
  239. providerKind: "anthropic",
  240. });
  241. await expect(fetch("https://api.z.ai/api/anthropic/v1/messages")).rejects.toMatchObject({
  242. providerCode: "1305",
  243. responseHeaders: {
  244. "retry-after": "41",
  245. "x-should-retry": "true",
  246. },
  247. responseStatus: 529,
  248. });
  249. // 回归 BG26:解析 clone 后抛业务错误时,原始 body 也必须被取消/消费,避免连接池泄漏。
  250. expect(originalResponse?.bodyUsed).toBe(true);
  251. });
  252. it("preserves a stable TLS code when provider fetch rejects with a nested Node TLS error", async () => {
  253. const tlsCause = Object.assign(
  254. new Error(
  255. "self-signed certificate; if the root CA is installed locally, try running Node.js with --use-system-ca",
  256. ),
  257. { code: "DEPTH_ZERO_SELF_SIGNED_CERT" },
  258. );
  259. const fetch = createProviderBusinessErrorFetch({
  260. fetch: async () => {
  261. throw new TypeError("fetch failed", { cause: tlsCause });
  262. },
  263. providerId: "zai",
  264. providerKind: "anthropic",
  265. });
  266. await expect(fetch("https://api.z.ai/api/anthropic/v1/messages")).rejects.toMatchObject({
  267. cause: { cause: tlsCause },
  268. code: "MODEL_TLS_VALIDATION_FAILED",
  269. });
  270. });
  271. it("does not let pending response body cleanup block provider business errors", async () => {
  272. vi.useFakeTimers();
  273. try {
  274. let notifyCleanupStarted!: () => void;
  275. const cleanupStarted = new Promise<void>((resolve) => {
  276. notifyCleanupStarted = resolve;
  277. });
  278. const response = new Response(
  279. JSON.stringify({
  280. error: {
  281. code: "1305",
  282. message: "平台流量限制,请稍后重试",
  283. },
  284. }),
  285. {
  286. headers: { "content-type": "application/json" },
  287. status: 429,
  288. },
  289. );
  290. const nativeClone = response.clone.bind(response);
  291. vi.spyOn(response, "clone").mockImplementation(() => {
  292. const cloned = nativeClone();
  293. // Response.clone() 会替换原 response 的 body 分支,清理必须覆盖 clone 后的原始分支。
  294. vi.spyOn(response, "arrayBuffer").mockImplementation(() => {
  295. notifyCleanupStarted();
  296. return new Promise<never>(() => undefined);
  297. });
  298. return cloned;
  299. });
  300. const fetch = createProviderBusinessErrorFetch({
  301. fetch: async () => response,
  302. providerId: "zai",
  303. providerKind: "anthropic",
  304. });
  305. const request = fetch("https://api.z.ai/api/anthropic/v1/messages");
  306. const rejection = expect(request).rejects.toMatchObject({
  307. message: "平台流量限制,请稍后重试",
  308. name: "ProviderBusinessError",
  309. providerCode: "1305",
  310. responseStatus: 429,
  311. } satisfies Partial<ProviderBusinessError>);
  312. await cleanupStarted;
  313. await vi.advanceTimersByTimeAsync(1_000);
  314. await rejection;
  315. } finally {
  316. vi.useRealTimers();
  317. }
  318. });
  319. it("adds the Anthropic v1 API prefix when consuming explicit base URLs", () => {
  320. const registry = new TestProviderConfigFixture({
  321. env: {},
  322. providers: {
  323. anthropic: {
  324. kind: "anthropic",
  325. baseURL: "https://example.test/anthropic",
  326. apiKey: "secret",
  327. },
  328. anthropicV1: {
  329. kind: "anthropic",
  330. baseURL: "https://example.test/anthropic/v1/",
  331. apiKey: "secret",
  332. },
  333. },
  334. });
  335. const normalized = registry.resolve("anthropic/claude-test").model as unknown as {
  336. config: { baseURL: string };
  337. };
  338. const alreadyVersioned = registry.resolve("anthropicV1/claude-test").model as unknown as {
  339. config: { baseURL: string };
  340. };
  341. expect(normalized.config.baseURL).toBe("https://example.test/anthropic/v1");
  342. expect(alreadyVersioned.config.baseURL).toBe("https://example.test/anthropic/v1");
  343. });
  344. it("turns HTTP 200 success=false provider bodies into business errors", async () => {
  345. const fetch = createProviderBusinessErrorFetch({
  346. fetch: async () =>
  347. new Response(
  348. JSON.stringify({
  349. code: 500,
  350. msg: "404 NOT_FOUND",
  351. success: false,
  352. }),
  353. {
  354. headers: { "content-type": "application/json" },
  355. status: 200,
  356. },
  357. ),
  358. providerId: "zai",
  359. providerKind: "openai-compatible",
  360. });
  361. await expect(fetch("https://example.test/v1/chat/completions")).rejects.toMatchObject({
  362. code: "PROVIDER_BUSINESS_ERROR",
  363. message: "404 NOT_FOUND",
  364. name: "ProviderBusinessError",
  365. providerCode: 500,
  366. providerId: "zai",
  367. responseStatus: 200,
  368. statusCode: 500,
  369. } satisfies Partial<ProviderBusinessError>);
  370. });
  371. it("turns HTTP 200 SSE error events into business errors", async () => {
  372. const fetch = createProviderBusinessErrorFetch({
  373. fetch: async () =>
  374. sseResponse([
  375. sseFrame("error", {
  376. error: {
  377. code: "1311",
  378. message: "当前订阅套餐暂未开放GLM-5V-Turbo权限",
  379. },
  380. request_id: "20260505201906b147bc4aa7cd4e58",
  381. }),
  382. "data: [DONE]\n\n",
  383. ]),
  384. providerId: "zai",
  385. providerKind: "openai-compatible",
  386. });
  387. const response = await fetch("https://example.test/v1/chat/completions?stream=true");
  388. let error: unknown;
  389. try {
  390. await response.text();
  391. } catch (caught) {
  392. error = caught;
  393. }
  394. expect(error).toMatchObject({
  395. code: "PROVIDER_BUSINESS_ERROR",
  396. message: "当前订阅套餐暂未开放GLM-5V-Turbo权限",
  397. name: "ProviderBusinessError",
  398. providerCode: "1311",
  399. providerId: "zai",
  400. providerRequestId: "20260505201906b147bc4aa7cd4e58",
  401. responseStatus: 200,
  402. } satisfies Partial<ProviderBusinessError>);
  403. expect((error as ProviderBusinessError).statusCode).toBeUndefined();
  404. });
  405. it("keeps successful provider SSE responses readable", async () => {
  406. const fetch = createProviderBusinessErrorFetch({
  407. fetch: async () =>
  408. sseResponse([
  409. sseFrame("message", {
  410. choices: [{ delta: { content: "ok" } }],
  411. code: 0,
  412. }),
  413. "data: [DONE]\n\n",
  414. ]),
  415. providerId: "local",
  416. providerKind: "openai-compatible",
  417. });
  418. const response = await fetch("https://example.test/v1/chat/completions?stream=true");
  419. await expect(response.text()).resolves.toContain('"content":"ok"');
  420. });
  421. it("turns non-zero code or error_code provider bodies into business errors", async () => {
  422. const fetch = createProviderBusinessErrorFetch({
  423. fetch: async () =>
  424. new Response(
  425. JSON.stringify({
  426. error_code: "model_not_found",
  427. message: "model does not exist",
  428. }),
  429. {
  430. headers: { "content-type": "application/json" },
  431. status: 200,
  432. },
  433. ),
  434. providerId: "local",
  435. providerKind: "openai-compatible",
  436. });
  437. await expect(fetch("https://example.test/v1/chat/completions")).rejects.toMatchObject({
  438. message: "model does not exist",
  439. providerCode: "model_not_found",
  440. responseStatus: 200,
  441. statusCode: undefined,
  442. } satisfies Partial<ProviderBusinessError>);
  443. });
  444. it("turns HTTP 403 zcode-plan security verification failures into business errors", async () => {
  445. const body = JSON.stringify({ code: 3007, msg: "security verify failed" });
  446. const fetchWithJsonContentType = createProviderBusinessErrorFetch({
  447. fetch: async () =>
  448. new Response(body, {
  449. headers: { "content-type": "application/json" },
  450. status: 403,
  451. }),
  452. providerId: "account:zai-individual-coding-plan",
  453. providerKind: "openai-compatible",
  454. });
  455. const fetchWithoutContentType = createProviderBusinessErrorFetch({
  456. fetch: async () =>
  457. new Response(body, {
  458. headers: { "content-length": String(body.length) },
  459. status: 403,
  460. }),
  461. providerId: "account:zai-individual-coding-plan",
  462. providerKind: "openai-compatible",
  463. });
  464. await expect(
  465. fetchWithJsonContentType("https://example.test/v1/chat/completions"),
  466. ).rejects.toMatchObject({
  467. code: "PROVIDER_BUSINESS_ERROR",
  468. message: "security verify failed",
  469. providerCode: 3007,
  470. responseStatus: 403,
  471. } satisfies Partial<ProviderBusinessError>);
  472. await expect(
  473. fetchWithoutContentType("https://example.test/v1/chat/completions"),
  474. ).rejects.toMatchObject({
  475. code: "PROVIDER_BUSINESS_ERROR",
  476. message: "security verify failed",
  477. providerCode: 3007,
  478. responseStatus: 403,
  479. } satisfies Partial<ProviderBusinessError>);
  480. });
  481. it("keeps successful provider JSON responses readable", async () => {
  482. const body = {
  483. choices: [{ message: { content: "ok" } }],
  484. code: 0,
  485. success: true,
  486. };
  487. const fetch = createProviderBusinessErrorFetch({
  488. fetch: async () =>
  489. new Response(JSON.stringify(body), {
  490. headers: { "content-type": "application/json" },
  491. status: 200,
  492. }),
  493. providerId: "local",
  494. providerKind: "openai-compatible",
  495. });
  496. const response = await fetch("https://example.test/v1/chat/completions");
  497. await expect(response.json()).resolves.toEqual(body);
  498. });
  499. it("routes provider fetch through explicit ZCODE_HTTP_PROXY env", async () => {
  500. const proxyRequests: string[] = [];
  501. const upstream = http.createServer((request, response) => {
  502. response.writeHead(200, { "content-type": "application/json" });
  503. response.end(JSON.stringify({ path: request.url, success: true }));
  504. });
  505. const proxy = http.createServer((clientRequest, clientResponse) => {
  506. proxyRequests.push(clientRequest.url ?? "");
  507. if (!clientRequest.url) {
  508. clientResponse.writeHead(400);
  509. clientResponse.end();
  510. return;
  511. }
  512. const target = new URL(clientRequest.url);
  513. const upstreamRequest = http.request(
  514. {
  515. headers: clientRequest.headers,
  516. hostname: target.hostname,
  517. method: clientRequest.method,
  518. path: `${target.pathname}${target.search}`,
  519. port: target.port,
  520. },
  521. (upstreamResponse) => {
  522. clientResponse.writeHead(upstreamResponse.statusCode ?? 502, upstreamResponse.headers);
  523. upstreamResponse.pipe(clientResponse);
  524. },
  525. );
  526. upstreamRequest.once("error", (error) => {
  527. clientResponse.writeHead(502, { "content-type": "text/plain" });
  528. clientResponse.end(String(error));
  529. });
  530. clientRequest.pipe(upstreamRequest);
  531. });
  532. try {
  533. const upstreamBaseUrl = await listenServer(upstream);
  534. const proxyBaseUrl = await listenServer(proxy);
  535. const fetch = createProviderBusinessErrorFetch({
  536. env: {
  537. ZCODE_HTTP_PROXY: proxyBaseUrl,
  538. },
  539. providerId: "local",
  540. providerKind: "openai-compatible",
  541. });
  542. const response = await fetch(`${upstreamBaseUrl}/v1/chat/completions?stream=true`, {
  543. headers: { "content-type": "application/json" },
  544. method: "POST",
  545. body: JSON.stringify({ model: "glm-5.1" }),
  546. });
  547. await expect(response.json()).resolves.toEqual({
  548. path: "/v1/chat/completions?stream=true",
  549. success: true,
  550. });
  551. expect(proxyRequests).toEqual([`${upstreamBaseUrl}/v1/chat/completions?stream=true`]);
  552. } finally {
  553. await closeServer(proxy);
  554. await closeServer(upstream);
  555. }
  556. });
  557. it("bypasses provider proxy when explicit noProxy matches target host", async () => {
  558. const proxyRequests: string[] = [];
  559. const upstream = http.createServer((_request, response) => {
  560. response.writeHead(200, { "content-type": "application/json" });
  561. response.end(JSON.stringify({ direct: true, success: true }));
  562. });
  563. const proxy = http.createServer((request, response) => {
  564. proxyRequests.push(request.url ?? "");
  565. response.writeHead(502, { "content-type": "application/json" });
  566. response.end(JSON.stringify({ success: false }));
  567. });
  568. try {
  569. const upstreamBaseUrl = await listenServer(upstream);
  570. const proxyBaseUrl = await listenServer(proxy);
  571. const fetch = createProviderBusinessErrorFetch({
  572. env: {
  573. ZCODE_HTTP_PROXY: proxyBaseUrl,
  574. },
  575. noProxy: "127.0.0.1",
  576. providerId: "local",
  577. providerKind: "openai-compatible",
  578. });
  579. const response = await fetch(`${upstreamBaseUrl}/v1/chat/completions`, {
  580. headers: { "content-type": "application/json" },
  581. method: "POST",
  582. body: JSON.stringify({ model: "glm-5.1" }),
  583. });
  584. await expect(response.json()).resolves.toEqual({ direct: true, success: true });
  585. expect(proxyRequests).toEqual([]);
  586. } finally {
  587. await closeServer(proxy);
  588. await closeServer(upstream);
  589. }
  590. });
  591. });
  592. describe("createAnthropicCompatFetch", () => {
  593. it("rewrites provider built-in server tools into provider-executed MCP blocks", async () => {
  594. const fetch = createAnthropicCompatFetch(async () =>
  595. sseResponse([
  596. sseFrame("message_start", {
  597. type: "message_start",
  598. message: {
  599. id: "msg_1",
  600. type: "message",
  601. role: "assistant",
  602. model: "glm-5.1",
  603. content: [],
  604. stop_reason: null,
  605. stop_sequence: null,
  606. usage: { input_tokens: 0, output_tokens: 0 },
  607. },
  608. }),
  609. sseFrame("content_block_start", {
  610. type: "content_block_start",
  611. index: 1,
  612. content_block: { type: "text", text: "" },
  613. }),
  614. sseFrame("content_block_delta", {
  615. type: "content_block_delta",
  616. index: 1,
  617. delta: { type: "text_delta", text: "Output already summarized" },
  618. }),
  619. sseFrame("content_block_stop", { type: "content_block_stop", index: 1 }),
  620. sseFrame("content_block_start", {
  621. type: "content_block_start",
  622. index: 2,
  623. content_block: {
  624. type: "server_tool_use",
  625. id: "call_image",
  626. name: "analyze_image",
  627. input: {},
  628. },
  629. }),
  630. sseFrame("content_block_stop", { type: "content_block_stop", index: 2 }),
  631. sseFrame("content_block_start", {
  632. type: "content_block_start",
  633. index: 4,
  634. content_block: {
  635. type: "tool_result",
  636. tool_use_id: "call_image",
  637. content: '["您尚未登录"]',
  638. },
  639. }),
  640. sseFrame("content_block_stop", { type: "content_block_stop", index: 4 }),
  641. sseFrame("content_block_start", {
  642. type: "content_block_start",
  643. index: 5,
  644. content_block: { type: "text", text: "" },
  645. }),
  646. sseFrame("content_block_delta", {
  647. type: "content_block_delta",
  648. index: 5,
  649. delta: { type: "text_delta", text: "The image says 您尚未登录." },
  650. }),
  651. ]),
  652. );
  653. const response = await fetch("https://example.test/v1/messages");
  654. const text = await response.text();
  655. // AI SDK 只解析固定名单的 server_tool_use,也不接受裸 tool_result;改写成 mcp 块后
  656. // 才能作为 provider 执行的调用和结果进入历史与界面。
  657. expect(text).not.toContain('"type":"server_tool_use"');
  658. expect(text).toContain(
  659. '{"type":"mcp_tool_use","id":"call_image","name":"analyze_image","input":{},"server_name":"zcode-provider-builtin"}',
  660. );
  661. expect(text).toContain(
  662. '{"type":"mcp_tool_result","tool_use_id":"call_image","is_error":false,"content":[{"type":"text","text":"[\\"您尚未登录\\"]"}]}',
  663. );
  664. expect(text).not.toContain('"type":"tool_result"');
  665. expect(text).toContain("Output already summarized");
  666. expect(text).toContain("The image says");
  667. });
  668. it("drops server-rendered markdown copies around provider built-in tools", async () => {
  669. const block = (index: number, text: string) => [
  670. sseFrame("content_block_start", {
  671. type: "content_block_start",
  672. index,
  673. content_block: { type: "text", text: "" },
  674. }),
  675. // 前缀被拆在多个 delta 里,缓冲需要跨 delta 判断。
  676. sseFrame("content_block_delta", {
  677. type: "content_block_delta",
  678. index,
  679. delta: { type: "text_delta", text: text.slice(0, 2) },
  680. }),
  681. sseFrame("ping", { type: "ping" }),
  682. sseFrame("content_block_delta", {
  683. type: "content_block_delta",
  684. index,
  685. delta: { type: "text_delta", text: text.slice(2) },
  686. }),
  687. sseFrame("content_block_stop", { type: "content_block_stop", index }),
  688. ];
  689. const fetch = createAnthropicCompatFetch(async () =>
  690. sseResponse([
  691. ...block(0, "先看图。"),
  692. ...block(1, "**🌐 Built-in Tool: analyze_image** *Executing on server...*"),
  693. sseFrame("content_block_start", {
  694. type: "content_block_start",
  695. index: 2,
  696. content_block: {
  697. type: "server_tool_use",
  698. id: "call_x",
  699. name: "analyze_image",
  700. input: {},
  701. },
  702. }),
  703. sseFrame("content_block_stop", { type: "content_block_stop", index: 2 }),
  704. ...block(3, "**Output:** rendered result"),
  705. sseFrame("content_block_start", {
  706. type: "content_block_start",
  707. index: 4,
  708. content_block: { type: "tool_result", tool_use_id: "call_x", content: "result" },
  709. }),
  710. sseFrame("content_block_stop", { type: "content_block_stop", index: 4 }),
  711. ...block(5, "**结论**:看完了。"),
  712. // 没有配对调用的裸 tool_result 仍按旧规则丢弃。
  713. sseFrame("content_block_start", {
  714. type: "content_block_start",
  715. index: 6,
  716. content_block: { type: "tool_result", tool_use_id: "call_unknown", content: "orphan" },
  717. }),
  718. sseFrame("content_block_stop", { type: "content_block_stop", index: 6 }),
  719. ]),
  720. );
  721. const text = await (await fetch("https://example.test/v1/messages")).text();
  722. expect(text).toContain('"text":"先看"');
  723. expect(text).not.toContain("Built-in Tool");
  724. expect(text).not.toContain("rendered result");
  725. expect(text).not.toContain('"index":1');
  726. expect(text).not.toContain('"index":3');
  727. // 结果之后的加粗正文是模型自己的回答,必须保留。
  728. expect(text).toContain("看完了");
  729. expect(text).toContain('"type":"mcp_tool_result"');
  730. expect(text).not.toContain("orphan");
  731. });
  732. it("keeps bold text that is not followed by a provider built-in tool", async () => {
  733. const fetch = createAnthropicCompatFetch(async () =>
  734. sseResponse([
  735. sseFrame("content_block_start", {
  736. type: "content_block_start",
  737. index: 0,
  738. content_block: { type: "text", text: "" },
  739. }),
  740. sseFrame("content_block_delta", {
  741. type: "content_block_delta",
  742. index: 0,
  743. delta: { type: "text_delta", text: "**🌐 not a tool header**" },
  744. }),
  745. sseFrame("content_block_stop", { type: "content_block_stop", index: 0 }),
  746. sseFrame("message_delta", {
  747. type: "message_delta",
  748. delta: { stop_reason: "end_turn", stop_sequence: null },
  749. usage: { output_tokens: 1 },
  750. }),
  751. ]),
  752. );
  753. const text = await (await fetch("https://example.test/v1/messages")).text();
  754. expect(text).toContain("not a tool header");
  755. expect(text.indexOf("not a tool header")).toBeLessThan(text.indexOf("message_delta"));
  756. });
  757. it("rewrites provider built-in tools in non-streaming JSON responses", async () => {
  758. const fetch = createAnthropicCompatFetch(async () =>
  759. Response.json({
  760. id: "msg_json",
  761. type: "message",
  762. role: "assistant",
  763. model: "glm-5.3",
  764. content: [
  765. { type: "text", text: "先看图。" },
  766. { type: "text", text: "**🌐 Built-in Tool: analyze_image**" },
  767. { type: "server_tool_use", id: "call_j", name: "analyze_image", input: { prompt: "p" } },
  768. { type: "text", text: "**Output:** rendered" },
  769. { type: "tool_result", tool_use_id: "call_j", content: "result" },
  770. { type: "text", text: "答案" },
  771. ],
  772. stop_reason: "end_turn",
  773. stop_sequence: null,
  774. usage: { input_tokens: 1, output_tokens: 1 },
  775. }),
  776. );
  777. const body = await (await fetch("https://example.test/v1/messages")).json();
  778. expect(body.content).toEqual([
  779. { type: "text", text: "先看图。" },
  780. {
  781. type: "mcp_tool_use",
  782. id: "call_j",
  783. name: "analyze_image",
  784. input: { prompt: "p" },
  785. server_name: "zcode-provider-builtin",
  786. },
  787. {
  788. type: "mcp_tool_result",
  789. tool_use_id: "call_j",
  790. is_error: false,
  791. content: [{ type: "text", text: "result" }],
  792. },
  793. { type: "text", text: "答案" },
  794. ]);
  795. });
  796. it("drops a bare tool_result that no server tool call paired", async () => {
  797. const fetch = createAnthropicCompatFetch(async () =>
  798. sseResponse([
  799. sseFrame("content_block_start", {
  800. type: "content_block_start",
  801. index: 2,
  802. content_block: { type: "tool_result", tool_use_id: "call_orphan", content: "orphan" },
  803. }),
  804. sseFrame("content_block_delta", {
  805. type: "content_block_delta",
  806. index: 2,
  807. delta: { type: "text_delta", text: "orphan delta" },
  808. }),
  809. sseFrame("content_block_stop", { type: "content_block_stop", index: 2 }),
  810. sseFrame("content_block_start", {
  811. type: "content_block_start",
  812. index: 3,
  813. content_block: { type: "text", text: "" },
  814. }),
  815. sseFrame("content_block_delta", {
  816. type: "content_block_delta",
  817. index: 3,
  818. delta: { type: "text_delta", text: "answer" },
  819. }),
  820. sseFrame("content_block_stop", { type: "content_block_stop", index: 3 }),
  821. ]),
  822. );
  823. const response = await fetch("https://example.test/v1/messages");
  824. const text = await response.text();
  825. // 没有对应服务端调用的裸 tool_result 仍是非标块:start、delta、stop 一并丢弃,不改写成 MCP 结果。
  826. expect(text).not.toContain('"type":"tool_result"');
  827. expect(text).not.toContain("mcp_tool_result");
  828. expect(text).not.toContain("orphan");
  829. expect(text).not.toContain('"index":2');
  830. expect(text).toContain("answer");
  831. });
  832. it("keeps typed Anthropic tool result blocks", async () => {
  833. const fetch = createAnthropicCompatFetch(async () =>
  834. sseResponse([
  835. sseFrame("content_block_start", {
  836. type: "content_block_start",
  837. index: 3,
  838. content_block: {
  839. type: "web_search_tool_result",
  840. tool_use_id: "srv_1",
  841. content: [
  842. {
  843. type: "web_search_result",
  844. url: "https://example.test",
  845. title: "Example",
  846. encrypted_content: "opaque",
  847. },
  848. ],
  849. },
  850. }),
  851. sseFrame("content_block_stop", { type: "content_block_stop", index: 3 }),
  852. ]),
  853. );
  854. const response = await fetch("https://example.test/v1/messages");
  855. const text = await response.text();
  856. expect(text).toContain('"type":"web_search_tool_result"');
  857. expect(text).toContain('"index":3');
  858. });
  859. it("synthesizes a signature delta for thinking signatures delivered at block start", async () => {
  860. const start = sseFrame("content_block_start", {
  861. type: "content_block_start",
  862. index: 0,
  863. content_block: { type: "thinking", thinking: "", signature: "sig_start" },
  864. });
  865. const thinking = sseFrame("content_block_delta", {
  866. type: "content_block_delta",
  867. index: 0,
  868. delta: { type: "thinking_delta", thinking: "internal trace" },
  869. });
  870. const stop = sseFrame("content_block_stop", { type: "content_block_stop", index: 0 });
  871. const fetch = createAnthropicCompatFetch(async () => sseResponse([start, thinking, stop]));
  872. const response = await fetch("https://example.test/v1/messages");
  873. await expect(response.text()).resolves.toBe(
  874. [
  875. start,
  876. thinking,
  877. sseFrame("content_block_delta", {
  878. type: "content_block_delta",
  879. index: 0,
  880. delta: { type: "signature_delta", signature: "sig_start" },
  881. }),
  882. stop,
  883. ].join(""),
  884. );
  885. });
  886. it("does not duplicate a native signature delta", async () => {
  887. const frames = [
  888. sseFrame("content_block_start", {
  889. type: "content_block_start",
  890. index: 0,
  891. content_block: { type: "thinking", thinking: "", signature: "sig_start" },
  892. }),
  893. sseFrame("content_block_delta", {
  894. type: "content_block_delta",
  895. index: 0,
  896. delta: { type: "signature_delta", signature: "sig_native" },
  897. }),
  898. sseFrame("content_block_stop", { type: "content_block_stop", index: 0 }),
  899. ];
  900. const fetch = createAnthropicCompatFetch(async () => sseResponse(frames));
  901. const response = await fetch("https://example.test/v1/messages");
  902. await expect(response.text()).resolves.toBe(frames.join(""));
  903. });
  904. it("synthesizes start-delivered signatures across fragmented CRLF frames", async () => {
  905. const separator = "\r\n\r\n";
  906. const start = sseFrame(
  907. "content_block_start",
  908. {
  909. type: "content_block_start",
  910. index: 0,
  911. content_block: { type: "thinking", thinking: "", signature: "sig_crlf" },
  912. },
  913. separator,
  914. );
  915. const stop = sseFrame(
  916. "content_block_stop",
  917. { type: "content_block_stop", index: 0 },
  918. separator,
  919. );
  920. const wire = `${start}${stop}`;
  921. const separatorSplit = start.indexOf(separator) + separator.length - 1;
  922. const fetch = createAnthropicCompatFetch(async () =>
  923. chunkedSseResponse([
  924. wire.slice(0, separatorSplit),
  925. wire.slice(separatorSplit, start.length + 7),
  926. wire.slice(start.length + 7),
  927. ]),
  928. );
  929. const response = await fetch("https://example.test/v1/messages");
  930. await expect(response.text()).resolves.toBe(
  931. [
  932. start,
  933. sseFrame(
  934. "content_block_delta",
  935. {
  936. type: "content_block_delta",
  937. index: 0,
  938. delta: { type: "signature_delta", signature: "sig_crlf" },
  939. },
  940. separator,
  941. ),
  942. stop,
  943. ].join(""),
  944. );
  945. });
  946. it("flushes a final stop frame without a trailing SSE separator", async () => {
  947. const start = sseFrame("content_block_start", {
  948. type: "content_block_start",
  949. index: 0,
  950. content_block: { type: "thinking", thinking: "", signature: "sig_final" },
  951. });
  952. const stop = `event: content_block_stop\ndata: ${JSON.stringify({
  953. type: "content_block_stop",
  954. index: 0,
  955. })}`;
  956. const fetch = createAnthropicCompatFetch(async () =>
  957. chunkedSseResponse([start, stop.slice(0, 11), stop.slice(11)]),
  958. );
  959. const response = await fetch("https://example.test/v1/messages");
  960. await expect(response.text()).resolves.toBe(
  961. [
  962. start,
  963. sseFrame("content_block_delta", {
  964. type: "content_block_delta",
  965. index: 0,
  966. delta: { type: "signature_delta", signature: "sig_final" },
  967. }),
  968. stop,
  969. ].join(""),
  970. );
  971. });
  972. it("drops unsigned thinking blocks from JSON message responses", async () => {
  973. const body = JSON.stringify({
  974. id: "msg_1",
  975. type: "message",
  976. role: "assistant",
  977. model: "glm-0606",
  978. content: [
  979. { type: "thinking", thinking: "internal trace" },
  980. { type: "text", text: "Visible answer" },
  981. ],
  982. stop_reason: "end_turn",
  983. stop_sequence: null,
  984. usage: { input_tokens: 1, output_tokens: 2 },
  985. });
  986. const fetch = createAnthropicCompatFetch(
  987. async () =>
  988. new Response(body, {
  989. headers: {
  990. "content-length": String(body.length),
  991. "content-type": "application/json",
  992. },
  993. }),
  994. );
  995. const response = await fetch("https://example.test/v1/messages");
  996. const parsed = (await response.json()) as {
  997. content: Array<{ type: string; text?: string; thinking?: string }>;
  998. };
  999. expect(parsed.content).toEqual([{ type: "text", text: "Visible answer" }]);
  1000. expect(response.headers.get("content-length")).toBeNull();
  1001. });
  1002. it("keeps signed thinking blocks in JSON message responses", async () => {
  1003. const body = JSON.stringify({
  1004. content: [
  1005. { type: "thinking", thinking: "trusted trace", signature: "sig_1" },
  1006. { type: "text", text: "Visible answer" },
  1007. ],
  1008. });
  1009. const fetch = createAnthropicCompatFetch(
  1010. async () =>
  1011. new Response(body, {
  1012. headers: {
  1013. "content-length": String(body.length),
  1014. "content-type": "application/json",
  1015. },
  1016. }),
  1017. );
  1018. const response = await fetch("https://example.test/v1/messages");
  1019. await expect(response.text()).resolves.toBe(body);
  1020. expect(response.headers.get("content-length")).toBe(String(body.length));
  1021. });
  1022. it.each([
  1023. ["an empty string signature", { signature: "" }],
  1024. ["redacted data", { redactedData: "opaque-redacted-thinking" }],
  1025. ])("keeps JSON thinking blocks carrying %s", async (_label, metadata) => {
  1026. const body = JSON.stringify({
  1027. content: [
  1028. { type: "thinking", thinking: "trusted trace", ...metadata },
  1029. { type: "text", text: "Visible answer" },
  1030. ],
  1031. });
  1032. const fetch = createAnthropicCompatFetch(
  1033. async () =>
  1034. new Response(body, {
  1035. headers: {
  1036. "content-length": String(body.length),
  1037. "content-type": "application/json",
  1038. },
  1039. }),
  1040. );
  1041. const response = await fetch("https://example.test/v1/messages");
  1042. await expect(response.text()).resolves.toBe(body);
  1043. expect(response.headers.get("content-length")).toBe(String(body.length));
  1044. });
  1045. it("does not rewrite unrelated JSON responses", async () => {
  1046. const body = JSON.stringify({
  1047. type: "content_block_start",
  1048. content_block: { type: "tool_result" },
  1049. });
  1050. const fetch = createAnthropicCompatFetch(
  1051. async () =>
  1052. new Response(body, {
  1053. headers: {
  1054. "content-length": String(body.length),
  1055. "content-type": "application/json",
  1056. },
  1057. }),
  1058. );
  1059. const response = await fetch("https://example.test/v1/messages");
  1060. await expect(response.text()).resolves.toBe(body);
  1061. expect(response.headers.get("content-length")).toBe(String(body.length));
  1062. });
  1063. it("keeps non-JSON SSE frames readable", async () => {
  1064. const fetch = createAnthropicCompatFetch(async () =>
  1065. sseResponse(["event: comment\ndata: not-json\n\n"]),
  1066. );
  1067. const response = await fetch("https://example.test/v1/messages");
  1068. await expect(response.text()).resolves.toBe("event: comment\ndata: not-json\n\n");
  1069. });
  1070. });
  1071. async function listenServer(server: Server): Promise<string> {
  1072. await new Promise<void>((resolve, reject) => {
  1073. server.once("error", reject);
  1074. server.listen(0, "127.0.0.1", () => {
  1075. server.off("error", reject);
  1076. resolve();
  1077. });
  1078. });
  1079. const address = server.address();
  1080. if (!address || typeof address === "string") {
  1081. throw new Error("Expected TCP server address");
  1082. }
  1083. return `http://127.0.0.1:${(address as AddressInfo).port}`;
  1084. }
  1085. async function closeServer(server: Server): Promise<void> {
  1086. if (!server.listening) {
  1087. return;
  1088. }
  1089. await new Promise<void>((resolve, reject) => {
  1090. server.close((error) => {
  1091. if (error) {
  1092. reject(error);
  1093. return;
  1094. }
  1095. resolve();
  1096. });
  1097. });
  1098. }
  1099. function sseFrame(event: string, data: unknown, separator = "\n\n"): string {
  1100. const lineEnding = separator === "\r\n\r\n" ? "\r\n" : separator === "\r\r" ? "\r" : "\n";
  1101. return `event: ${event}${lineEnding}data: ${JSON.stringify(data)}${separator}`;
  1102. }
  1103. function sseResponse(frames: string[]): Response {
  1104. const body = frames.join("");
  1105. return new Response(body, {
  1106. headers: {
  1107. "content-length": String(body.length),
  1108. "content-type": "text/event-stream; charset=utf-8",
  1109. },
  1110. });
  1111. }
  1112. function chunkedSseResponse(chunks: string[]): Response {
  1113. const encoder = new TextEncoder();
  1114. return new Response(
  1115. new ReadableStream<Uint8Array>({
  1116. start(controller) {
  1117. for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));
  1118. controller.close();
  1119. },
  1120. }),
  1121. {
  1122. headers: {
  1123. "content-type": "text/event-stream; charset=utf-8",
  1124. },
  1125. },
  1126. );
  1127. }