opencode-go-wire.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import { readFile } from "node:fs/promises";
  2. import { generateText } from "ai";
  3. import { beforeAll, describe, expect, it } from "vitest";
  4. import {
  5. createRegistryProviderConfig,
  6. createRegistryModelConfig,
  7. parseProviderConfig,
  8. parseZCodeBuiltinModelConfigRules,
  9. type ModelConfigRules,
  10. } from "@zcode/provider";
  11. import { AiSdkModelExecution } from "../src/model/model-execution.js";
  12. import { createGenerateTextOptions } from "../src/model/runner-options.js";
  13. import { createStatusContext } from "../src/model/runner-status.js";
  14. import type { AiSdkModelTextRequest } from "../src/model/runner-runtime.js";
  15. let rules: ModelConfigRules;
  16. beforeAll(async () => {
  17. const release = JSON.parse(
  18. await readFile(
  19. new URL("../../../../../config/provider/zcode-builtin.json", import.meta.url),
  20. "utf8",
  21. ),
  22. );
  23. rules = parseZCodeBuiltinModelConfigRules(release.config.modelConfigRules);
  24. });
  25. const baseUrl = "https://opencode.ai/zen/go/v1";
  26. // 每种 Go 映射走正式 SDK / transport;只截获假 Key 请求,不消耗用户额度。
  27. describe("Todo149 OpenCode Go 正式 SDK 请求", () => {
  28. it.each([
  29. ["glm-5.3", "openai-chat-completions", ["low", "high", "max"], "effort"],
  30. ["glm-5.3-flash", "openai-chat-completions", ["low", "high", "max"], "effort"],
  31. ["deepseek-v4-pro", "openai-chat-completions", ["high", "max"], "effort"],
  32. ["hy3", "openai-chat-completions", ["none", "low", "high"], "effort"],
  33. ["kimi-k2.7-code", "openai-chat-completions", ["enabled"], "fixed"],
  34. ["mimo-v2.5", "openai-chat-completions", ["enabled"], "fixed"],
  35. ["minimax-m3", "anthropic-messages", ["disabled", "enabled"], "adaptive"],
  36. ["minimax-m2.7", "anthropic-messages", ["enabled"], "fixed"],
  37. ["qwen3.7-max", "anthropic-messages", ["disabled", "enabled"], "toggle"],
  38. ["qwen3.8-max", "anthropic-messages", ["low", "medium", "xhigh"], "qwen-effort"],
  39. [
  40. "gpt-5.6-luna",
  41. "openai-responses",
  42. ["none", "low", "medium", "high", "xhigh", "max"],
  43. "responses",
  44. ],
  45. ["grok-4.6", "openai-responses", ["low", "medium", "high", "xhigh"], "responses"],
  46. ] as const)("%s/%s 不混发其他协议字段", async (modelId, apiType, levels, mode) => {
  47. const config = rules.resolve({ providerId: "go", modelId, apiType, baseUrl });
  48. const modelConfig = createRegistryModelConfig(config);
  49. const provider = createRegistryProviderConfig(
  50. parseProviderConfig({
  51. group: "standard-personal",
  52. access: { type: "api-key", apiKey: "E2E_GO_FAKE_KEY" },
  53. api: { type: apiType, baseUrl },
  54. }),
  55. );
  56. if (!provider.ok || !modelConfig.ok) throw new Error("Invalid Go fixture");
  57. const requests: Request[] = [];
  58. const execution = new AiSdkModelExecution(
  59. {
  60. env: {},
  61. defaultHeaders: { "User-Agent": "ZCode/3.12.1", "X-ZCode-App-Version": "3.12.1" },
  62. },
  63. {
  64. transport: async (input, init) => {
  65. requests.push(new Request(input, init));
  66. return Response.json(
  67. { type: "error", error: { message: "E2E_GO_CAPTURED", type: "invalid_request_error" } },
  68. { status: 400 },
  69. );
  70. },
  71. },
  72. );
  73. const bound = execution.bindModel({
  74. providerId: "go",
  75. modelId,
  76. providerConfig: provider.config,
  77. supportsJsonSchemaOutput: false,
  78. optionSpecs: {
  79. reasoningLevel: { map: config.optionSpecs!.reasoningLevel!.map! },
  80. maxOutputTokens: { map: config.optionSpecs!.maxOutputTokens!.map! },
  81. },
  82. });
  83. for (const { reasoningLevel, maxOutputTokens } of levels.flatMap((reasoningLevel) =>
  84. [1, 4096].map((maxOutputTokens) => ({ reasoningLevel, maxOutputTokens })),
  85. )) {
  86. const resolved = bound.resolveRequest({ options: { reasoningLevel, maxOutputTokens } });
  87. const ready = { ...resolved, properties: modelConfig.config.properties };
  88. const requestInput: AiSdkModelTextRequest = {
  89. messages: [{ role: "user", content: "E2E_GO_CAPTURE" }],
  90. metadata: { sessionId: "go-wire-session", requestId: "go-wire-request" },
  91. };
  92. await expect(
  93. generateText(
  94. createGenerateTextOptions({
  95. includeModelIO: false,
  96. resolved: ready,
  97. request: requestInput,
  98. statusContext: createStatusContext({
  99. maxAttempts: 1,
  100. request: requestInput,
  101. resolved: ready,
  102. transport: "http",
  103. }),
  104. }),
  105. ),
  106. ).rejects.toThrow("E2E_GO_CAPTURED");
  107. const request = requests.at(-1)!;
  108. const body = await request.json();
  109. expect(request.url).toBe(
  110. `${baseUrl}/${apiType === "anthropic-messages" ? "messages" : apiType === "openai-responses" ? "responses" : "chat/completions"}`,
  111. );
  112. expect(request.headers.get("authorization")).toBe("Bearer E2E_GO_FAKE_KEY");
  113. expect(request.headers.get("user-agent")).toContain("ZCode/3.12.1");
  114. expect(request.headers.get("x-zcode-app-version")).toBe("3.12.1");
  115. expect(request.headers.get("x-session-id")).toBe("go-wire-session");
  116. expect(request.headers.get("x-opencode-session")).toBe("go-wire-session");
  117. expect(body.model).toBe(modelId);
  118. expect(body.enable_thinking).toBeUndefined();
  119. expect(body.max_completion_tokens).toBeUndefined();
  120. expect(body[mode === "responses" ? "max_output_tokens" : "max_tokens"]).toBe(maxOutputTokens);
  121. const reasoning = Object.fromEntries(
  122. ["reasoning_effort", "reasoning", "thinking", "output_config"]
  123. .filter((k) => k in body)
  124. .map((k) => [k, body[k]]),
  125. );
  126. expect(reasoning).toEqual(
  127. mode === "effort"
  128. ? { reasoning_effort: reasoningLevel }
  129. : mode === "responses"
  130. ? { reasoning: { effort: reasoningLevel } }
  131. : mode === "fixed"
  132. ? {}
  133. : mode === "qwen-effort"
  134. ? { thinking: { type: "enabled" }, output_config: { effort: reasoningLevel } }
  135. : {
  136. thinking: {
  137. type:
  138. reasoningLevel === "disabled"
  139. ? "disabled"
  140. : mode === "adaptive"
  141. ? "adaptive"
  142. : "enabled",
  143. },
  144. },
  145. );
  146. }
  147. expect(requests).toHaveLength(levels.length * 2);
  148. });
  149. it.each([
  150. ["glm-5.3-flash", "openai-chat-completions", "low"],
  151. ["minimax-m3", "anthropic-messages", "enabled"],
  152. ["gpt-5.6-luna", "openai-responses", "low"],
  153. ] as const)(
  154. "%s 正式 SDK 可解析正文、工具调用与用量",
  155. async (modelId, apiType, reasoningLevel) => {
  156. const modelConfig = createRegistryModelConfig(
  157. rules.resolve({ providerId: "go", modelId, apiType, baseUrl }),
  158. );
  159. const provider = createRegistryProviderConfig(
  160. parseProviderConfig({
  161. group: "standard-personal",
  162. access: { type: "api-key", apiKey: "E2E_GO_FAKE_KEY" },
  163. api: { type: apiType, baseUrl },
  164. }),
  165. );
  166. if (!modelConfig.ok || !provider.ok) throw new Error("Invalid Go fixture");
  167. let body: Record<string, unknown> = {};
  168. const execution = new AiSdkModelExecution(
  169. { env: {} },
  170. {
  171. transport: async (input, init) => {
  172. body = await new Request(input, init).json();
  173. // synthetic:各协议按官方结构返回相同的正文、工具意图与非零用量,不调用真实工具。
  174. if (apiType === "anthropic-messages")
  175. return Response.json({
  176. id: "msg_go",
  177. type: "message",
  178. role: "assistant",
  179. model: modelId,
  180. content: [
  181. { type: "text", text: "ok" },
  182. { type: "tool_use", id: "call_go", name: "Read", input: { path: "README.md" } },
  183. ],
  184. stop_reason: "tool_use",
  185. stop_sequence: null,
  186. usage: { input_tokens: 7, output_tokens: 3 },
  187. });
  188. if (apiType === "openai-chat-completions")
  189. return Response.json({
  190. id: "chat_go",
  191. object: "chat.completion",
  192. created: 1,
  193. model: modelId,
  194. choices: [
  195. {
  196. index: 0,
  197. message: {
  198. role: "assistant",
  199. content: "ok",
  200. tool_calls: [
  201. {
  202. id: "call_go",
  203. type: "function",
  204. function: { name: "Read", arguments: '{"path":"README.md"}' },
  205. },
  206. ],
  207. },
  208. finish_reason: "tool_calls",
  209. },
  210. ],
  211. usage: { prompt_tokens: 7, completion_tokens: 3, total_tokens: 10 },
  212. });
  213. return Response.json({
  214. id: "resp_go",
  215. object: "response",
  216. created_at: 1,
  217. status: "completed",
  218. model: modelId,
  219. output: [
  220. {
  221. id: "msg_go",
  222. type: "message",
  223. role: "assistant",
  224. status: "completed",
  225. content: [{ type: "output_text", text: "ok", annotations: [] }],
  226. },
  227. {
  228. id: "fc_go",
  229. type: "function_call",
  230. call_id: "call_go",
  231. name: "Read",
  232. arguments: '{"path":"README.md"}',
  233. status: "completed",
  234. },
  235. ],
  236. usage: { input_tokens: 7, output_tokens: 3, total_tokens: 10 },
  237. });
  238. },
  239. },
  240. );
  241. const model = execution.bindModel({
  242. providerId: "go",
  243. modelId,
  244. providerConfig: provider.config,
  245. supportsJsonSchemaOutput: false,
  246. optionSpecs: modelConfig.config.optionSpecs,
  247. });
  248. const resolved = {
  249. ...model.resolveRequest({ options: { reasoningLevel, maxOutputTokens: 4096 } }),
  250. properties: modelConfig.config.properties,
  251. };
  252. const request: AiSdkModelTextRequest = {
  253. messages: [{ role: "user", content: "E2E_GO_TOOL" }],
  254. tools: [
  255. {
  256. name: "Read",
  257. inputSchema: {
  258. type: "object",
  259. properties: { path: { type: "string" } },
  260. required: ["path"],
  261. additionalProperties: false,
  262. },
  263. },
  264. ],
  265. };
  266. const result = await generateText(
  267. createGenerateTextOptions({
  268. includeModelIO: false,
  269. request,
  270. resolved,
  271. statusContext: createStatusContext({
  272. maxAttempts: 1,
  273. request,
  274. resolved,
  275. transport: "http",
  276. }),
  277. }),
  278. );
  279. expect(body.model).toBe(modelId);
  280. expect(body.tools).toHaveLength(1);
  281. expect(result.text).toBe("ok");
  282. expect(result.toolCalls).toMatchObject([
  283. { toolCallId: "call_go", toolName: "Read", input: { path: "README.md" } },
  284. ]);
  285. expect(result.usage).toMatchObject({ inputTokens: 7, outputTokens: 3 });
  286. },
  287. );
  288. });