provider-config.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /* oxlint-disable eslint(max-lines) -- Provider 与 Access Config 的 Overlay/序列化必须集中维护同一联合类型;待契约稳定后再按配置族拆文件。 */
  2. import { ConfigOverlay, type ConfigValidationIssue } from "../config-overlay.js";
  3. import type { z } from "zod";
  4. import {
  5. completeApiKeyAccessDataSchema,
  6. completeZhipuAccountAccessDataSchema,
  7. completeProviderApiDataSchema,
  8. completeProviderConfigDataSchema,
  9. type providerApiTypeDataSchema,
  10. type providerGroupDataSchema,
  11. type zhipuAccountModeDataSchema,
  12. type providerVisibilityDataSchema,
  13. type providerLogoDataSchema,
  14. type apiKeyAccessDataSchema,
  15. type zhipuAccountAccessDataSchema,
  16. type providerAccessDataSchema,
  17. type providerApiDataSchema,
  18. type providerConfigDataSchema,
  19. type providerTemplateNameMapDataSchema,
  20. type providerTemplateDataSchema,
  21. } from "./provider-data-schema.js";
  22. import { validateConfigSchema } from "./schema-validation.js";
  23. import type { ModelId, ProviderId, ProviderTemplateId } from "./ids.js";
  24. import type { ProviderConfigRuleData } from "./rule-data-schema.js";
  25. export type ProviderApiType = z.infer<typeof providerApiTypeDataSchema>;
  26. export type ProviderGroup = z.infer<typeof providerGroupDataSchema>;
  27. export type ZhipuAccountMode = z.infer<typeof zhipuAccountModeDataSchema>;
  28. export type ApiKeyAccessConfigInput = Omit<ApiKeyAccessConfigObject, "type"> & {
  29. readonly type?: ApiKeyAccessConfigObject["type"];
  30. };
  31. export type ApiKeyAccessConfigObject = Readonly<z.infer<typeof apiKeyAccessDataSchema>>;
  32. export class ApiKeyAccessConfig extends ConfigOverlay<ApiKeyAccessConfig> {
  33. readonly type: ApiKeyAccessConfigObject["type"];
  34. readonly apiKey?: ApiKeyAccessConfigInput["apiKey"];
  35. readonly apiKeyManagementUrl?: ApiKeyAccessConfigInput["apiKeyManagementUrl"];
  36. constructor(input: ApiKeyAccessConfigInput = {}) {
  37. super();
  38. this.type = input.type ?? "api-key";
  39. this.apiKey = input.apiKey;
  40. this.apiKeyManagementUrl = input.apiKeyManagementUrl;
  41. Object.freeze(this);
  42. }
  43. overlay(next: ApiKeyAccessConfig): ApiKeyAccessConfig {
  44. return new ApiKeyAccessConfig({
  45. type: next.type,
  46. apiKey: this.overlayValue(this.apiKey, next.apiKey),
  47. apiKeyManagementUrl: this.overlayValue(this.apiKeyManagementUrl, next.apiKeyManagementUrl),
  48. });
  49. }
  50. validateComplete(path: readonly string[] = []): readonly ConfigValidationIssue[] {
  51. return validateConfigSchema(completeApiKeyAccessDataSchema, this.toJSON(), path);
  52. }
  53. toJSON(): ApiKeyAccessConfigObject {
  54. return {
  55. type: this.type,
  56. ...objectWithoutUndefined({
  57. apiKey: this.apiKey,
  58. apiKeyManagementUrl: this.apiKeyManagementUrl,
  59. }),
  60. };
  61. }
  62. }
  63. export type ZhipuAccountAccessConfigInput = Omit<ZhipuAccountAccessConfigObject, "type">;
  64. export type ZhipuAccountAccessConfigObject = Readonly<z.infer<typeof zhipuAccountAccessDataSchema>>;
  65. export class ZhipuAccountAccessConfig extends ConfigOverlay<ZhipuAccountAccessConfig> {
  66. readonly type = "zhipu-account" as const;
  67. readonly accountType?: ZhipuAccountAccessConfigInput["accountType"];
  68. readonly mode?: ZhipuAccountAccessConfigInput["mode"];
  69. readonly entitled?: ZhipuAccountAccessConfigInput["entitled"];
  70. constructor(input: ZhipuAccountAccessConfigInput = {}) {
  71. super();
  72. this.accountType = input.accountType;
  73. this.mode = input.mode;
  74. this.entitled = input.entitled;
  75. Object.freeze(this);
  76. }
  77. overlay(next: ZhipuAccountAccessConfig): ZhipuAccountAccessConfig {
  78. return new ZhipuAccountAccessConfig({
  79. accountType: this.overlayValue(this.accountType, next.accountType),
  80. mode: this.overlayValue(this.mode, next.mode),
  81. entitled: this.overlayValue(this.entitled, next.entitled),
  82. });
  83. }
  84. validateComplete(path: readonly string[] = []): readonly ConfigValidationIssue[] {
  85. return validateConfigSchema(completeZhipuAccountAccessDataSchema, this.toJSON(), path);
  86. }
  87. toJSON(): ZhipuAccountAccessConfigObject {
  88. return {
  89. type: this.type,
  90. ...objectWithoutUndefined({
  91. accountType: this.accountType,
  92. mode: this.mode,
  93. entitled: this.entitled,
  94. }),
  95. };
  96. }
  97. }
  98. export type ProviderAccessConfig = ApiKeyAccessConfig | ZhipuAccountAccessConfig;
  99. export type ProviderAccessConfigObject = Readonly<z.infer<typeof providerAccessDataSchema>>;
  100. /** 手动 Key 的编辑/保存共用能力判断,不把套餐 Key 误写成普通 API Key。 */
  101. export function isApiKeyAccess<T extends { readonly type: string }>(
  102. access: T | null | undefined,
  103. ): access is Extract<T, { readonly type: ApiKeyAccessConfigObject["type"] }> {
  104. return access?.type === "api-key" || access?.type === "zhipu-coding-plan-api-key";
  105. }
  106. export type ProviderVisibility = z.infer<typeof providerVisibilityDataSchema>;
  107. export type ProviderLogoRef = Readonly<z.infer<typeof providerLogoDataSchema>>;
  108. export type ProviderApiConfigInput = Readonly<z.infer<typeof providerApiDataSchema>>;
  109. export class ProviderApiConfig extends ConfigOverlay<ProviderApiConfig> {
  110. readonly type?: ProviderApiConfigInput["type"];
  111. readonly baseUrl?: ProviderApiConfigInput["baseUrl"];
  112. readonly headers?: ProviderApiConfigInput["headers"];
  113. constructor(input: ProviderApiConfigInput = {}) {
  114. super();
  115. this.type = input.type;
  116. this.baseUrl = input.baseUrl;
  117. this.headers = input.headers ? Object.freeze({ ...input.headers }) : input.headers;
  118. Object.freeze(this);
  119. }
  120. overlay(next: ProviderApiConfig): ProviderApiConfig {
  121. return new ProviderApiConfig({
  122. type: this.overlayValue(this.type, next.type),
  123. baseUrl: this.overlayValue(this.baseUrl, next.baseUrl),
  124. headers: this.overlayValue(this.headers, next.headers),
  125. });
  126. }
  127. validateComplete(path: readonly string[] = []): readonly ConfigValidationIssue[] {
  128. // 旧检查只判断 type 非空,不可信 JS 值可绕过枚举;准入与保存共用 schema。
  129. return validateConfigSchema(completeProviderApiDataSchema, this.toJSON(), path);
  130. }
  131. toJSON(): ProviderApiConfigInput {
  132. return objectWithoutUndefined({
  133. type: this.type,
  134. baseUrl: this.baseUrl,
  135. headers: this.headers,
  136. });
  137. }
  138. }
  139. export type ProviderConfigInput = Omit<ProviderConfigObject, "access" | "api"> & {
  140. readonly access?: ProviderAccessConfig | null;
  141. readonly api?: ProviderApiConfig | null;
  142. };
  143. export type ProviderConfigObject = Readonly<z.infer<typeof providerConfigDataSchema>>;
  144. export class ProviderConfig extends ConfigOverlay<ProviderConfig> {
  145. readonly group?: ProviderConfigObject["group"];
  146. readonly logo?: ProviderConfigObject["logo"];
  147. readonly access?: ProviderAccessConfig | null;
  148. readonly api?: ProviderApiConfig | null;
  149. readonly builtinModelIds?: ProviderConfigObject["builtinModelIds"];
  150. readonly personalModelIds?: ProviderConfigObject["personalModelIds"];
  151. readonly modelOrder?: ProviderConfigObject["modelOrder"];
  152. readonly visibility?: ProviderConfigObject["visibility"];
  153. constructor(input: ProviderConfigInput = {}) {
  154. super();
  155. this.group = input.group;
  156. this.logo = freezeProviderLogo(input.logo);
  157. this.access = input.access;
  158. this.api = input.api;
  159. this.builtinModelIds = freezeModelIds(input.builtinModelIds);
  160. this.personalModelIds = freezeModelIds(input.personalModelIds);
  161. this.modelOrder = freezeModelIds(input.modelOrder);
  162. this.visibility = input.visibility;
  163. Object.freeze(this);
  164. }
  165. overlay(next: ProviderConfig): ProviderConfig {
  166. return new ProviderConfig({
  167. group: this.overlayValue(this.group, next.group),
  168. logo: this.overlayValue(this.logo, next.logo),
  169. access: overlayProviderAccess(this.access, next.access),
  170. api: this.overlayConfig(this.api, next.api),
  171. builtinModelIds: this.overlayValue(this.builtinModelIds, next.builtinModelIds),
  172. personalModelIds: this.overlayValue(this.personalModelIds, next.personalModelIds),
  173. modelOrder: this.overlayValue(this.modelOrder, next.modelOrder),
  174. visibility: this.overlayValue(this.visibility, next.visibility),
  175. });
  176. }
  177. withBuiltinModelIds(builtinModelIds: readonly ModelId[]): ProviderConfig {
  178. return this.overlay(new ProviderConfig({ builtinModelIds }));
  179. }
  180. withPersonalModelIds(modelIds: readonly ModelId[]): ProviderConfig {
  181. return this.overlay(new ProviderConfig({ personalModelIds: modelIds }));
  182. }
  183. withModelOrder(modelOrder: readonly ModelId[]): ProviderConfig {
  184. return this.overlay(new ProviderConfig({ modelOrder }));
  185. }
  186. withoutGroup(): ProviderConfig {
  187. return new ProviderConfig({
  188. logo: this.logo,
  189. access: this.access,
  190. api: this.api,
  191. builtinModelIds: this.builtinModelIds,
  192. personalModelIds: this.personalModelIds,
  193. modelOrder: this.modelOrder,
  194. visibility: this.visibility,
  195. });
  196. }
  197. /** 普通 Provider 字段保存不拥有成员变更;成员只能由明确的领域操作更新。 */
  198. withModelMembershipFrom(source: ProviderConfig | undefined): ProviderConfig {
  199. return new ProviderConfig({
  200. group: this.group,
  201. logo: this.logo,
  202. access: this.access,
  203. api: this.api,
  204. builtinModelIds: source?.builtinModelIds,
  205. personalModelIds: source?.personalModelIds,
  206. modelOrder: source?.modelOrder,
  207. visibility: this.visibility,
  208. });
  209. }
  210. validateComplete(path: readonly string[] = []): readonly ConfigValidationIssue[] {
  211. // 不再用字段存在性代替值域验证,也不把展示/成员等可选字段变成执行必填项。
  212. return validateConfigSchema(completeProviderConfigDataSchema, this.toJSON(), path);
  213. }
  214. toJSON(): ProviderConfigObject {
  215. return objectWithoutUndefined({
  216. group: this.group,
  217. logo: this.logo,
  218. access: this.access?.toJSON() ?? this.access,
  219. api: this.api?.toJSON() ?? this.api,
  220. builtinModelIds: this.builtinModelIds,
  221. personalModelIds: this.personalModelIds,
  222. modelOrder: this.modelOrder,
  223. visibility: this.visibility,
  224. });
  225. }
  226. }
  227. export type ProviderTemplateNameMap = Readonly<z.infer<typeof providerTemplateNameMapDataSchema>>;
  228. export type ProviderTemplateLocale = keyof ProviderTemplateNameMap;
  229. export type ProviderTemplateInput = Omit<ProviderTemplateObject, "config"> & {
  230. readonly config: ProviderConfig;
  231. };
  232. export type ProviderTemplateObject = Readonly<z.infer<typeof providerTemplateDataSchema>>;
  233. /** Template 是元数据与 Provider Overlay 的领域壳,本身不是 Provider。 */
  234. export class ProviderTemplate {
  235. readonly templateId: ProviderTemplateId;
  236. readonly templateNameMap: ProviderTemplateNameMap;
  237. readonly config: ProviderConfig;
  238. constructor(input: ProviderTemplateInput) {
  239. this.templateId = input.templateId;
  240. this.templateNameMap = Object.freeze({ ...input.templateNameMap });
  241. this.config = input.config;
  242. Object.freeze(this);
  243. }
  244. toJSON(): ProviderTemplateObject {
  245. return {
  246. templateId: this.templateId,
  247. templateNameMap: this.templateNameMap,
  248. config: this.config.toJSON(),
  249. };
  250. }
  251. }
  252. export function resolveProviderTemplateName(
  253. templateId: ProviderTemplateId,
  254. template: Pick<ProviderTemplate, "templateNameMap">,
  255. locale: ProviderTemplateLocale,
  256. ): string {
  257. return (
  258. template.templateNameMap[locale]?.trim() ||
  259. template.templateNameMap["en-US"]?.trim() ||
  260. templateId
  261. );
  262. }
  263. /** Built-in Template 与真实 Provider 使用不同身份空间;Template 永不进入 Registry。 */
  264. export class ProviderTemplateMap extends ConfigOverlay<ProviderTemplateMap> {
  265. readonly #values: ReadonlyMap<ProviderTemplateId, ProviderTemplate>;
  266. constructor(entries: Iterable<readonly [ProviderTemplateId, ProviderTemplate]> = []) {
  267. super();
  268. const values = new Map<ProviderTemplateId, ProviderTemplate>();
  269. for (const [templateId, template] of entries) {
  270. if (values.has(templateId)) throw new Error(`重复 Provider Template key: ${templateId}`);
  271. values.set(templateId, template);
  272. }
  273. this.#values = values;
  274. Object.freeze(this);
  275. }
  276. static empty(): ProviderTemplateMap {
  277. return new ProviderTemplateMap();
  278. }
  279. overlay(next: ProviderTemplateMap): ProviderTemplateMap {
  280. const result = new Map(this.#values);
  281. for (const [templateId, template] of next.#values) result.set(templateId, template);
  282. return new ProviderTemplateMap(result);
  283. }
  284. validateComplete(): readonly ConfigValidationIssue[] {
  285. return [];
  286. }
  287. get(templateId: ProviderTemplateId): ProviderTemplate | undefined {
  288. return this.#values.get(templateId);
  289. }
  290. has(templateId: ProviderTemplateId): boolean {
  291. return this.#values.has(templateId);
  292. }
  293. keys(): ProviderTemplateId[] {
  294. return [...this.#values.keys()];
  295. }
  296. entries(): Array<readonly [ProviderTemplateId, ProviderTemplate]> {
  297. return [...this.#values.entries()];
  298. }
  299. toJSON(): ProviderTemplateObject[] {
  300. return this.entries().map(([, template]) => template.toJSON());
  301. }
  302. }
  303. function freezeProviderLogo(
  304. logo: ProviderLogoRef | null | undefined,
  305. ): ProviderLogoRef | null | undefined {
  306. return logo ? Object.freeze({ ...logo }) : logo;
  307. }
  308. function freezeModelIds(
  309. modelIds: readonly ModelId[] | null | undefined,
  310. ): readonly ModelId[] | null | undefined {
  311. if (!modelIds) return modelIds;
  312. return Object.freeze(
  313. modelIds.map((modelId) => {
  314. const normalized = modelId.trim();
  315. if (!normalized) throw new Error("Model ID 不能为空");
  316. return normalized;
  317. }),
  318. );
  319. }
  320. export type ProviderConfigRule = Readonly<
  321. Omit<ProviderConfigRuleData, "config"> & { config: ProviderConfig }
  322. >;
  323. /** 索引只保存完整规则;get/entries 是内容投影,改成员时不能丢掉外层身份和名称。 */
  324. export class ProviderConfigMap extends ConfigOverlay<ProviderConfigMap> {
  325. readonly #values: ReadonlyMap<ProviderId, ProviderConfigRule>;
  326. constructor(entries: Iterable<ProviderConfigRule | readonly [ProviderId, ProviderConfig]> = []) {
  327. super();
  328. const values = new Map<ProviderId, ProviderConfigRule>();
  329. for (const entry of entries) {
  330. const rule = "providerId" in entry ? entry : { providerId: entry[0], config: entry[1] };
  331. if (values.has(rule.providerId)) throw new Error(`重复 Provider key: ${rule.providerId}`);
  332. values.set(rule.providerId, Object.freeze({ ...rule }));
  333. }
  334. this.#values = values;
  335. Object.freeze(this);
  336. }
  337. static empty(): ProviderConfigMap {
  338. return new ProviderConfigMap();
  339. }
  340. overlay(next: ProviderConfigMap): ProviderConfigMap {
  341. const result = new Map(this.#values);
  342. for (const [providerId, rule] of next.#values) {
  343. const current = result.get(providerId);
  344. result.set(
  345. providerId,
  346. current
  347. ? {
  348. providerId,
  349. templateId: this.overlayValue(current.templateId, rule.templateId),
  350. providerName: this.overlayValue(current.providerName, rule.providerName),
  351. enabled: this.overlayValue(current.enabled, rule.enabled),
  352. config: current.config.overlay(rule.config),
  353. }
  354. : rule,
  355. );
  356. }
  357. return new ProviderConfigMap(result.values());
  358. }
  359. mapConfigs(
  360. transform: (
  361. config: ProviderConfig,
  362. providerId: ProviderId,
  363. rule: ProviderConfigRule,
  364. ) => ProviderConfig,
  365. ): ProviderConfigMap {
  366. return new ProviderConfigMap(
  367. this.rules().map((rule) => ({
  368. ...rule,
  369. config: transform(rule.config, rule.providerId, rule),
  370. })),
  371. );
  372. }
  373. reorder(providerIds: readonly ProviderId[]): ProviderConfigMap {
  374. const result = new Map<ProviderId, ProviderConfigRule>();
  375. for (const providerId of providerIds) {
  376. const rule = this.#values.get(providerId);
  377. if (rule && !result.has(providerId)) result.set(providerId, rule);
  378. }
  379. for (const [providerId, rule] of this.#values) {
  380. if (!result.has(providerId)) result.set(providerId, rule);
  381. }
  382. return new ProviderConfigMap(result.values());
  383. }
  384. set(providerId: ProviderId, config: ProviderConfig): ProviderConfigMap {
  385. return this.setRule({ ...this.#values.get(providerId), providerId, config });
  386. }
  387. setRule(rule: ProviderConfigRule): ProviderConfigMap {
  388. const result = new Map(this.#values);
  389. result.set(rule.providerId, rule);
  390. return new ProviderConfigMap(result.values());
  391. }
  392. delete(providerId: ProviderId): ProviderConfigMap {
  393. return new ProviderConfigMap(this.rules().filter((rule) => rule.providerId !== providerId));
  394. }
  395. validateComplete(path: readonly string[] = []): readonly ConfigValidationIssue[] {
  396. return this.entries().flatMap(([providerId, config]) =>
  397. config.validateComplete([...path, providerId]),
  398. );
  399. }
  400. get(providerId: ProviderId): ProviderConfig | undefined {
  401. return this.#values.get(providerId)?.config;
  402. }
  403. getRule(providerId: ProviderId): ProviderConfigRule | undefined {
  404. return this.#values.get(providerId);
  405. }
  406. has(providerId: ProviderId): boolean {
  407. return this.#values.has(providerId);
  408. }
  409. keys(): ProviderId[] {
  410. return [...this.#values.keys()];
  411. }
  412. rules(): ProviderConfigRule[] {
  413. return [...this.#values.values()];
  414. }
  415. entries(): Array<readonly [ProviderId, ProviderConfig]> {
  416. return this.rules().map((rule) => [rule.providerId, rule.config]);
  417. }
  418. toJSON(): ProviderConfigRuleData[] {
  419. return this.rules().map(({ config, ...rule }) =>
  420. objectWithoutUndefined({ ...rule, config: config.toJSON() }),
  421. );
  422. }
  423. }
  424. function overlayProviderAccess(
  425. current: ProviderAccessConfig | null | undefined,
  426. next: ProviderAccessConfig | null | undefined,
  427. ): ProviderAccessConfig | null | undefined {
  428. if (next === undefined) return current;
  429. if (next === null || current === undefined || current === null) return next;
  430. if (current.type !== next.type) return next;
  431. switch (current.type) {
  432. case "api-key":
  433. case "zhipu-coding-plan-api-key":
  434. return current.overlay(next as ApiKeyAccessConfig);
  435. case "zhipu-account":
  436. return current.overlay(next as ZhipuAccountAccessConfig);
  437. }
  438. }
  439. function objectWithoutUndefined<T extends object>(input: T): T {
  440. return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined)) as T;
  441. }