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

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