model-config.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. /* oxlint-disable eslint(max-lines) -- Model Config、嵌套 Overlay 与有序规则共同定义一份领域类型,暂不为行数拆散。 */
  2. import { ConfigOverlay, type ConfigValidationIssue } from "../config-overlay.js";
  3. import type { z } from "zod";
  4. import {
  5. completeEnumOptionSpecDataSchema,
  6. completeLimitOptionSpecDataSchema,
  7. completeModelInputFormatDataSchema,
  8. completeModelOutputFormatDataSchema,
  9. completeModelPropertiesDataSchema,
  10. completeModelOptionSpecsDataSchema,
  11. completeModelConfigDataSchema,
  12. type enumOptionSpecDataSchema,
  13. type limitOptionSpecDataSchema,
  14. type modelInputFormatDataSchema,
  15. type modelOutputFormatDataSchema,
  16. type modelPropertiesDataSchema,
  17. type modelOptionSpecsDataSchema,
  18. type modelConfigDataSchema,
  19. } from "@zcode/shared/model-config";
  20. import { validateConfigSchema } from "./schema-validation.js";
  21. import { clearManualModelConfig } from "./manual-model-config.js";
  22. import {
  23. providerModelConfigRuleSchema,
  24. manualProviderModelConfigRuleSchema,
  25. personalModelConfigRulesSchema,
  26. builtinModelConfigRulesSchema,
  27. type ProviderModelConfigRuleData,
  28. type ManualProviderModelConfigRuleData,
  29. type TemplateModelConfigRuleData,
  30. type ModelMatchConfigRuleData,
  31. type ModelApiMatchConfigRuleData,
  32. type ProviderSiteMatchConfigRuleData,
  33. type BuiltinModelConfigRulesData,
  34. type PersonalModelConfigRulesData,
  35. } from "./rule-data-schema.js";
  36. export type EnumOptionSpec = Readonly<z.infer<typeof completeEnumOptionSpecDataSchema>>;
  37. export type LimitOptionSpec = Readonly<z.infer<typeof completeLimitOptionSpecDataSchema>>;
  38. export type EnumOptionSpecConfigInput = Readonly<z.infer<typeof enumOptionSpecDataSchema>>;
  39. export class EnumOptionSpecConfig extends ConfigOverlay<EnumOptionSpecConfig> {
  40. readonly values?: EnumOptionSpecConfigInput["values"];
  41. readonly map?: EnumOptionSpecConfigInput["map"];
  42. constructor(input: EnumOptionSpecConfigInput = {}) {
  43. super();
  44. this.values =
  45. input.values === undefined
  46. ? undefined
  47. : input.values === null
  48. ? null
  49. : Object.freeze([...input.values]);
  50. this.map = input.map;
  51. Object.freeze(this);
  52. }
  53. overlay(next: EnumOptionSpecConfig): EnumOptionSpecConfig {
  54. return new EnumOptionSpecConfig({
  55. values: this.overlayValue(this.values, next.values),
  56. map: this.overlayValue(this.map, next.map),
  57. });
  58. }
  59. validateComplete(path: readonly string[] = []): readonly ConfigValidationIssue[] {
  60. return validateConfigSchema(completeEnumOptionSpecDataSchema, this.toJSON(), path, true);
  61. }
  62. toJSON(): EnumOptionSpecConfigInput {
  63. return objectWithoutUndefined({
  64. values: this.values,
  65. map: this.map,
  66. });
  67. }
  68. }
  69. export type LimitOptionSpecConfigInput = Readonly<z.infer<typeof limitOptionSpecDataSchema>>;
  70. export class LimitOptionSpecConfig extends ConfigOverlay<LimitOptionSpecConfig> {
  71. readonly max?: LimitOptionSpecConfigInput["max"];
  72. readonly map?: LimitOptionSpecConfigInput["map"];
  73. constructor(input: LimitOptionSpecConfigInput = {}) {
  74. super();
  75. Object.assign(this, input);
  76. Object.freeze(this);
  77. }
  78. overlay(next: LimitOptionSpecConfig): LimitOptionSpecConfig {
  79. return new LimitOptionSpecConfig({
  80. max: this.overlayValue(this.max, next.max),
  81. map: this.overlayValue(this.map, next.map),
  82. });
  83. }
  84. validateComplete(path: readonly string[] = []): readonly ConfigValidationIssue[] {
  85. return validateConfigSchema(completeLimitOptionSpecDataSchema, this.toJSON(), path, true);
  86. }
  87. toJSON(): LimitOptionSpecConfigInput {
  88. return objectWithoutUndefined({
  89. max: this.max,
  90. map: this.map,
  91. });
  92. }
  93. }
  94. export type ModelPropertiesConfigInput = Readonly<z.infer<typeof modelPropertiesDataSchema>>;
  95. export type ModelInputFormatConfigInput = Readonly<z.infer<typeof modelInputFormatDataSchema>>;
  96. export class ModelInputFormatConfig extends ConfigOverlay<ModelInputFormatConfig> {
  97. readonly supportsText?: ModelInputFormatConfigInput["supportsText"];
  98. readonly supportsImage?: ModelInputFormatConfigInput["supportsImage"];
  99. readonly supportsVideo?: ModelInputFormatConfigInput["supportsVideo"];
  100. readonly supportsAudio?: ModelInputFormatConfigInput["supportsAudio"];
  101. readonly supportsPdf?: ModelInputFormatConfigInput["supportsPdf"];
  102. constructor(input: ModelInputFormatConfigInput = {}) {
  103. super();
  104. Object.assign(this, input);
  105. Object.freeze(this);
  106. }
  107. overlay(next: ModelInputFormatConfig): ModelInputFormatConfig {
  108. return new ModelInputFormatConfig({
  109. supportsText: this.overlayValue(this.supportsText, next.supportsText),
  110. supportsImage: this.overlayValue(this.supportsImage, next.supportsImage),
  111. supportsVideo: this.overlayValue(this.supportsVideo, next.supportsVideo),
  112. supportsAudio: this.overlayValue(this.supportsAudio, next.supportsAudio),
  113. supportsPdf: this.overlayValue(this.supportsPdf, next.supportsPdf),
  114. });
  115. }
  116. validateComplete(path: readonly string[] = []): readonly ConfigValidationIssue[] {
  117. return validateConfigSchema(completeModelInputFormatDataSchema, this.toJSON(), path);
  118. }
  119. toJSON(): ModelInputFormatConfigInput {
  120. return objectWithoutUndefined({
  121. supportsText: this.supportsText,
  122. supportsImage: this.supportsImage,
  123. supportsVideo: this.supportsVideo,
  124. supportsAudio: this.supportsAudio,
  125. supportsPdf: this.supportsPdf,
  126. });
  127. }
  128. }
  129. export type ModelOutputFormatConfigInput = Readonly<z.infer<typeof modelOutputFormatDataSchema>>;
  130. export class ModelOutputFormatConfig extends ConfigOverlay<ModelOutputFormatConfig> {
  131. readonly supportsText?: ModelOutputFormatConfigInput["supportsText"];
  132. constructor(input: ModelOutputFormatConfigInput = {}) {
  133. super();
  134. Object.assign(this, input);
  135. Object.freeze(this);
  136. }
  137. overlay(next: ModelOutputFormatConfig): ModelOutputFormatConfig {
  138. return new ModelOutputFormatConfig({
  139. supportsText: this.overlayValue(this.supportsText, next.supportsText),
  140. });
  141. }
  142. validateComplete(path: readonly string[] = []): readonly ConfigValidationIssue[] {
  143. return validateConfigSchema(completeModelOutputFormatDataSchema, this.toJSON(), path);
  144. }
  145. toJSON(): ModelOutputFormatConfigInput {
  146. return objectWithoutUndefined({ supportsText: this.supportsText });
  147. }
  148. }
  149. export class ModelPropertiesConfig extends ConfigOverlay<ModelPropertiesConfig> {
  150. readonly requiresMfjsToolSchema?: ModelPropertiesConfigInput["requiresMfjsToolSchema"];
  151. readonly contextWindow?: ModelPropertiesConfigInput["contextWindow"];
  152. readonly inputFormat?: ModelInputFormatConfig | null;
  153. readonly outputFormat?: ModelOutputFormatConfig | null;
  154. readonly supportsToolCall?: ModelPropertiesConfigInput["supportsToolCall"];
  155. readonly supportsJsonSchemaOutput?: ModelPropertiesConfigInput["supportsJsonSchemaOutput"];
  156. readonly supportsNativeWebSearch?: ModelPropertiesConfigInput["supportsNativeWebSearch"];
  157. readonly supportsMidConversationSystem?: ModelPropertiesConfigInput["supportsMidConversationSystem"];
  158. constructor(input: ModelPropertiesConfigInput = {}) {
  159. super();
  160. Object.assign(this, {
  161. ...input,
  162. inputFormat:
  163. input.inputFormat instanceof ModelInputFormatConfig || input.inputFormat == null
  164. ? input.inputFormat
  165. : new ModelInputFormatConfig(input.inputFormat),
  166. outputFormat:
  167. input.outputFormat instanceof ModelOutputFormatConfig || input.outputFormat == null
  168. ? input.outputFormat
  169. : new ModelOutputFormatConfig(input.outputFormat),
  170. });
  171. Object.freeze(this);
  172. }
  173. overlay(next: ModelPropertiesConfig): ModelPropertiesConfig {
  174. return new ModelPropertiesConfig({
  175. requiresMfjsToolSchema: this.overlayValue(
  176. this.requiresMfjsToolSchema,
  177. next.requiresMfjsToolSchema,
  178. ),
  179. contextWindow: this.overlayValue(this.contextWindow, next.contextWindow),
  180. inputFormat: this.overlayConfig(this.inputFormat, next.inputFormat),
  181. outputFormat: this.overlayConfig(this.outputFormat, next.outputFormat),
  182. supportsToolCall: this.overlayValue(this.supportsToolCall, next.supportsToolCall),
  183. supportsJsonSchemaOutput: this.overlayValue(
  184. this.supportsJsonSchemaOutput,
  185. next.supportsJsonSchemaOutput,
  186. ),
  187. supportsNativeWebSearch: this.overlayValue(
  188. this.supportsNativeWebSearch,
  189. next.supportsNativeWebSearch,
  190. ),
  191. supportsMidConversationSystem: this.overlayValue(
  192. this.supportsMidConversationSystem,
  193. next.supportsMidConversationSystem,
  194. ),
  195. });
  196. }
  197. validateComplete(path: readonly string[] = []): readonly ConfigValidationIssue[] {
  198. return validateConfigSchema(completeModelPropertiesDataSchema, this.toJSON(), path);
  199. }
  200. toJSON(): ModelPropertiesConfigInput {
  201. return objectWithoutUndefined({
  202. requiresMfjsToolSchema: this.requiresMfjsToolSchema,
  203. contextWindow: this.contextWindow,
  204. inputFormat: this.inputFormat?.toJSON() ?? this.inputFormat,
  205. outputFormat: this.outputFormat?.toJSON() ?? this.outputFormat,
  206. supportsToolCall: this.supportsToolCall,
  207. supportsJsonSchemaOutput: this.supportsJsonSchemaOutput,
  208. supportsNativeWebSearch: this.supportsNativeWebSearch,
  209. supportsMidConversationSystem: this.supportsMidConversationSystem,
  210. });
  211. }
  212. }
  213. export type ModelOptionSpecsConfigInput = Readonly<z.infer<typeof modelOptionSpecsDataSchema>>;
  214. export class ModelOptionSpecsConfig extends ConfigOverlay<ModelOptionSpecsConfig> {
  215. readonly reasoningLevel?: EnumOptionSpecConfig | null;
  216. readonly maxOutputTokens?: LimitOptionSpecConfig | null;
  217. constructor(input: ModelOptionSpecsConfigInput = {}) {
  218. super();
  219. this.reasoningLevel = toEnumOptionSpecConfig(input.reasoningLevel);
  220. this.maxOutputTokens = toLimitOptionSpecConfig(input.maxOutputTokens);
  221. Object.freeze(this);
  222. }
  223. overlay(next: ModelOptionSpecsConfig): ModelOptionSpecsConfig {
  224. return new ModelOptionSpecsConfig({
  225. reasoningLevel: this.overlayConfig(this.reasoningLevel, next.reasoningLevel),
  226. maxOutputTokens: this.overlayConfig(this.maxOutputTokens, next.maxOutputTokens),
  227. });
  228. }
  229. validateComplete(path: readonly string[] = []): readonly ConfigValidationIssue[] {
  230. return validateConfigSchema(completeModelOptionSpecsDataSchema, this.toJSON(), path, true);
  231. }
  232. toJSON(): ModelOptionSpecsConfigInput {
  233. return objectWithoutUndefined({
  234. reasoningLevel: this.reasoningLevel?.toJSON() ?? this.reasoningLevel,
  235. maxOutputTokens: this.maxOutputTokens?.toJSON() ?? this.maxOutputTokens,
  236. });
  237. }
  238. }
  239. export type ModelConfigInput = Omit<ModelConfigObject, "properties" | "optionSpecs"> & {
  240. readonly properties?: ModelPropertiesConfig | null;
  241. readonly optionSpecs?: ModelOptionSpecsConfig | null;
  242. };
  243. export type ModelConfigObject = Readonly<z.infer<typeof modelConfigDataSchema>>;
  244. export class ModelConfig extends ConfigOverlay<ModelConfig> {
  245. readonly enabled?: ModelConfigObject["enabled"];
  246. readonly properties?: ModelPropertiesConfig | null;
  247. readonly optionSpecs?: ModelOptionSpecsConfig | null;
  248. constructor(input: ModelConfigInput = {}) {
  249. super();
  250. this.enabled = input.enabled;
  251. this.properties = input.properties;
  252. this.optionSpecs = input.optionSpecs;
  253. Object.freeze(this);
  254. }
  255. static empty(): ModelConfig {
  256. return new ModelConfig();
  257. }
  258. static fromData(config: ModelConfigObject): ModelConfig {
  259. return new ModelConfig({
  260. enabled: config.enabled,
  261. properties:
  262. config.properties == null
  263. ? config.properties
  264. : new ModelPropertiesConfig(config.properties),
  265. optionSpecs:
  266. config.optionSpecs == null
  267. ? config.optionSpecs
  268. : new ModelOptionSpecsConfig(config.optionSpecs),
  269. });
  270. }
  271. overlay(next: ModelConfig): ModelConfig {
  272. return new ModelConfig({
  273. enabled: this.overlayValue(this.enabled, next.enabled),
  274. properties: this.overlayConfig(this.properties, next.properties),
  275. optionSpecs: this.overlayConfig(this.optionSpecs, next.optionSpecs),
  276. });
  277. }
  278. validateComplete(path: readonly string[] = []): readonly ConfigValidationIssue[] {
  279. return validateConfigSchema(completeModelConfigDataSchema, this.toJSON(), path);
  280. }
  281. toJSON(): ModelConfigObject {
  282. return objectWithoutUndefined({
  283. enabled: this.enabled,
  284. properties: this.properties?.toJSON() ?? this.properties,
  285. optionSpecs: this.optionSpecs?.toJSON() ?? this.optionSpecs,
  286. });
  287. }
  288. }
  289. type RuleWithConfig<T> = Readonly<Omit<T, "config"> & { config: ModelConfig }>;
  290. export type ProviderModelConfigRule = RuleWithConfig<ProviderModelConfigRuleData>;
  291. export type ManualProviderModelConfigRule = RuleWithConfig<ManualProviderModelConfigRuleData>;
  292. export type TemplateModelConfigRule = RuleWithConfig<TemplateModelConfigRuleData>;
  293. export type ModelMatchConfigRule = RuleWithConfig<ModelMatchConfigRuleData>;
  294. export type ModelApiMatchConfigRule = RuleWithConfig<ModelApiMatchConfigRuleData>;
  295. export type ProviderSiteMatchConfigRule = RuleWithConfig<ProviderSiteMatchConfigRuleData>;
  296. /** type 只标识内存执行规则的来源层,不写入配置文件;分组不能再按字段有无猜测。 */
  297. export type ModelConfigRule =
  298. | (ProviderModelConfigRule & { readonly type: "provider-model" })
  299. | (ManualProviderModelConfigRule & { readonly type: "manual-provider-model" })
  300. | (TemplateModelConfigRule & { readonly type: "template-model" })
  301. | (ModelMatchConfigRule & { readonly type: "model" })
  302. | (ModelApiMatchConfigRule & { readonly type: "model-api" })
  303. | (ProviderSiteMatchConfigRule & { readonly type: "provider-site" });
  304. type ExactModelConfigRule = Extract<
  305. ModelConfigRule,
  306. { type: "provider-model" | "manual-provider-model" }
  307. >;
  308. export interface ModelConfigRuleResolutionInput {
  309. readonly providerId: string;
  310. readonly templateId?: string | null;
  311. readonly modelId: string;
  312. readonly apiType?: string | null;
  313. readonly baseUrl?: string | null;
  314. }
  315. export class ModelConfigRules {
  316. readonly #rules: readonly ModelConfigRule[];
  317. constructor(rules: readonly ModelConfigRule[] = []) {
  318. this.#rules = Object.freeze(rules.map((rule) => Object.freeze({ ...rule })));
  319. Object.freeze(this);
  320. }
  321. static empty(): ModelConfigRules {
  322. return new ModelConfigRules();
  323. }
  324. /** Built-in 保留原层次和组内顺序;个人只包含普通/手动精确规则。 */
  325. static composeEffective(builtin: ModelConfigRules, personal: ModelConfigRules): ModelConfigRules {
  326. return new ModelConfigRules([...builtin.rules(), ...personal.rules().filter(isExactModelRule)]);
  327. }
  328. rules(): readonly ModelConfigRule[] {
  329. return this.#rules;
  330. }
  331. resolve(input: ModelConfigRuleResolutionInput): ModelConfig {
  332. let result = ModelConfig.empty();
  333. const baseUrl = input.baseUrl == null ? undefined : normalizeBaseURLForRuleMatch(input.baseUrl);
  334. for (const rule of this.#rules) {
  335. if (isExactModelRule(rule)) {
  336. if (rule.providerId !== input.providerId || rule.modelId !== input.modelId) continue;
  337. // 手动规则要求所有可编辑叶子齐全,因此可直接覆盖;系统叶子继续来自当前身份的规则。
  338. // 清空整份基线会既丢失系统映射,也迫使 UI 把旧模型的隐藏配置复制进个人规则。
  339. result = (
  340. rule.type === "manual-provider-model"
  341. ? ModelConfig.fromData(clearManualModelConfig(result.toJSON()))
  342. : result
  343. ).overlay(rule.config);
  344. continue;
  345. }
  346. if (rule.type === "template-model") {
  347. if (rule.templateId === input.templateId && rule.modelId === input.modelId)
  348. result = result.overlay(rule.config);
  349. continue;
  350. }
  351. // 只放宽推荐规则匹配,不改真实请求里的模型 ID。
  352. if (!matchesRule(rule.modelMatch, input.modelId, true)) continue;
  353. if (
  354. (rule.type === "model-api" || rule.type === "provider-site") &&
  355. rule.apiTypeMatch !== undefined
  356. ) {
  357. if (input.apiType == null || !matchesRule(rule.apiTypeMatch, input.apiType)) continue;
  358. }
  359. if (
  360. rule.type === "provider-site" &&
  361. (baseUrl === undefined || !matchesRule(rule.baseUrlMatch, baseUrl))
  362. )
  363. continue;
  364. result = result.overlay(rule.config);
  365. }
  366. return result;
  367. }
  368. setExact(
  369. providerId: string,
  370. modelId: string,
  371. config: ModelConfig,
  372. useRecommendedConfig?: boolean,
  373. ): ModelConfigRules {
  374. const previous = this.getExactRule(providerId, modelId);
  375. const manual =
  376. useRecommendedConfig === undefined
  377. ? previous?.type === "manual-provider-model"
  378. : !useRecommendedConfig;
  379. // 保存入口复用整条规则 schema,不再另写一份“完整但忽略 enabled”的校验。
  380. const data = { providerId, modelId, config: config.toJSON() };
  381. (manual ? manualProviderModelConfigRuleSchema : providerModelConfigRuleSchema).parse(data);
  382. const replacement: ExactModelConfigRule = {
  383. type: manual ? "manual-provider-model" : "provider-model",
  384. providerId,
  385. modelId,
  386. config,
  387. };
  388. const result: ModelConfigRule[] = [];
  389. let replaced = false;
  390. for (const rule of this.#rules) {
  391. if (isExactModelRule(rule) && rule.providerId === providerId && rule.modelId === modelId) {
  392. if (!replaced) result.push(replacement);
  393. replaced = true;
  394. } else {
  395. result.push(rule);
  396. }
  397. }
  398. if (!replaced) result.push(replacement);
  399. return new ModelConfigRules(result);
  400. }
  401. deleteExact(providerId: string, modelId: string): ModelConfigRules {
  402. return new ModelConfigRules(
  403. this.#rules.filter(
  404. (rule) =>
  405. !isExactModelRule(rule) || rule.providerId !== providerId || rule.modelId !== modelId,
  406. ),
  407. );
  408. }
  409. renameExactModel(
  410. providerId: string,
  411. currentModelId: string,
  412. nextModelId: string,
  413. ): ModelConfigRules {
  414. if (currentModelId === nextModelId) return this;
  415. return new ModelConfigRules(
  416. this.#rules.map((rule) =>
  417. isExactModelRule(rule) && rule.providerId === providerId && rule.modelId === currentModelId
  418. ? { ...rule, modelId: nextModelId }
  419. : rule,
  420. ),
  421. );
  422. }
  423. deleteExactForProvider(providerId: string): ModelConfigRules {
  424. return new ModelConfigRules(
  425. this.#rules.filter((rule) => !isExactModelRule(rule) || rule.providerId !== providerId),
  426. );
  427. }
  428. getExact(providerId: string, modelId: string): ModelConfig | undefined {
  429. let result: ModelConfig | undefined;
  430. for (const rule of this.#rules) {
  431. if (!isExactModelRule(rule) || rule.providerId !== providerId || rule.modelId !== modelId)
  432. continue;
  433. result = result ? result.overlay(rule.config) : rule.config;
  434. }
  435. return result;
  436. }
  437. getExactRule(providerId: string, modelId: string): ExactModelConfigRule | undefined {
  438. for (let index = this.#rules.length - 1; index >= 0; index -= 1) {
  439. const rule = this.#rules[index]!;
  440. if (isExactModelRule(rule) && rule.providerId === providerId && rule.modelId === modelId)
  441. return rule;
  442. }
  443. return undefined;
  444. }
  445. toZCodeBuiltinJSON(): BuiltinModelConfigRulesData {
  446. return builtinModelConfigRulesSchema.parse({
  447. modelRules: this.#collect("model"),
  448. modelApiRules: this.#collect("model-api"),
  449. providerSiteRules: this.#collect("provider-site"),
  450. templateModelRules: this.#collect("template-model"),
  451. builtinProviderModelRules: this.#collect("provider-model"),
  452. });
  453. }
  454. toPersonalJSON(): PersonalModelConfigRulesData {
  455. // 完整规则必须在编码边界再校验,不能把直接构造的不完整手动值写入文件。
  456. return personalModelConfigRulesSchema.parse({
  457. providerModelRules: this.#collect("provider-model"),
  458. manualProviderModelRules: this.#collect("manual-provider-model"),
  459. });
  460. }
  461. toJSON() {
  462. return {
  463. ...this.toZCodeBuiltinJSON(),
  464. manualProviderModelRules: this.#collect("manual-provider-model"),
  465. };
  466. }
  467. #collect<T extends ModelConfigRule["type"]>(type: T) {
  468. return this.#rules
  469. .filter((rule): rule is Extract<ModelConfigRule, { type: T }> => rule.type === type)
  470. .map(({ type: _type, config, ...identity }) => ({ ...identity, config: config.toJSON() }));
  471. }
  472. }
  473. function isExactModelRule(rule: ModelConfigRule): rule is ExactModelConfigRule {
  474. return rule.type === "provider-model" || rule.type === "manual-provider-model";
  475. }
  476. function matchesRule(pattern: string, value: string, ignoreCase = false): boolean {
  477. return new RegExp(`^(?:${pattern})$`, ignoreCase ? "i" : undefined).test(value);
  478. }
  479. function normalizeBaseURLForRuleMatch(value: string): string | undefined {
  480. try {
  481. // Host 大小写、默认端口和尾部斜杠不应改变配置命中;URL parser 会保留 path/query 大小写。
  482. const parsed = new URL(value);
  483. const suffix = `${parsed.search}${parsed.hash}`;
  484. const serialized = parsed.toString();
  485. const endpoint = suffix.length === 0 ? serialized : serialized.slice(0, -suffix.length);
  486. return `${endpoint.replace(/\/+$/, "")}${suffix}`;
  487. } catch {
  488. return undefined;
  489. }
  490. }
  491. function toEnumOptionSpecConfig(
  492. spec: EnumOptionSpecConfig | EnumOptionSpecConfigInput | null | undefined,
  493. ): EnumOptionSpecConfig | null | undefined {
  494. return spec instanceof EnumOptionSpecConfig || spec == null
  495. ? spec
  496. : new EnumOptionSpecConfig(spec);
  497. }
  498. function toLimitOptionSpecConfig(
  499. spec: LimitOptionSpecConfig | LimitOptionSpecConfigInput | null | undefined,
  500. ): LimitOptionSpecConfig | null | undefined {
  501. return spec instanceof LimitOptionSpecConfig || spec == null
  502. ? spec
  503. : new LimitOptionSpecConfig(spec);
  504. }
  505. function objectWithoutUndefined<T extends object>(value: T): T {
  506. return Object.fromEntries(
  507. Object.entries(value).filter(([, fieldValue]) => fieldValue !== undefined),
  508. ) as T;
  509. }