legacy-cli-output-token-runtime.test.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import { createServer } from "node:http";
  2. import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. import { describe, expect, it } from "vitest";
  7. import { createSharedZCodeCredentialStore } from "@zcode/adapters/auth";
  8. import { AiSdkModelAdapter } from "@zcode/adapters/model";
  9. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  10. import { createZCodeApp } from "../src/app/create-app.js";
  11. import { startProcessProviderRegistryRuntime } from "../src/app/process-provider-registry-runtime.js";
  12. const OUTPUT_BUDGET = 24_000;
  13. const builtinPath = fileURLToPath(
  14. new URL("../../../../../config/provider/zcode-builtin.json", import.meta.url),
  15. );
  16. describe("CLI 旧输出上限从首次导入到请求", () => {
  17. it.each([
  18. { kind: "anthropic", field: "max_tokens", legacy: { maxOutputTokens: OUTPUT_BUDGET } },
  19. {
  20. kind: "openai-compatible",
  21. field: "max_completion_tokens",
  22. legacy: { options: { max_tokens: OUTPUT_BUDGET } },
  23. },
  24. { kind: "openai", field: "max_output_tokens", legacy: { limit: { output: OUTPUT_BUDGET } } },
  25. ])(
  26. "$kind 保留预算、继承 map,重启不重读旧配置",
  27. async ({ kind, field, legacy }) => {
  28. const directory = await mkdtemp(join(tmpdir(), "cli-output-migration-"));
  29. const requests: Record<string, unknown>[] = [];
  30. const server = createServer(async (request, response) => {
  31. const chunks: Buffer[] = [];
  32. for await (const chunk of request) chunks.push(Buffer.from(chunk));
  33. requests.push(JSON.parse(Buffer.concat(chunks).toString("utf8")));
  34. // 本地服务只捕获真实 SDK wire;400 终止本轮,避免重试或调用真实模型。
  35. response.writeHead(400, { "content-type": "application/json" });
  36. response.end(
  37. JSON.stringify({ error: { type: "invalid_request_error", message: "fixture captured" } }),
  38. );
  39. });
  40. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  41. const address = server.address();
  42. if (!address || typeof address === "string") throw new Error("missing local fixture address");
  43. const legacyPath = join(directory, "config.json");
  44. const personalPath = join(directory, "provider_config.json");
  45. const env = {
  46. ZCODE_DATA_BASE_DIR: directory,
  47. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: builtinPath,
  48. ZCODE_PERSONAL_PROVIDER_CONFIG_FILE: personalPath,
  49. };
  50. const options = {
  51. standalone: {
  52. legacyCliUserConfigFilePath: legacyPath,
  53. credentialStore: createSharedZCodeCredentialStore({
  54. baseDir: join(directory, "credentials"),
  55. env,
  56. }),
  57. },
  58. };
  59. const input = {
  60. model: "evaluation/eval-model",
  61. provider: {
  62. evaluation: {
  63. kind,
  64. options: { apiKey: "fixture-key", baseURL: `http://127.0.0.1:${address.port}/v1` },
  65. models: { "eval-model": legacy },
  66. },
  67. },
  68. };
  69. const original = JSON.stringify(input);
  70. try {
  71. await writeFile(legacyPath, original);
  72. const processRuntime = await startProcessProviderRegistryRuntime(env, options);
  73. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  74. try {
  75. const personal = await processRuntime.runtime.personalRepository.read();
  76. expect(personal.models.getExact("evaluation", "eval-model")?.toJSON()).toEqual({
  77. optionSpecs: { maxOutputTokens: { max: OUTPUT_BUDGET } },
  78. });
  79. const config = processRuntime.runtime.registryService.getModel(
  80. "evaluation",
  81. "eval-model",
  82. )?.config;
  83. expect(config?.optionSpecs.maxOutputTokens.max).toBe(OUTPUT_BUDGET);
  84. expect(config?.optionSpecs.maxOutputTokens.map).toContain(field);
  85. expect(await readFile(legacyPath, "utf8")).toBe(original);
  86. const app = await createZCodeApp({
  87. env,
  88. providerRegistry: processRuntime.runtime.registryService,
  89. configuredDefaultModelSelection: processRuntime.configuredDefaultModelSelection,
  90. modelAdapter: new AiSdkModelAdapter({ env: {}, network: { noProxy: "*" } }),
  91. sessionStore: store,
  92. skipUserConfig: true,
  93. runtimeConfig: { mcp: { enabled: false }, workingDirectory: directory },
  94. });
  95. try {
  96. await expect(app.runtime.executeTurn("Reply with ok.")).rejects.toThrow(
  97. "Turn execution failed",
  98. );
  99. expect(requests).toHaveLength(1);
  100. expect(requests[0]?.model).toBe("eval-model");
  101. expect(requests[0]?.[field]).toBe(OUTPUT_BUDGET);
  102. } finally {
  103. await app.close?.();
  104. }
  105. } finally {
  106. store.close();
  107. processRuntime.dispose();
  108. }
  109. const saved = await readFile(personalPath, "utf8");
  110. // 模拟评测修改旧文件:已有正式文件时不能覆盖迁移后的值。
  111. input.provider.evaluation.models["eval-model"] = { maxOutputTokens: 8_000 };
  112. await writeFile(legacyPath, JSON.stringify(input));
  113. const restart = await startProcessProviderRegistryRuntime(env, options);
  114. try {
  115. expect(
  116. restart.runtime.registryService.getModel("evaluation", "eval-model")?.config.optionSpecs
  117. .maxOutputTokens.max,
  118. ).toBe(OUTPUT_BUDGET);
  119. expect(await readFile(personalPath, "utf8")).toBe(saved);
  120. } finally {
  121. restart.dispose();
  122. }
  123. } finally {
  124. server.closeAllConnections();
  125. await new Promise<void>((resolve, reject) =>
  126. server.close((error) => (error ? reject(error) : resolve())),
  127. );
  128. await rm(directory, { recursive: true, force: true });
  129. }
  130. },
  131. 30_000,
  132. );
  133. });