model-default-headers-wire.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. createSessionId,
  4. InMemorySessionEventStore,
  5. type SessionStorePort,
  6. } from "@zcode/contracts";
  7. import { AgentRuntime } from "@zcode/core";
  8. import {
  9. createRegistryModelConfig,
  10. createRegistryProviderConfig,
  11. ModelConfig,
  12. ModelOptionSpecsConfig,
  13. ModelPropertiesConfig,
  14. parseProviderConfig,
  15. type RegistryProviderConfig,
  16. } from "@zcode/provider";
  17. import { createRuntimeAiSdkModelExecutionConfig } from "../src/model-config.js";
  18. import { createModelAdapter } from "../src/model-factory.js";
  19. type ApiType = RegistryProviderConfig["api"]["type"];
  20. const CLIENT_VERSION = "3.12.0";
  21. const MODEL_ID = "header-test-model";
  22. const API_TYPES: ApiType[] = ["anthropic-messages", "openai-chat-completions", "openai-responses"];
  23. afterEach(() => vi.unstubAllGlobals());
  24. function createFixture(
  25. options: {
  26. apiType?: ApiType;
  27. baseUrl?: string;
  28. headers?: Record<string, string>;
  29. access?: Record<string, unknown>;
  30. env?: Record<string, string | undefined>;
  31. sourceTitle?: "cli" | "electron";
  32. appVersion?: string;
  33. } = {},
  34. ) {
  35. const apiType = options.apiType ?? "anthropic-messages";
  36. const requests: Request[] = [];
  37. vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
  38. const request = new Request(input, init);
  39. requests.push(request.clone());
  40. const body = (await request.json()) as { stream?: boolean };
  41. return body.stream ? streamResponseFor(apiType) : responseFor(apiType);
  42. });
  43. const provider = createRegistryProviderConfig(
  44. parseProviderConfig({
  45. group: "standard-personal",
  46. access: options.access ?? { type: "api-key", apiKey: "fixture-key" },
  47. api: {
  48. type: apiType,
  49. baseUrl: options.baseUrl ?? "https://provider.example.test/v1",
  50. ...(options.headers ? { headers: options.headers } : {}),
  51. },
  52. }),
  53. );
  54. const model = createRegistryModelConfig(
  55. new ModelConfig({
  56. enabled: true,
  57. properties: new ModelPropertiesConfig({
  58. contextWindow: 200_000,
  59. requiresMfjsToolSchema: false,
  60. inputFormat: {
  61. supportsText: true,
  62. supportsImage: false,
  63. supportsVideo: false,
  64. supportsAudio: false,
  65. supportsPdf: false,
  66. },
  67. outputFormat: { supportsText: true },
  68. supportsToolCall: true,
  69. supportsJsonSchemaOutput: false,
  70. supportsNativeWebSearch: false,
  71. supportsMidConversationSystem: false,
  72. }),
  73. optionSpecs: new ModelOptionSpecsConfig({
  74. reasoningLevel: { values: ["disabled"], map: "{}" },
  75. maxOutputTokens: { max: 2048, map: "{}" },
  76. }),
  77. }),
  78. );
  79. if (!provider.ok || !model.ok) throw new Error("invalid header fixture");
  80. const executionConfig = createRuntimeAiSdkModelExecutionConfig(
  81. options.env ?? { ZCODE_APP_VERSION: CLIENT_VERSION, ZCODE_ENV: "production" },
  82. { sourceTitle: options.sourceTitle ?? "electron", appVersion: options.appVersion },
  83. );
  84. const adapter = createModelAdapter({ executionConfig, env: {} });
  85. const bound = adapter.createModel({
  86. providerId: "header-provider",
  87. modelId: MODEL_ID,
  88. providerConfig: provider.config,
  89. modelConfig: model.config,
  90. options: { reasoningLevel: "disabled", maxOutputTokens: 2048 },
  91. });
  92. return { requests, model: bound };
  93. }
  94. function responseFor(apiType: ApiType) {
  95. if (apiType === "anthropic-messages")
  96. return Response.json({
  97. id: "msg_fixture",
  98. type: "message",
  99. role: "assistant",
  100. model: MODEL_ID,
  101. content: [{ type: "text", text: '{"title":"Header regression"}' }],
  102. stop_reason: "end_turn",
  103. stop_sequence: null,
  104. usage: { input_tokens: 1, output_tokens: 1 },
  105. });
  106. if (apiType === "openai-chat-completions")
  107. return Response.json({
  108. id: "chat_fixture",
  109. object: "chat.completion",
  110. created: 1,
  111. model: MODEL_ID,
  112. choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }],
  113. usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
  114. });
  115. return Response.json({
  116. id: "resp_fixture",
  117. object: "response",
  118. created_at: 1,
  119. status: "completed",
  120. model: MODEL_ID,
  121. output: [
  122. {
  123. id: "msg_fixture",
  124. type: "message",
  125. role: "assistant",
  126. status: "completed",
  127. content: [{ type: "output_text", text: "ok", annotations: [] }],
  128. },
  129. ],
  130. usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
  131. });
  132. }
  133. const requestInput = { messages: [{ role: "user" as const, content: "hello" }] };
  134. async function streamResponseFor(apiType: ApiType) {
  135. const response = await responseFor(apiType).json();
  136. const events =
  137. apiType === "anthropic-messages"
  138. ? [
  139. { type: "message_start", message: { ...response, content: [], stop_reason: null } },
  140. { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  141. { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "ok" } },
  142. { type: "content_block_stop", index: 0 },
  143. {
  144. type: "message_delta",
  145. delta: { stop_reason: "end_turn", stop_sequence: null },
  146. usage: { output_tokens: 1 },
  147. },
  148. { type: "message_stop" },
  149. ]
  150. : apiType === "openai-chat-completions"
  151. ? [
  152. {
  153. id: "chat_fixture",
  154. object: "chat.completion.chunk",
  155. created: 1,
  156. model: MODEL_ID,
  157. choices: [
  158. { index: 0, delta: { role: "assistant", content: "ok" }, finish_reason: "stop" },
  159. ],
  160. usage: response.usage,
  161. },
  162. ]
  163. : [{ type: "response.completed", response }];
  164. return new Response(events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), {
  165. headers: { "content-type": "text/event-stream" },
  166. });
  167. }
  168. describe("模型请求默认 Header:Bootstrap → Adapter → 真实 SDK", () => {
  169. for (const apiType of API_TYPES) {
  170. for (const stream of [false, true]) {
  171. it(`${apiType} / ${stream ? "streamText" : "generateText"} 带来源、版本且不新增设备身份`, async () => {
  172. const { model, requests } = createFixture({ apiType });
  173. if (stream) {
  174. const events = [];
  175. for await (const event of model.streamText(requestInput)) events.push(event);
  176. expect(events.length).toBeGreaterThan(0);
  177. expect(events.some((event) => event.type === "error")).toBe(false);
  178. } else await model.generateText(requestInput);
  179. expect(requests).toHaveLength(1);
  180. const headers = requests[0]!.headers;
  181. expect(headers.get("user-agent")).toContain(`ZCode/${CLIENT_VERSION}`);
  182. expect(headers.get("x-zcode-app-version")).toBe(CLIENT_VERSION);
  183. expect(headers.get("x-title")).toBe("Z Code@electron");
  184. expect(headers.get("http-referer")).toBe("https://zcode.z.ai");
  185. expect(headers.get("x-zcode-agent")).toBe("glm");
  186. expect(headers.get("x-release-channel")).toBe("production");
  187. for (const key of [
  188. "x-client-language",
  189. "x-client-timezone",
  190. "x-platform",
  191. "x-os-category",
  192. "x-os-version",
  193. ])
  194. expect(headers.get(key)).toBeTruthy();
  195. expect(headers.get("authorization")).toBe("Bearer fixture-key");
  196. expect(headers.has("x-device-mid")).toBe(false);
  197. expect(headers.has("x-openrouter-title")).toBe(false);
  198. expect((await requests[0]!.json()).model).toBe(MODEL_ID);
  199. });
  200. }
  201. }
  202. it.each([
  203. ["https://openrouter.ai/api/v1", true],
  204. ["https://API.OPENROUTER.AI/api/v1", true],
  205. ["https://openrouter.ai.example.test/v1", false],
  206. ["http://openrouter.ai/api/v1", false],
  207. ])("按真实 URL 匹配 OpenRouter,不按 Provider 名称:%s", async (baseUrl, matches) => {
  208. const { model, requests } = createFixture({ baseUrl, apiType: "openai-chat-completions" });
  209. await model.generateText(requestInput);
  210. expect(requests[0]!.headers.get("x-openrouter-title")).toBe(matches ? "ZCode" : null);
  211. expect(requests[0]!.headers.get("x-openrouter-categories")).toBe(
  212. matches ? "programming-app" : null,
  213. );
  214. });
  215. it("用户 Header 大小写不敏感地覆盖默认值,不拼接重复值", async () => {
  216. const headers = {
  217. "x-title": "User Title",
  218. "USER-AGENT": "Custom/1",
  219. "x-openrouter-title": "User Router",
  220. "http-referer": "https://user.example.test",
  221. };
  222. const { model, requests } = createFixture({ baseUrl: "https://openrouter.ai/api/v1", headers });
  223. await model.generateText(requestInput);
  224. expect(requests[0]!.headers.get("x-title")).toBe("User Title");
  225. expect(requests[0]!.headers.get("user-agent")).toMatch(/^Custom\/1(?: |$)/);
  226. expect(requests[0]!.headers.get("user-agent")).not.toContain("ZCode/");
  227. expect(requests[0]!.headers.get("x-openrouter-title")).toBe("User Router");
  228. expect(requests[0]!.headers.get("http-referer")).toBe("https://user.example.test");
  229. expect(headers["x-title"]).toBe("User Title");
  230. });
  231. it.each([
  232. { env: {}, sourceTitle: "cli" as const, appVersion: "1.2.3", expected: "1.2.3" },
  233. {
  234. env: { ZCODE_APP_VERSION: "3.12.0" },
  235. sourceTitle: "electron" as const,
  236. appVersion: "0.13.3",
  237. expected: "3.12.0",
  238. },
  239. {
  240. env: { ZCODE_APP_VERSION: "bad\r\nheader" },
  241. sourceTitle: "cli" as const,
  242. appVersion: "1.2.3",
  243. expected: undefined,
  244. },
  245. { env: {}, sourceTitle: "cli" as const, expected: undefined },
  246. ])("保留版本来源及非法/缺失语义:$sourceTitle / $expected", async (options) => {
  247. const { model, requests } = createFixture(options);
  248. await model.generateText(requestInput);
  249. expect(requests[0]!.headers.get("user-agent")).toContain(
  250. `ZCode/${options.expected ?? "unknown"}`,
  251. );
  252. expect(requests[0]!.headers.get("x-zcode-app-version")).toBe(options.expected ?? null);
  253. expect(requests[0]!.headers.get("x-title")).toBe(`Z Code@${options.sourceTitle}`);
  254. });
  255. it("真实 Runtime 标题 sidecar 沿公共工厂携带版本、other 类型和会话追踪", async () => {
  256. const { model, requests } = createFixture();
  257. const sessionId = createSessionId("header-title-session");
  258. const updateSession = vi.fn(async (input) => input);
  259. const store = {
  260. getSession: async () => ({
  261. id: sessionId,
  262. title: "New session",
  263. titleSource: "default",
  264. taskType: "interactive",
  265. }),
  266. updateSession,
  267. } as unknown as SessionStorePort;
  268. const runtime = new AgentRuntime(
  269. sessionId,
  270. {
  271. modelSelection: {
  272. providerId: "header-provider",
  273. modelId: MODEL_ID,
  274. options: { reasoningLevel: "disabled" },
  275. },
  276. titleGeneration: { enabled: true },
  277. },
  278. {
  279. modelFactory: () => model,
  280. eventStore: new InMemorySessionEventStore({ retention: "unbounded" }),
  281. sessionStore: store,
  282. },
  283. );
  284. runtime.maybeStartSessionTitleGenerationFromExternalInput(
  285. "Please investigate missing client headers",
  286. );
  287. await vi.waitFor(() =>
  288. expect(updateSession).toHaveBeenCalledWith(
  289. expect.objectContaining({ title: "Header regression", titleSource: "generated" }),
  290. ),
  291. );
  292. expect(requests).toHaveLength(1);
  293. expect(requests[0]!.headers.get("x-zcode-app-version")).toBe(CLIENT_VERSION);
  294. expect(requests[0]!.headers.get("x-zcode-session-type")).toBe("other");
  295. // 既有请求归因会去掉内部 sess_ 前缀;本次不改变服务端看到的会话身份格式。
  296. expect(requests[0]!.headers.get("x-session-id")).toBe("header-title-session");
  297. expect(requests[0]!.headers.get("x-zcode-trace-id")).toBeTruthy();
  298. expect(JSON.stringify(await requests[0]!.json())).toContain(
  299. "This is a title-generation task, not a conversation.",
  300. );
  301. });
  302. });