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

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