process-provider-registry-runtime.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. import { mkdtemp, readFile, 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 {
  6. ProviderConfig,
  7. ProviderConfigMap,
  8. ZhipuAccountAccessConfig,
  9. createAccountProviderConfigSnapshot,
  10. } from "@zcode/provider";
  11. import { zcodeProviderUpdateAccountConfigParamsSchema } from "@zcode/shared";
  12. import {
  13. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV,
  14. ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV,
  15. ZCODE_BUILTIN_RELEASE_SCHEMA_VERSION,
  16. createNodeModelSelectionFacade,
  17. } from "@zcode/provider-node";
  18. import { afterEach, describe, expect, it, vi } from "vitest";
  19. import {
  20. createSharedZCodeCredentialStore,
  21. type SharedZCodeCredentialStore,
  22. } from "@zcode/adapters/auth";
  23. import {
  24. parseProcessAccountProviderConfigSnapshot,
  25. startProcessProviderRegistryRuntime,
  26. } from "../src/app/process-provider-registry-runtime.js";
  27. import {
  28. standaloneAccountAuthSourceCredentialKey,
  29. standaloneAccountIdentityCredentialKey,
  30. standaloneAccountProviderCredentialKey,
  31. } from "../src/app/standalone-account-provider-runtime.js";
  32. const temporaryDirectories: string[] = [];
  33. afterEach(async () => {
  34. await Promise.all(
  35. temporaryDirectories
  36. .splice(0)
  37. .map((directory) => rm(directory, { force: true, recursive: true })),
  38. );
  39. });
  40. describe("process provider registry runtime", () => {
  41. it("Standalone 长生命周期下载 URL Release 后跟进 Registry;Managed Worker 不下载", async () => {
  42. const root = await temporaryDirectory();
  43. const builtin = JSON.parse(
  44. await readFile(
  45. new URL("../../../../../config/provider/zcode-builtin.json", import.meta.url),
  46. "utf8",
  47. ),
  48. );
  49. const bundled = join(root, "bundled.json");
  50. const active = join(root, "active.json");
  51. await writeFile(bundled, JSON.stringify(builtin));
  52. await writeFile(active, JSON.stringify(builtin));
  53. builtin.revision += 1;
  54. let releaseDownload!: () => void;
  55. const wait = new Promise<void>((resolve) => {
  56. releaseDownload = resolve;
  57. });
  58. const request = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
  59. expect(init?.headers).toBeUndefined();
  60. if (String(url).includes("/api/v1/client/configs?"))
  61. return new Response(
  62. JSON.stringify({
  63. code: 0,
  64. data: { configs: { builtin_provider_config_json: "https://cdn.example.com/new.json" } },
  65. }),
  66. );
  67. await wait;
  68. return new Response(JSON.stringify(builtin));
  69. });
  70. const credentialStore = createSharedZCodeCredentialStore({
  71. env: { ZCODE_DATA_BASE_DIR: root },
  72. });
  73. const env = {
  74. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: active,
  75. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: join(root, "personal.json"),
  76. ZCODE_BUILTIN_PROVIDER_BUNDLED_CONFIG_FILE: bundled,
  77. };
  78. const runtime = await startProcessProviderRegistryRuntime(env, {
  79. standalone: {
  80. credentialStore,
  81. request,
  82. legacyCliUserConfigFilePath: join(root, "absent.json"),
  83. },
  84. });
  85. const old = runtime.runtime.registryService.getSnapshot()!;
  86. try {
  87. await vi.waitFor(() => expect(request).toHaveBeenCalledTimes(2));
  88. expect(runtime.runtime.registryService.getSnapshot()).toBe(old);
  89. releaseDownload();
  90. await vi.waitFor(() =>
  91. expect(runtime.runtime.registryService.getSnapshot()!.config.zcodeBuiltinRevision).toMatch(
  92. `zcode-builtin:${builtin.revision}:`,
  93. ),
  94. );
  95. const next = runtime.runtime.registryService.getSnapshot()!;
  96. expect(next.account.basedOnZCodeBuiltinRevision).toBe(next.config.zcodeBuiltinRevision);
  97. expect(JSON.parse(await readFile(active, "utf8")).revision).toBe(builtin.revision);
  98. expect(JSON.parse(await readFile(bundled, "utf8")).revision).toBe(builtin.revision - 1);
  99. const worker = await startProcessProviderRegistryRuntime(env);
  100. try {
  101. expect(worker.snapshot.config.zcodeBuiltinRevision).toBe(next.config.zcodeBuiltinRevision);
  102. expect(request).toHaveBeenCalledTimes(2);
  103. } finally {
  104. worker.dispose();
  105. }
  106. } finally {
  107. releaseDownload();
  108. runtime.dispose();
  109. }
  110. });
  111. it("Standalone 无凭据时 Built-in 文件更新仍重新解析 Account 并整体发布 Registry", async () => {
  112. const root = await temporaryDirectory();
  113. const builtin = JSON.parse(
  114. await readFile(
  115. new URL("../../../../../config/provider/zcode-builtin.json", import.meta.url),
  116. "utf8",
  117. ),
  118. );
  119. const filePath = join(root, "builtin.json");
  120. await writeFile(filePath, JSON.stringify(builtin));
  121. const credentialStore = createSharedZCodeCredentialStore({
  122. env: { ZCODE_DATA_BASE_DIR: root },
  123. });
  124. const runtime = await startProcessProviderRegistryRuntime(
  125. {
  126. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: filePath,
  127. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: join(root, "personal.json"),
  128. },
  129. { standalone: { credentialStore, legacyCliUserConfigFilePath: join(root, "absent.json") } },
  130. );
  131. try {
  132. builtin.revision += 1;
  133. await writeFile(filePath, JSON.stringify(builtin));
  134. await vi.waitFor(() => {
  135. const next = runtime.runtime.registryService.getSnapshot()!;
  136. expect(next.config.zcodeBuiltinRevision).toMatch(`zcode-builtin:${builtin.revision}:`);
  137. expect(next.account.basedOnZCodeBuiltinRevision).toBe(next.config.zcodeBuiltinRevision);
  138. });
  139. expect(
  140. runtime.runtime.registryService.getProvider("account:bigmodel-individual-coding-plan"),
  141. ).toBeUndefined();
  142. } finally {
  143. runtime.dispose();
  144. }
  145. });
  146. it("真实 Built-in 下完整状态跨协议往返;仅切 current 即更新 Worker 的有效选择", async () => {
  147. const root = await temporaryDirectory();
  148. const runtime = await startProcessProviderRegistryRuntime({
  149. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: fileURLToPath(
  150. new URL("../../../../../config/provider/zcode-builtin.json", import.meta.url),
  151. ),
  152. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: join(root, "personal.json"),
  153. });
  154. const personal = "account:bigmodel-individual-coding-plan";
  155. const team = "account:bigmodel-team-coding-plan";
  156. const original = Object.freeze({
  157. providerId: personal,
  158. modelId: "GLM-5.3",
  159. options: Object.freeze({ reasoningLevel: "high" }),
  160. });
  161. const facade = createNodeModelSelectionFacade(runtime.runtime.registryService);
  162. const providers = new ProviderConfigMap(
  163. [personal, team].map((id) => [
  164. id,
  165. new ProviderConfig({ access: new ZhipuAccountAccessConfig({ entitled: true }) }),
  166. ]),
  167. );
  168. const revisions = new Set<string>();
  169. try {
  170. for (const current of [personal, team, personal]) {
  171. const snapshot = createAccountProviderConfigSnapshot(
  172. runtime.snapshot.config.zcodeBuiltinRevision,
  173. providers,
  174. {
  175. [personal]: {
  176. availability: "available",
  177. entitled: true,
  178. current: current === personal,
  179. },
  180. [team]: { availability: "available", entitled: true, current: current === team },
  181. },
  182. );
  183. revisions.add(snapshot.revision);
  184. const wire = zcodeProviderUpdateAccountConfigParamsSchema.parse(
  185. JSON.parse(
  186. JSON.stringify({
  187. ...snapshot,
  188. providers: Object.fromEntries(
  189. [...snapshot.providers.entries()].map(([id, config]) => [id, config.toJSON()]),
  190. ),
  191. }),
  192. ),
  193. );
  194. await runtime.syncAccountProviderConfig(parseProcessAccountProviderConfigSnapshot(wire));
  195. expect(runtime.runtime.registryService.getProvider(current)).toBeDefined();
  196. expect(
  197. runtime.runtime.registryService.getProvider(current === personal ? team : personal),
  198. ).toBeUndefined();
  199. expect(
  200. facade.getView(undefined, undefined, { selection: original }).effectiveSelection,
  201. ).toEqual({ ...original, providerId: current });
  202. expect(original.providerId).toBe(personal);
  203. }
  204. expect(revisions.size).toBe(2);
  205. } finally {
  206. runtime.dispose();
  207. }
  208. });
  209. it("解析独立同步的 Account Provider Config", () => {
  210. const states = {
  211. account: { availability: "available", entitled: true, current: false },
  212. } as const;
  213. const parsed = parseProcessAccountProviderConfigSnapshot({
  214. revision: "account-1",
  215. basedOnZCodeBuiltinRevision: "zcode-builtin:1",
  216. states,
  217. providers: {
  218. account: {
  219. access: { type: "zhipu-account", entitled: true },
  220. builtinModelIds: ["model-a"],
  221. },
  222. },
  223. });
  224. expect(
  225. Object.fromEntries(
  226. [...parsed.providers.entries()].map(([id, config]) => [id, config.toJSON()]),
  227. ),
  228. ).toEqual({
  229. account: {
  230. access: { type: "zhipu-account", entitled: true },
  231. builtinModelIds: ["model-a"],
  232. },
  233. });
  234. expect(parsed.basedOnZCodeBuiltinRevision).toBe("zcode-builtin:1");
  235. expect(parsed.states).toEqual(states);
  236. });
  237. it("独立 Account Config 同步拒绝 API Provider", () => {
  238. expect(() =>
  239. parseProcessAccountProviderConfigSnapshot({
  240. revision: "account-invalid",
  241. basedOnZCodeBuiltinRevision: "zcode-builtin:1",
  242. providers: {
  243. api: {
  244. access: {
  245. type: "api-key",
  246. apiKey: "must-not-enter-account-source",
  247. },
  248. },
  249. },
  250. }),
  251. ).toThrow();
  252. });
  253. it("独立 Account Config 只接受 entitlement 与账号特定模型成员", () => {
  254. expect(() =>
  255. parseProcessAccountProviderConfigSnapshot({
  256. revision: "account-invalid-static-field",
  257. basedOnZCodeBuiltinRevision: "zcode-builtin:1",
  258. providers: {
  259. account: {
  260. access: { type: "zhipu-account", entitled: true },
  261. label: "不得由 Account Source 覆盖",
  262. },
  263. },
  264. }),
  265. ).toThrow();
  266. });
  267. it("未注入 Provider Config 路径时拒绝启动", async () => {
  268. await expect(startProcessProviderRegistryRuntime({})).rejects.toThrow(
  269. "缺少进程 Provider Registry",
  270. );
  271. });
  272. it("Personal 文件损坏时保留原文件并以内存空配置启动", async () => {
  273. const root = await temporaryDirectory();
  274. const zcodeBuiltinFilePath = join(root, "zcode-builtin.json");
  275. const personalFilePath = join(root, "personal.json");
  276. await writeFile(
  277. zcodeBuiltinFilePath,
  278. JSON.stringify(zcodeBuiltinRelease({ providers: {}, templates: {}, models: [] })),
  279. );
  280. await writeFile(personalFilePath, "{not-json");
  281. const started = await startProcessProviderRegistryRuntime({
  282. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: zcodeBuiltinFilePath,
  283. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: personalFilePath,
  284. });
  285. try {
  286. expect(started.configuredDefaultModelSelection).toBeUndefined();
  287. expect(await readFile(personalFilePath, "utf8")).toBe("{not-json");
  288. await expect(
  289. started.modelSelectionConfigRepository.saveConfiguredDefault(undefined),
  290. ).rejects.toThrow();
  291. } finally {
  292. started.dispose();
  293. }
  294. await expect(started.modelSelectionConfigRepository.read()).rejects.toThrow("已 dispose");
  295. await expect(started.runtime.start()).rejects.toThrow("已 dispose");
  296. });
  297. it("从进程环境启动一份 Registry,并由调用方持有生命周期", async () => {
  298. const root = await temporaryDirectory();
  299. const zcodeBuiltinFilePath = join(root, "zcode-builtin.json");
  300. const personalFilePath = join(root, "personal.json");
  301. await writeFile(
  302. zcodeBuiltinFilePath,
  303. JSON.stringify(
  304. zcodeBuiltinRelease({
  305. providers: {
  306. account: {
  307. group: "zai-family",
  308. access: {
  309. type: "zhipu-account",
  310. accountType: "zai",
  311. mode: "individual-coding-plan",
  312. },
  313. api: {
  314. type: "anthropic-messages",
  315. baseUrl: "https://account.example.com",
  316. },
  317. builtinModelIds: ["model-a"],
  318. },
  319. },
  320. templates: {
  321. "zcode-template": {
  322. access: { type: "api-key" },
  323. api: {
  324. type: "anthropic-messages",
  325. baseUrl: "https://api.example.com",
  326. },
  327. builtinModelIds: ["model-a"],
  328. },
  329. },
  330. models: [
  331. {
  332. modelMatch: "model-a",
  333. config: {
  334. enabled: true,
  335. properties: {
  336. requiresMfjsToolSchema: false,
  337. contextWindow: 200000,
  338. inputFormat: {
  339. supportsText: true,
  340. supportsImage: false,
  341. supportsVideo: false,
  342. supportsAudio: false,
  343. supportsPdf: false,
  344. },
  345. outputFormat: { supportsText: true },
  346. supportsToolCall: true,
  347. supportsJsonSchemaOutput: true,
  348. supportsNativeWebSearch: false,
  349. supportsMidConversationSystem: false,
  350. },
  351. optionSpecs: {
  352. reasoningLevel: { values: ["disabled"], map: "{}" },
  353. maxOutputTokens: {
  354. max: 32000,
  355. map: '{"max_completion_tokens":maxOutputTokens}',
  356. },
  357. },
  358. },
  359. },
  360. ],
  361. }),
  362. ),
  363. "utf8",
  364. );
  365. await writeFile(
  366. personalFilePath,
  367. JSON.stringify(
  368. personalRelease([
  369. {
  370. providerId: "personal-api",
  371. templateId: "zcode-template",
  372. config: {
  373. group: "standard-personal",
  374. access: { type: "api-key", apiKey: "secret" },
  375. },
  376. },
  377. ]),
  378. ),
  379. "utf8",
  380. );
  381. const started = await startProcessProviderRegistryRuntime({
  382. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: zcodeBuiltinFilePath,
  383. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: personalFilePath,
  384. });
  385. expect(started?.snapshot.registry.providers).toHaveLength(1);
  386. expect(started?.runtime.registryService.getModel("personal-api", "model-a")).toBeDefined();
  387. started?.accountSource.replace(
  388. {
  389. revision: "account-access-1",
  390. basedOnZCodeBuiltinRevision: started!.snapshot.config.zcodeBuiltinRevision,
  391. providers: new ProviderConfigMap([
  392. [
  393. "account",
  394. new ProviderConfig({
  395. access: new ZhipuAccountAccessConfig({ entitled: true }),
  396. }),
  397. ],
  398. ]),
  399. },
  400. "test",
  401. );
  402. await started?.runtime.registryService.refresh("wait-for-account-access");
  403. expect(started?.runtime.registryService.getProvider("account")?.config).toMatchObject({
  404. access: {
  405. type: "zhipu-account",
  406. },
  407. builtinModelIds: ["model-a"],
  408. });
  409. const beforeSwitch = await started.accountSource.read();
  410. const switched = parseProcessAccountProviderConfigSnapshot({
  411. revision: "account-access-2",
  412. basedOnZCodeBuiltinRevision: beforeSwitch.basedOnZCodeBuiltinRevision,
  413. providers: Object.fromEntries(
  414. [...beforeSwitch.providers.entries()].map(([id, config]) => [id, config.toJSON()]),
  415. ),
  416. states: { account: { availability: "available", entitled: true, current: false } },
  417. });
  418. started.accountSource.replace(switched, "account-no-longer-current");
  419. await started.runtime.registryService.refresh("wait-for-account-selection");
  420. expect(started.runtime.registryService.getProvider("account")).toBeUndefined();
  421. expect(started.runtime.registryService.getProvider("personal-api")).toBeDefined();
  422. started?.dispose();
  423. });
  424. it("Standalone 从账号凭据生成 Account Overlay,并在请求前返回当前 API Key", async () => {
  425. const root = await temporaryDirectory();
  426. const zcodeBuiltinFilePath = join(root, "zcode-builtin.json");
  427. const personalFilePath = join(root, "personal.json");
  428. const credentialStore = createSharedZCodeCredentialStore({
  429. baseDir: join(root, "home"),
  430. env: { ZCODE_CREDENTIAL_SECRET: "process-registry-test" },
  431. });
  432. const providerId = "configured-standalone-provider";
  433. const accountIdentity = "account-1";
  434. const accountProviderCredentialKey = standaloneAccountProviderCredentialKey({
  435. providerId,
  436. accountIdentity,
  437. });
  438. await writeFile(
  439. zcodeBuiltinFilePath,
  440. JSON.stringify(
  441. zcodeBuiltinRelease({
  442. providers: {
  443. [providerId]: {
  444. group: "zai-family",
  445. access: {
  446. type: "zhipu-account",
  447. accountType: "zai",
  448. mode: "individual-coding-plan",
  449. },
  450. api: {
  451. type: "anthropic-messages",
  452. baseUrl: "https://account.example.com",
  453. },
  454. builtinModelIds: ["model-a"],
  455. },
  456. },
  457. templates: {},
  458. models: [
  459. {
  460. modelMatch: "model-a",
  461. config: {
  462. enabled: true,
  463. properties: {
  464. requiresMfjsToolSchema: false,
  465. contextWindow: 200000,
  466. inputFormat: {
  467. supportsText: true,
  468. supportsImage: false,
  469. supportsVideo: false,
  470. supportsAudio: false,
  471. supportsPdf: false,
  472. },
  473. outputFormat: { supportsText: true },
  474. supportsToolCall: true,
  475. supportsJsonSchemaOutput: true,
  476. supportsNativeWebSearch: false,
  477. supportsMidConversationSystem: false,
  478. },
  479. optionSpecs: {
  480. reasoningLevel: { values: ["disabled"], map: "{}" },
  481. maxOutputTokens: {
  482. max: 32000,
  483. map: '{"max_completion_tokens":maxOutputTokens}',
  484. },
  485. },
  486. },
  487. },
  488. ],
  489. }),
  490. ),
  491. "utf8",
  492. );
  493. await writeFile(personalFilePath, JSON.stringify(personalRelease([])), "utf8");
  494. await credentialStore.saveMany({
  495. [standaloneAccountIdentityCredentialKey(providerId)]: accountIdentity,
  496. [accountProviderCredentialKey]: "runtime-api-key",
  497. [standaloneAccountAuthSourceCredentialKey(providerId)]: "manual",
  498. });
  499. const started = await startProcessProviderRegistryRuntime(
  500. {
  501. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: zcodeBuiltinFilePath,
  502. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: personalFilePath,
  503. },
  504. { standalone: { credentialStore } },
  505. );
  506. expect(started?.runtime.registryService.getProvider(providerId)?.config.access).toMatchObject({
  507. type: "zhipu-account",
  508. accountType: "zai",
  509. mode: "individual-coding-plan",
  510. });
  511. await expect(
  512. started?.providerRuntimeHeadersPort.refreshBeforeModelRequest({
  513. accountAccess: {
  514. type: "zhipu-account",
  515. accountType: "zai",
  516. entitled: true,
  517. mode: "individual-coding-plan",
  518. },
  519. modelId: "model-a",
  520. providerId,
  521. reason: "model-request",
  522. sessionId: "session-1" as never,
  523. traceContext: { traceId: "trace-1" } as never,
  524. }),
  525. ).resolves.toMatchObject({
  526. headersApplied: true,
  527. requestAuth: { apiKey: "runtime-api-key" },
  528. });
  529. await credentialStore.save(accountProviderCredentialKey, "rotated-runtime-api-key");
  530. await expect(
  531. started?.providerRuntimeHeadersPort.refreshBeforeModelRequest({
  532. accountAccess: {
  533. type: "zhipu-account",
  534. accountType: "zai",
  535. entitled: true,
  536. mode: "individual-coding-plan",
  537. },
  538. modelId: "model-a",
  539. providerId,
  540. reason: "model-request",
  541. sessionId: "session-1" as never,
  542. traceContext: { traceId: "trace-2" } as never,
  543. }),
  544. ).resolves.toMatchObject({
  545. requestAuth: { apiKey: "rotated-runtime-api-key" },
  546. });
  547. await credentialStore.deleteIfValues({
  548. [standaloneAccountIdentityCredentialKey(providerId)]: accountIdentity,
  549. [accountProviderCredentialKey]: "rotated-runtime-api-key",
  550. });
  551. await vi.waitFor(() => {
  552. expect(started?.runtime.registryService.getProvider(providerId)).toBeUndefined();
  553. });
  554. started?.dispose();
  555. });
  556. it("Standalone 首次账号凭据读取失败时仍以 fail-closed Account 启动 Personal API Provider", async () => {
  557. const root = await temporaryDirectory();
  558. const zcodeBuiltinFilePath = join(root, "zcode-builtin.json");
  559. const personalFilePath = join(root, "personal.json");
  560. await writeFile(
  561. zcodeBuiltinFilePath,
  562. JSON.stringify(
  563. zcodeBuiltinRelease({
  564. providers: {},
  565. templates: {
  566. api: {
  567. access: { type: "api-key" },
  568. api: { type: "anthropic-messages", baseUrl: "https://api.example.com" },
  569. builtinModelIds: ["model-a"],
  570. },
  571. },
  572. models: [completeZCodeBuiltinModelRule()],
  573. }),
  574. ),
  575. "utf8",
  576. );
  577. await writeFile(
  578. personalFilePath,
  579. JSON.stringify(
  580. personalRelease([
  581. {
  582. providerId: "api",
  583. templateId: "api",
  584. config: {
  585. group: "standard-personal",
  586. access: { type: "api-key", apiKey: "secret" },
  587. },
  588. },
  589. ]),
  590. ),
  591. "utf8",
  592. );
  593. const accountError = new Error("credential store unavailable");
  594. const onAccountInitializationError = vi.fn();
  595. const credentialStore = {
  596. loadMany: vi.fn(async () => {
  597. throw accountError;
  598. }),
  599. } as unknown as SharedZCodeCredentialStore;
  600. const started = await startProcessProviderRegistryRuntime(
  601. {
  602. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: zcodeBuiltinFilePath,
  603. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: personalFilePath,
  604. },
  605. { standalone: { credentialStore, onAccountInitializationError } },
  606. );
  607. expect(started.runtime.registryService.getProvider("api")).toBeDefined();
  608. expect(onAccountInitializationError).toHaveBeenCalledWith(accountError);
  609. started.dispose();
  610. });
  611. it("只有显式开启 Standalone 导入时才迁移旧 CLI 用户 Provider", async () => {
  612. const root = await temporaryDirectory();
  613. const zcodeBuiltinFilePath = join(root, "zcode-builtin.json");
  614. const personalFilePath = join(root, "personal.json");
  615. const legacyFilePath = join(root, "legacy-cli.json");
  616. await writeFile(
  617. zcodeBuiltinFilePath,
  618. JSON.stringify(
  619. zcodeBuiltinRelease({
  620. providers: {},
  621. templates: {},
  622. // Personal Provider 仍由 Built-in 通用规则补齐静态模型事实;迁移器只搬运旧文件显式字段。
  623. models: [completeZCodeBuiltinModelRule()],
  624. }),
  625. ),
  626. "utf8",
  627. );
  628. await writeFile(
  629. legacyFilePath,
  630. JSON.stringify({
  631. model: "custom/model-a",
  632. provider: {
  633. custom: {
  634. kind: "anthropic",
  635. options: {
  636. apiKey: "secret",
  637. baseURL: "https://custom.example.com",
  638. },
  639. models: {
  640. "model-a": {
  641. limit: { context: 64_000, output: 8_000 },
  642. },
  643. },
  644. },
  645. },
  646. }),
  647. "utf8",
  648. );
  649. const env = {
  650. [ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]: zcodeBuiltinFilePath,
  651. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: personalFilePath,
  652. };
  653. // Protocol 启动会创建自己的空目标文件;若与 Standalone 共用目标,就会提前消费
  654. // “仅目标不存在时导入”的机会,无法再证明 Standalone importer 的独立边界。
  655. const protocolRuntime = await startProcessProviderRegistryRuntime({
  656. ...env,
  657. [ZCODE_PERSONAL_PROVIDER_CONFIG_FILE_ENV]: join(root, "protocol-personal.json"),
  658. });
  659. expect(protocolRuntime?.snapshot.registry.providers).toEqual([]);
  660. expect(protocolRuntime?.configuredDefaultModelSelection).toBeUndefined();
  661. protocolRuntime?.dispose();
  662. const standaloneRuntime = await startProcessProviderRegistryRuntime(env, {
  663. standalone: { legacyCliUserConfigFilePath: legacyFilePath },
  664. });
  665. expect(standaloneRuntime?.snapshot.registry.providers.map((entry) => entry.providerId)).toEqual(
  666. ["custom"],
  667. );
  668. expect(JSON.parse(await readFile(personalFilePath, "utf8"))).toMatchObject({
  669. schemaVersion: 1,
  670. config: {
  671. providerConfigRules: {
  672. providerRules: [
  673. { providerId: "custom", config: { access: { type: "api-key", apiKey: "secret" } } },
  674. ],
  675. },
  676. },
  677. });
  678. expect(standaloneRuntime?.configuredDefaultModelSelection).toEqual({
  679. providerId: "custom",
  680. modelId: "model-a",
  681. });
  682. expect(
  683. JSON.parse(await readFile(personalFilePath, "utf8")).config.defaultModelSelection,
  684. ).toEqual({
  685. providerId: "custom",
  686. modelId: "model-a",
  687. });
  688. standaloneRuntime?.dispose();
  689. const protocolRestart = await startProcessProviderRegistryRuntime(env);
  690. expect(protocolRestart?.configuredDefaultModelSelection).toEqual({
  691. providerId: "custom",
  692. modelId: "model-a",
  693. });
  694. protocolRestart?.dispose();
  695. await writeFile(
  696. legacyFilePath,
  697. JSON.stringify({
  698. provider: {
  699. replacement: {
  700. kind: "anthropic",
  701. options: {
  702. apiKey: "replacement-secret",
  703. baseURL: "https://replacement.example.com",
  704. },
  705. models: {
  706. "model-b": { limit: { context: 32_000, output: 4_000 } },
  707. },
  708. },
  709. },
  710. }),
  711. "utf8",
  712. );
  713. const restarted = await startProcessProviderRegistryRuntime(env, {
  714. standalone: { legacyCliUserConfigFilePath: legacyFilePath },
  715. });
  716. expect(restarted?.snapshot.registry.providers.map((entry) => entry.providerId)).toEqual([
  717. "custom",
  718. ]);
  719. expect(restarted?.configuredDefaultModelSelection).toEqual({
  720. providerId: "custom",
  721. modelId: "model-a",
  722. });
  723. restarted?.dispose();
  724. });
  725. });
  726. async function temporaryDirectory(): Promise<string> {
  727. const directory = await mkdtemp(join(tmpdir(), "zcode-process-provider-registry-"));
  728. temporaryDirectories.push(directory);
  729. return directory;
  730. }
  731. function completeZCodeBuiltinModelRule() {
  732. return {
  733. modelMatch: ".*",
  734. config: {
  735. enabled: true,
  736. properties: {
  737. requiresMfjsToolSchema: false,
  738. contextWindow: 200_000,
  739. inputFormat: {
  740. supportsText: true,
  741. supportsImage: false,
  742. supportsVideo: false,
  743. supportsAudio: false,
  744. supportsPdf: false,
  745. },
  746. outputFormat: { supportsText: true },
  747. supportsToolCall: true,
  748. supportsJsonSchemaOutput: true,
  749. supportsNativeWebSearch: false,
  750. supportsMidConversationSystem: false,
  751. },
  752. optionSpecs: {
  753. reasoningLevel: { values: ["disabled"], map: "{}" },
  754. maxOutputTokens: {
  755. max: 32_000,
  756. map: '{"max_completion_tokens":maxOutputTokens}',
  757. },
  758. },
  759. },
  760. } as const;
  761. }
  762. function zcodeBuiltinRelease(input: {
  763. readonly providers: object;
  764. readonly templates: object;
  765. readonly models: readonly unknown[];
  766. }): object {
  767. return {
  768. schemaVersion: ZCODE_BUILTIN_RELEASE_SCHEMA_VERSION,
  769. revision: 1,
  770. config: {
  771. providerConfigRules: {
  772. providerRules: Object.entries(input.providers).map(([providerId, config]) => ({
  773. providerId,
  774. config,
  775. })),
  776. templateRules: Object.entries(input.templates).map(([templateId, config]) => ({
  777. templateId,
  778. templateNameMap: { "en-US": templateId, "zh-CN": templateId },
  779. config,
  780. })),
  781. },
  782. modelConfigRules: {
  783. modelRules: input.models,
  784. modelApiRules: [],
  785. providerSiteRules: [],
  786. templateModelRules: [],
  787. builtinProviderModelRules: [],
  788. },
  789. },
  790. };
  791. }
  792. function personalRelease(providerRules: readonly unknown[]) {
  793. return {
  794. schemaVersion: 1,
  795. config: {
  796. providerConfigRules: { providerRules },
  797. modelConfigRules: { providerModelRules: [], manualProviderModelRules: [] },
  798. },
  799. };
  800. }