provider-node-runtime.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { fileURLToPath } from "node:url";
  5. import { compileModelOptionMap } from "@zcode/model-option-map";
  6. import {
  7. ApiKeyAccessConfig,
  8. ModelConfigRules,
  9. ProviderConfig,
  10. ProviderConfigMap,
  11. type ProviderConfigLayerUpdate,
  12. } from "@zcode/provider";
  13. import { afterEach, describe, expect, it, vi } from "vitest";
  14. import {
  15. NodeZCodeBuiltinProviderConfigSource,
  16. NodePersonalProviderConfigRepository,
  17. NodeProviderConfigRuntime,
  18. NodeProviderRegistryRuntime,
  19. createNodeProviderRuntimePathEnv,
  20. materializeZCodeBuiltinProviderConfig,
  21. encodeProviderConfigFile,
  22. resolveZCodeBuiltinCachePaths,
  23. resolveNodeProviderRuntimePaths,
  24. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV,
  25. ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV,
  26. } from "../src/index.js";
  27. const temporaryDirectories: string[] = [];
  28. const zcodeBuiltinProviderConfigFilePath = fileURLToPath(
  29. new URL("../../../config/provider/zcode-builtin.json", import.meta.url),
  30. );
  31. afterEach(async () => {
  32. await Promise.all(
  33. temporaryDirectories
  34. .splice(0)
  35. // Windows 上 runtime 句柄异步关闭,rm 立刻删会撞 EBUSY;带重试兜住句柄释放延迟
  36. .map((directory) =>
  37. rm(directory, { force: true, recursive: true, maxRetries: 10, retryDelay: 200 }),
  38. ),
  39. );
  40. });
  41. describe("@zcode/provider-node", () => {
  42. it("从 Built-in Model Config Rules 解析 ox-alpha 同策略别名和 API-specific reasoning", async () => {
  43. const source = new NodeZCodeBuiltinProviderConfigSource({
  44. bundledFilePath: zcodeBuiltinProviderConfigFilePath,
  45. watch: false,
  46. });
  47. const snapshot = await source.read();
  48. for (const modelId of [
  49. "ox-alpha",
  50. "OPENROUTER/OX-ALPHA",
  51. "GLM-x-preview-f",
  52. "x-preview-f-free",
  53. ]) {
  54. const anthropic = snapshot.models.resolve({
  55. providerId: "custom",
  56. modelId,
  57. apiType: "anthropic-messages",
  58. });
  59. expect(anthropic.optionSpecs?.reasoningLevel).toMatchObject({
  60. values: ["low", "high", "max"],
  61. });
  62. expect(anthropic.optionSpecs?.reasoningLevel?.map).toContain("reasoningLevel");
  63. expect(
  64. compileModelOptionMap(
  65. anthropic.optionSpecs!.reasoningLevel!.map!,
  66. "reasoningLevel",
  67. ).evaluate("max"),
  68. ).toEqual({ thinking: { type: "adaptive" }, output_config: { effort: "max" } });
  69. const openAiCompatible = snapshot.models.resolve({
  70. providerId: "custom",
  71. modelId,
  72. apiType: "openai-chat-completions",
  73. });
  74. expect(
  75. compileModelOptionMap(
  76. openAiCompatible.optionSpecs!.reasoningLevel!.map!,
  77. "reasoningLevel",
  78. ).evaluate("high"),
  79. ).toEqual({ reasoning_effort: "high" });
  80. const responses = snapshot.models.resolve({
  81. providerId: "custom",
  82. modelId,
  83. apiType: "openai-responses",
  84. });
  85. // Todo138 已把通用兜底改为两档;Responses 没有 ox-alpha 专用值域,应继承该结果。
  86. expect(responses.optionSpecs?.reasoningLevel?.toJSON()).toMatchObject({
  87. values: ["disabled", "enabled"],
  88. });
  89. expect(
  90. compileModelOptionMap(
  91. responses.optionSpecs!.reasoningLevel!.map!,
  92. "reasoningLevel",
  93. ).evaluate("disabled"),
  94. ).toEqual({ reasoning: { effort: "none" } });
  95. expect(
  96. compileModelOptionMap(
  97. responses.optionSpecs!.reasoningLevel!.map!,
  98. "reasoningLevel",
  99. ).evaluate("enabled"),
  100. ).toEqual({ reasoning: { effort: "high" } });
  101. }
  102. source.dispose();
  103. });
  104. it("从 Built-in Config 解析模型能力、Access 协议和 Tool Schema 兼容事实", async () => {
  105. const source = new NodeZCodeBuiltinProviderConfigSource({
  106. bundledFilePath: zcodeBuiltinProviderConfigFilePath,
  107. watch: false,
  108. });
  109. const snapshot = await source.read();
  110. expect(
  111. snapshot.models.resolve({
  112. providerId: "personal-zai-api",
  113. templateId: "zai-api",
  114. modelId: "glm-5.3",
  115. apiType: "anthropic-messages",
  116. baseUrl: "https://api.z.ai/api/anthropic",
  117. }).properties,
  118. ).toMatchObject({
  119. supportsMidConversationSystem: true,
  120. supportsNativeWebSearch: true,
  121. });
  122. expect(
  123. snapshot.models.resolve({
  124. providerId: "moonshot-kimi",
  125. modelId: "kimi-k3",
  126. apiType: "anthropic-messages",
  127. baseUrl: "https://api.moonshot.cn/anthropic",
  128. }),
  129. ).toMatchObject({ properties: { requiresMfjsToolSchema: true } });
  130. expect(
  131. snapshot.models.resolve({
  132. providerId: "moonshot-kimi",
  133. modelId: "kimi-k2.6",
  134. apiType: "anthropic-messages",
  135. }),
  136. ).toMatchObject({ properties: { requiresMfjsToolSchema: false } });
  137. expect(
  138. snapshot.models.resolve({
  139. providerId: "personal",
  140. modelId: "claude-opus-4-8",
  141. apiType: "anthropic-messages",
  142. }).properties,
  143. ).toMatchObject({
  144. supportsMidConversationSystem: true,
  145. supportsNativeWebSearch: false,
  146. });
  147. expect(snapshot.providers.get("account:zai-start-plan")?.access).toMatchObject({
  148. type: "zhipu-account",
  149. accountType: "zai",
  150. mode: "start-plan",
  151. });
  152. expect(snapshot.providers.get("account:zai-offpeak-idle-plan")?.access).toMatchObject({
  153. type: "zhipu-account",
  154. accountType: "zai",
  155. mode: "off-peak",
  156. });
  157. expect(snapshot.providerTemplates?.get("deepseek")?.config.access).toMatchObject({
  158. type: "api-key",
  159. });
  160. source.dispose();
  161. });
  162. it("随包配置固定路径复用相同内容,升级后原子覆盖而不增加历史副本", async () => {
  163. const root = await temporaryDirectory();
  164. const firstContent = JSON.stringify({
  165. schemaVersion: 1,
  166. revision: 1,
  167. config: {
  168. providerConfigRules: { providerRules: [], templateRules: [] },
  169. modelConfigRules: {
  170. modelRules: [],
  171. modelApiRules: [],
  172. providerSiteRules: [],
  173. templateModelRules: [],
  174. builtinProviderModelRules: [],
  175. },
  176. },
  177. });
  178. const secondContent = JSON.stringify({
  179. schemaVersion: 1,
  180. revision: 2,
  181. config: {
  182. providerConfigRules: {
  183. providerRules: [
  184. {
  185. providerId: "zcodeBuiltin",
  186. config: {
  187. group: "zai-family",
  188. access: {
  189. type: "zhipu-account",
  190. accountType: "zai",
  191. mode: "start-plan",
  192. },
  193. builtinModelIds: [],
  194. },
  195. },
  196. ],
  197. templateRules: [],
  198. },
  199. modelConfigRules: {
  200. modelRules: [],
  201. modelApiRules: [],
  202. providerSiteRules: [],
  203. templateModelRules: [],
  204. builtinProviderModelRules: [],
  205. },
  206. },
  207. });
  208. const firstPath = await materializeZCodeBuiltinProviderConfig({
  209. environmentConfigRoot: root,
  210. content: firstContent,
  211. });
  212. const repeatedPath = await materializeZCodeBuiltinProviderConfig({
  213. environmentConfigRoot: root,
  214. content: firstContent,
  215. });
  216. const secondPath = await materializeZCodeBuiltinProviderConfig({
  217. environmentConfigRoot: root,
  218. content: secondContent,
  219. });
  220. expect(repeatedPath).toBe(firstPath);
  221. expect(firstPath).toBe(join(root, "runtime", "provider", "bundled", "zcode-builtin.json"));
  222. expect(secondPath).toBe(firstPath);
  223. expect(JSON.parse(await readFile(secondPath, "utf8"))).toEqual(JSON.parse(secondContent));
  224. expect(await readdir(join(root, "runtime", "provider", "bundled"))).toEqual([
  225. "zcode-builtin.json",
  226. ]);
  227. });
  228. it("只在 ZCode Built-in 与 Personal 路径同时存在时启用进程 Registry", () => {
  229. expect(resolveNodeProviderRuntimePaths({})).toBeNull();
  230. expect(() =>
  231. resolveNodeProviderRuntimePaths({
  232. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: "/zcodeBuiltin.json",
  233. }),
  234. ).toThrow("必须同时提供");
  235. expect(
  236. resolveNodeProviderRuntimePaths({
  237. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: " /zcodeBuiltin.json ",
  238. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: " /personal.json ",
  239. }),
  240. ).toEqual({
  241. zcodeBuiltinFilePath: "/zcodeBuiltin.json",
  242. personalFilePath: "/personal.json",
  243. });
  244. expect(
  245. createNodeProviderRuntimePathEnv({
  246. zcodeBuiltinFilePath: "/zcodeBuiltin.json",
  247. personalFilePath: "/personal.json",
  248. }),
  249. ).toEqual({
  250. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: "/zcodeBuiltin.json",
  251. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: "/personal.json",
  252. });
  253. });
  254. it("ZCode Built-in Source 每次读取当前版本化文件,revision 随内容改变", async () => {
  255. const root = await temporaryDirectory();
  256. const filePath = join(root, "zcodeBuiltin.json");
  257. await writeZCodeBuiltin(filePath, "model-a");
  258. const source = new NodeZCodeBuiltinProviderConfigSource({
  259. bundledFilePath: filePath,
  260. watch: false,
  261. });
  262. const first = await source.read();
  263. await writeZCodeBuiltin(filePath, "model-b");
  264. const second = await source.read();
  265. expect(first.providers.get("zcodeBuiltin")?.builtinModelIds).toEqual(["model-a"]);
  266. expect(second.providers.get("zcodeBuiltin")?.builtinModelIds).toEqual(["model-b"]);
  267. expect(second.revision).not.toBe(first.revision);
  268. source.dispose();
  269. });
  270. it("ZCode Built-in Source 只为新的 content revision 发布一次变化", async () => {
  271. const root = await temporaryDirectory();
  272. const filePath = join(root, "zcodeBuiltin.json");
  273. await writeZCodeBuiltin(filePath, "model-a");
  274. const source = new NodeZCodeBuiltinProviderConfigSource({ bundledFilePath: filePath });
  275. const reasons: string[] = [];
  276. source.onDidChange((reason) => reasons.push(reason));
  277. await source.read();
  278. await writeZCodeBuiltin(filePath, "model-a");
  279. await settleFileWatcher();
  280. expect(reasons).toEqual([]);
  281. await writeZCodeBuiltin(filePath, "model-b");
  282. await vi.waitFor(() => expect(reasons).toContain("file-changed"));
  283. await settleFileWatcher();
  284. expect(reasons).toEqual(["file-changed"]);
  285. expect((await source.read()).providers.get("zcodeBuiltin")?.builtinModelIds).toEqual([
  286. "model-b",
  287. ]);
  288. source.dispose();
  289. });
  290. it("Personal Repository 在跨调用文件锁内执行 read-modify-write", async () => {
  291. const root = await temporaryDirectory();
  292. const filePath = join(root, "provider-config.json");
  293. await writeFile(filePath, JSON.stringify(storedConfig(emptyUpdate())), "utf8");
  294. const first = new NodePersonalProviderConfigRepository({ filePath, watch: false });
  295. const second = new NodePersonalProviderConfigRepository({ filePath, watch: false });
  296. await Promise.all([
  297. first.update((current) => ({
  298. providers: current.providers.set("A", personalProviderConfig(false)),
  299. models: current.models,
  300. })),
  301. second.update((current) => ({
  302. providers: current.providers.set("B", personalProviderConfig(false)),
  303. models: current.models,
  304. })),
  305. ]);
  306. expect((await first.read()).providers.keys().toSorted()).toEqual(["A", "B"]);
  307. first.dispose();
  308. second.dispose();
  309. });
  310. it("Personal Repository 的显式更新不会被 polling 重复通知", async () => {
  311. const root = await temporaryDirectory();
  312. const filePath = join(root, "provider-config.json");
  313. await writeFile(filePath, JSON.stringify(storedConfig(emptyUpdate())), "utf8");
  314. const repository = new NodePersonalProviderConfigRepository({
  315. filePath,
  316. pollingIntervalMs: 10,
  317. });
  318. const reasons: string[] = [];
  319. repository.onDidChange((reason) => reasons.push(reason));
  320. await repository.read();
  321. await repository.update((current) => ({
  322. providers: current.providers.set("personal", personalProviderConfig(false)),
  323. models: current.models,
  324. }));
  325. await new Promise((resolve) => setTimeout(resolve, 40));
  326. expect(reasons).toEqual(["updated"]);
  327. repository.dispose();
  328. });
  329. it("Personal Repository 不依赖文件事件也会发现正式原子写产生的新 revision", async () => {
  330. const root = await temporaryDirectory();
  331. const filePath = join(root, "provider-config.json");
  332. await writeFile(filePath, JSON.stringify(storedConfig(emptyUpdate())), "utf8");
  333. const writer = new NodePersonalProviderConfigRepository({
  334. filePath,
  335. pollingIntervalMs: false,
  336. });
  337. const repository = new NodePersonalProviderConfigRepository({
  338. filePath,
  339. pollingIntervalMs: 10,
  340. });
  341. const reasons: string[] = [];
  342. repository.onDidChange((reason) => reasons.push(reason));
  343. await repository.read();
  344. await writer.update(() => ({
  345. providers: new ProviderConfigMap([["external", personalProviderConfig(false)]]),
  346. models: ModelConfigRules.empty(),
  347. }));
  348. await vi.waitFor(() => expect(reasons).toContain("poll-changed"));
  349. await new Promise((resolve) => setTimeout(resolve, 30));
  350. expect(reasons).toEqual(["poll-changed"]);
  351. expect((await repository.read()).providers.keys()).toEqual(["external"]);
  352. writer.dispose();
  353. repository.dispose();
  354. });
  355. it("Personal Repository 轮询读取暂时失败后会继续重试并恢复", async () => {
  356. const root = await temporaryDirectory();
  357. const filePath = join(root, "provider-config.json");
  358. // Windows 无开发者模式时 symlink 会 EPERM;直接把配置路径本身设为目录同样触发
  359. // 读取失败(readFile 目录抛错),保持用例跨平台可跑;恢复阶段先删目录再写文件
  360. await mkdir(filePath);
  361. const pollingErrors: unknown[] = [];
  362. const reasons: string[] = [];
  363. const repository = new NodePersonalProviderConfigRepository({
  364. filePath,
  365. onPollingError: (error) => pollingErrors.push(error),
  366. pollingIntervalMs: 10,
  367. });
  368. repository.onDidChange((reason) => reasons.push(reason));
  369. await repository.read();
  370. await vi.waitFor(() => expect(pollingErrors).toHaveLength(1));
  371. await new Promise((resolve) => setTimeout(resolve, 30));
  372. expect(pollingErrors).toHaveLength(1);
  373. await rm(filePath, { force: true, recursive: true });
  374. await writeFile(
  375. filePath,
  376. JSON.stringify(
  377. storedConfig({
  378. providers: new ProviderConfigMap([["recovered", personalProviderConfig(false)]]),
  379. models: ModelConfigRules.empty(),
  380. }),
  381. ),
  382. "utf8",
  383. );
  384. await vi.waitFor(() => expect(reasons).toContain("poll-changed"));
  385. expect((await repository.read()).providers.keys()).toEqual(["recovered"]);
  386. repository.dispose();
  387. });
  388. it("Personal Repository 轮询不会重复执行 Legacy importer 或写迁移文件", async () => {
  389. const root = await temporaryDirectory();
  390. const filePath = join(root, "provider-config.json");
  391. const importLegacy = vi.fn(async () => null);
  392. const repository = new NodePersonalProviderConfigRepository({
  393. filePath,
  394. importLegacy,
  395. pollingIntervalMs: 10,
  396. });
  397. await repository.read();
  398. await new Promise((resolve) => setTimeout(resolve, 40));
  399. expect(importLegacy).toHaveBeenCalledOnce();
  400. repository.dispose();
  401. });
  402. it("Node Config Runtime 在新目标缺失时调用外部 Legacy Importer 并不产生备份", async () => {
  403. const root = await temporaryDirectory();
  404. const zcodeBuiltinFilePath = join(root, "zcodeBuiltin.json");
  405. const personalFilePath = join(root, "provider_config.json");
  406. await writeZCodeBuiltin(zcodeBuiltinFilePath, "zcodeBuiltin-model");
  407. const importLegacy = vi.fn(async () => {
  408. return Object.freeze({
  409. providers: new ProviderConfigMap([["legacy", personalProviderConfig(false)]]),
  410. models: ModelConfigRules.empty(),
  411. });
  412. });
  413. const runtime = new NodeProviderConfigRuntime({
  414. zcodeBuiltinFilePath,
  415. personalFilePath,
  416. importLegacy,
  417. watch: false,
  418. });
  419. expect(await runtime.start()).toBeUndefined();
  420. const snapshot = await runtime.configService.read();
  421. expect(importLegacy).toHaveBeenCalledOnce();
  422. expect(snapshot.personalProviders.keys()).toEqual(["legacy"]);
  423. expect(JSON.parse(await readFile(personalFilePath, "utf8"))).toMatchObject({
  424. schemaVersion: 1,
  425. config: {
  426. providerConfigRules: {
  427. providerRules: [{ providerId: "legacy", config: { group: "standard-personal" } }],
  428. },
  429. },
  430. });
  431. expect((await readdir(root)).some((name) => name.endsWith(".bak"))).toBe(false);
  432. runtime.dispose();
  433. const repeatedImport = vi.fn(async () => {
  434. throw new Error("已有 Personal Config 时不应再次导入旧 Provider Store");
  435. });
  436. const restartedRuntime = new NodeProviderConfigRuntime({
  437. zcodeBuiltinFilePath,
  438. personalFilePath,
  439. importLegacy: repeatedImport,
  440. watch: false,
  441. });
  442. expect(await restartedRuntime.start()).toBeUndefined();
  443. const restartedSnapshot = await restartedRuntime.configService.read();
  444. expect(repeatedImport).not.toHaveBeenCalled();
  445. expect(restartedSnapshot.personalProviders.keys()).toEqual(["legacy"]);
  446. restartedRuntime.dispose();
  447. });
  448. it("多个进程并发首次读取时只在目标文件锁内导入一次", async () => {
  449. const root = await temporaryDirectory();
  450. const personalFilePath = join(root, "provider_config.json");
  451. const importLegacy = vi.fn(async () =>
  452. Object.freeze({
  453. providers: new ProviderConfigMap([["legacy", personalProviderConfig(false)]]),
  454. models: ModelConfigRules.empty(),
  455. }),
  456. );
  457. const first = new NodePersonalProviderConfigRepository({
  458. filePath: personalFilePath,
  459. importLegacy,
  460. pollingIntervalMs: false,
  461. });
  462. const second = new NodePersonalProviderConfigRepository({
  463. filePath: personalFilePath,
  464. importLegacy,
  465. pollingIntervalMs: false,
  466. });
  467. const snapshots = await Promise.all([first.read(), second.read()]);
  468. expect(importLegacy).toHaveBeenCalledOnce();
  469. expect(snapshots.map((snapshot) => snapshot.providers.keys())).toEqual([
  470. ["legacy"],
  471. ["legacy"],
  472. ]);
  473. first.dispose();
  474. second.dispose();
  475. });
  476. it("Endpoint-scoped Config Runtime 向 Agent 暴露当前 Endpoint 的 Active 路径", async () => {
  477. const root = await temporaryDirectory();
  478. const zcodeBuiltinFilePath = join(root, "zcodeBuiltin.json");
  479. const environmentConfigRoot = join(root, "environment");
  480. const personalFilePath = join(root, "config.json");
  481. const endpointOrigin = "https://api.example.com";
  482. await writeZCodeBuiltin(zcodeBuiltinFilePath, "zcodeBuiltin-model");
  483. const runtime = new NodeProviderConfigRuntime({
  484. zcodeBuiltinFilePath,
  485. personalFilePath,
  486. zcodeBuiltinEnvironment: {
  487. environmentConfigRoot,
  488. platform: "darwin-aarch64",
  489. appVersion: "3.9.2",
  490. resolveEndpointOrigin: () => endpointOrigin,
  491. fetchRelease: async () => null,
  492. watch: false,
  493. },
  494. watch: false,
  495. });
  496. await runtime.start();
  497. await expect(runtime.resolveZCodeBuiltinActiveFilePath()).resolves.toBe(
  498. resolveZCodeBuiltinCachePaths({
  499. environmentConfigRoot,
  500. platform: "darwin-aarch64",
  501. appVersion: "3.9.2",
  502. zcodeEndpointOrigin: endpointOrigin,
  503. }).activeFilePath,
  504. );
  505. // start 不等待后台下载;释放临时目录前等待首轮控制文件 lease 收尾,不能和 rm 竞态。
  506. await runtime.refreshZCodeBuiltin();
  507. runtime.dispose();
  508. });
  509. it("正式 Personal Config 损坏时保留原文件且不误调 Legacy Importer", async () => {
  510. const root = await temporaryDirectory();
  511. const zcodeBuiltinFilePath = join(root, "zcodeBuiltin.json");
  512. const personalFilePath = join(root, "provider_config.json");
  513. const invalidText = JSON.stringify({ provider: { unsupported: {} } }, null, 2);
  514. await writeZCodeBuiltin(zcodeBuiltinFilePath, "zcodeBuiltin-model");
  515. await writeFile(personalFilePath, invalidText, "utf8");
  516. const importLegacy = vi.fn(async () => emptyUpdate());
  517. const runtime = new NodeProviderConfigRuntime({
  518. zcodeBuiltinFilePath,
  519. personalFilePath,
  520. importLegacy,
  521. watch: false,
  522. });
  523. await expect(runtime.start()).resolves.toBeUndefined();
  524. await expect(runtime.start()).resolves.toBeUndefined();
  525. expect((await runtime.configService.read()).personalProviders.keys()).toEqual([]);
  526. expect(importLegacy).not.toHaveBeenCalled();
  527. expect(await readFile(personalFilePath, "utf8")).toBe(invalidText);
  528. expect((await readdir(root)).some((name) => name.endsWith(".bak"))).toBe(false);
  529. runtime.dispose();
  530. });
  531. it("Node Registry Runtime 在进程级聚合 Config,并只发布完整 API Provider", async () => {
  532. const root = await temporaryDirectory();
  533. const zcodeBuiltinFilePath = join(root, "zcodeBuiltin.json");
  534. const personalFilePath = join(root, "personal.json");
  535. await writeCompleteZCodeBuiltin(zcodeBuiltinFilePath);
  536. await writeFile(
  537. personalFilePath,
  538. JSON.stringify(
  539. storedConfig({
  540. providers: new ProviderConfigMap([
  541. {
  542. providerId: "zcodeBuiltin",
  543. templateId: "test-api",
  544. config: new ProviderConfig({
  545. group: "standard-personal",
  546. access: new ApiKeyAccessConfig({ apiKey: "secret" }),
  547. }),
  548. },
  549. ]),
  550. models: ModelConfigRules.empty(),
  551. }),
  552. ),
  553. "utf8",
  554. );
  555. const runtime = new NodeProviderRegistryRuntime({
  556. zcodeBuiltinFilePath,
  557. personalFilePath,
  558. watch: false,
  559. });
  560. expect(await runtime.start()).toBeUndefined();
  561. const snapshot = runtime.registryService.getSnapshot()!;
  562. expect(snapshot.registry.providers).toHaveLength(1);
  563. expect(
  564. runtime.registryService.getModel("zcodeBuiltin", "model-a")?.config.properties,
  565. ).toMatchObject({
  566. contextWindow: 200_000,
  567. inputFormat: expect.objectContaining({ supportsVideo: false }),
  568. });
  569. runtime.dispose();
  570. });
  571. });
  572. async function temporaryDirectory(): Promise<string> {
  573. const directory = await mkdtemp(join(tmpdir(), "zcode-provider-node-"));
  574. temporaryDirectories.push(directory);
  575. return directory;
  576. }
  577. async function settleFileWatcher(): Promise<void> {
  578. await new Promise((resolve) => setTimeout(resolve, 100));
  579. }
  580. function emptyUpdate(): ProviderConfigLayerUpdate {
  581. return Object.freeze({
  582. providers: ProviderConfigMap.empty(),
  583. models: ModelConfigRules.empty(),
  584. });
  585. }
  586. function personalProviderConfig(_enabled: boolean): ProviderConfig {
  587. return new ProviderConfig({
  588. group: "standard-personal",
  589. access: new ApiKeyAccessConfig(),
  590. });
  591. }
  592. function storedConfig(update: ProviderConfigLayerUpdate): object {
  593. return encodeProviderConfigFile(update);
  594. }
  595. async function writeZCodeBuiltin(filePath: string, modelId: string): Promise<void> {
  596. await writeFile(
  597. filePath,
  598. JSON.stringify({
  599. schemaVersion: 1,
  600. revision: modelId === "model-a" ? 1 : 2,
  601. config: {
  602. providerConfigRules: {
  603. providerRules: [
  604. {
  605. providerId: "zcodeBuiltin",
  606. config: {
  607. group: "zai-family",
  608. access: {
  609. type: "zhipu-account",
  610. accountType: "zai",
  611. mode: "start-plan",
  612. },
  613. builtinModelIds: [modelId],
  614. },
  615. },
  616. ],
  617. templateRules: [],
  618. },
  619. modelConfigRules: {
  620. modelRules: [],
  621. modelApiRules: [],
  622. providerSiteRules: [],
  623. templateModelRules: [],
  624. builtinProviderModelRules: [],
  625. },
  626. },
  627. }),
  628. "utf8",
  629. );
  630. }
  631. async function writeCompleteZCodeBuiltin(filePath: string): Promise<void> {
  632. await writeFile(
  633. filePath,
  634. JSON.stringify({
  635. schemaVersion: 1,
  636. revision: 1,
  637. config: {
  638. providerConfigRules: {
  639. providerRules: [],
  640. templateRules: [
  641. {
  642. templateId: "test-api",
  643. templateNameMap: { "en-US": "Test API" },
  644. config: {
  645. access: { type: "api-key" },
  646. api: {
  647. type: "anthropic-messages",
  648. baseUrl: "https://api.example.com",
  649. },
  650. builtinModelIds: ["model-a"],
  651. },
  652. },
  653. ],
  654. },
  655. modelConfigRules: {
  656. modelRules: [],
  657. modelApiRules: [],
  658. providerSiteRules: [],
  659. templateModelRules: [
  660. {
  661. templateId: "test-api",
  662. modelId: "model-a",
  663. config: {
  664. enabled: true,
  665. properties: {
  666. requiresMfjsToolSchema: false,
  667. contextWindow: 200000,
  668. inputFormat: {
  669. supportsText: true,
  670. supportsImage: false,
  671. supportsVideo: false,
  672. supportsAudio: false,
  673. supportsPdf: false,
  674. },
  675. outputFormat: { supportsText: true },
  676. supportsToolCall: true,
  677. supportsJsonSchemaOutput: true,
  678. supportsNativeWebSearch: false,
  679. supportsMidConversationSystem: false,
  680. },
  681. optionSpecs: {
  682. reasoningLevel: {
  683. values: ["disabled"],
  684. map: "{}",
  685. },
  686. maxOutputTokens: {
  687. max: 32000,
  688. map: "{'max_tokens': maxOutputTokens}",
  689. },
  690. },
  691. },
  692. },
  693. ],
  694. builtinProviderModelRules: [],
  695. },
  696. },
  697. }),
  698. "utf8",
  699. );
  700. }