model-resolver-byok.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // BYOK source resolution planning for the model resolver: turns a
  2. // source-qualified provider reference (`minimax_api`, `custom_provider:<key>`)
  3. // into concrete credentials + limits, without touching the legacy provider
  4. // tree path. Custom providers never consult the Pi catalog by name; missing
  5. // limits use the dedicated BYOK fallbacks (not the legacy 2048 default).
  6. import type { Api } from '@earendil-works/pi-ai';
  7. import { MINIMAX_API_MODEL_CATALOG } from '@mavis/config';
  8. import type {
  9. LocalCustomProvidersConfig,
  10. LocalMinimaxApiConfig,
  11. LocalModelsConfig,
  12. } from '../config/types.js';
  13. import { MINIMAX_API_DEFAULT_BASE_URL } from '../model-provider/list-models.js';
  14. import {
  15. mergeProviderHeaders,
  16. normalizeProviderBaseUrl,
  17. type ModelProviderApi,
  18. } from '../model-provider/provider-request.js';
  19. export interface LocalByokProviderConfig {
  20. minimax_api?: LocalMinimaxApiConfig;
  21. custom_provider?: LocalCustomProvidersConfig;
  22. minimaxModelSource?: 'token_plan' | 'minimax_api_key';
  23. }
  24. export const BYOK_FALLBACK_MODEL_LIMITS = {
  25. contextWindow: 200_000,
  26. maxTokens: 16_384,
  27. } as const;
  28. export interface ByokResolutionPlan {
  29. provider: string;
  30. api: Api;
  31. apiKey?: string;
  32. authProvider?: string;
  33. runtimeProvider?: string;
  34. baseUrl: string;
  35. contextWindow: number;
  36. maxTokens: number;
  37. configHeaders?: Record<string, string>;
  38. }
  39. type ResolvedByokResolutionPlan = Omit<ByokResolutionPlan, 'apiKey' | 'authProvider'> & {
  40. apiKey: string;
  41. };
  42. export async function resolveByokResolutionPlan(
  43. plan: ByokResolutionPlan,
  44. providerAuthGetter:
  45. | ((provider: string) => Promise<string | undefined> | string | undefined)
  46. | undefined,
  47. ): Promise<ResolvedByokResolutionPlan> {
  48. const { authProvider, apiKey: configuredApiKey, ...resolved } = plan;
  49. const apiKey = (
  50. authProvider ? await providerAuthGetter?.(authProvider) : configuredApiKey
  51. )?.trim();
  52. if (!apiKey) {
  53. throw new Error(
  54. authProvider
  55. ? `LocalModelResolver: ${authProvider} login required; no OAuth credentials found.`
  56. : `LocalModelResolver: api_key not configured for provider "${plan.provider}".`,
  57. );
  58. }
  59. return { ...resolved, apiKey };
  60. }
  61. export function planMinimaxApiResolution(input: {
  62. byok: LocalByokProviderConfig | undefined;
  63. providerConfig: LocalModelsConfig | undefined;
  64. modelId: string;
  65. catalog: { contextWindow: number; maxTokens: number; fromCatalog: boolean };
  66. }): ByokResolutionPlan | undefined {
  67. const cfg = input.byok?.minimax_api;
  68. if (!cfg) return undefined;
  69. const apiKey = cfg.apiKey?.trim();
  70. if (!apiKey) {
  71. throw new Error('LocalModelResolver: minimax_api apiKey is not configured.');
  72. }
  73. const catalogModel = MINIMAX_API_MODEL_CATALOG[input.modelId];
  74. const contextOverride = cfg.modelContextLimits?.[input.modelId];
  75. const contextLimit =
  76. contextOverride !== undefined && catalogModel?.contextWindowOptions?.includes(contextOverride)
  77. ? contextOverride
  78. : catalogModel?.limit?.context;
  79. return {
  80. provider: 'minimax_api',
  81. api: 'anthropic-messages',
  82. apiKey,
  83. baseUrl: normalizeProviderBaseUrl(
  84. 'anthropic-messages',
  85. cfg.baseURL?.trim() || MINIMAX_API_DEFAULT_BASE_URL,
  86. ),
  87. contextWindow:
  88. contextLimit ??
  89. (input.catalog.fromCatalog
  90. ? input.catalog.contextWindow
  91. : BYOK_FALLBACK_MODEL_LIMITS.contextWindow),
  92. maxTokens:
  93. catalogModel?.limit?.output ??
  94. (input.catalog.fromCatalog ? input.catalog.maxTokens : BYOK_FALLBACK_MODEL_LIMITS.maxTokens),
  95. };
  96. }
  97. export function planCustomProviderResolution(input: {
  98. byok: LocalByokProviderConfig | undefined;
  99. provider: string;
  100. providerKey: string;
  101. modelId: string;
  102. }): ByokResolutionPlan | undefined {
  103. const cfg = input.byok?.custom_provider?.[input.providerKey];
  104. if (!cfg) return undefined;
  105. // Disabled providers keep their config but must never be called.
  106. if (cfg.enabled === false) return undefined;
  107. // Custom models must come from the user's config: an unconfigured model id
  108. // (deleted, typo, dangling session reference) is rejected by the caller.
  109. const modelConfig = cfg.models?.[input.modelId];
  110. if (!modelConfig) return undefined;
  111. const authProvider =
  112. cfg.kind === 'oauth' || cfg.options?.authMode === 'oauth' ? input.providerKey : undefined;
  113. const apiKey = cfg.options?.apiKey?.trim();
  114. if (!apiKey && !authProvider) {
  115. throw new Error(`LocalModelResolver: api_key not configured for provider "${input.provider}".`);
  116. }
  117. const baseUrl = cfg.options?.baseURL?.trim();
  118. if (!baseUrl) {
  119. throw new Error(
  120. `LocalModelResolver: base_url not configured for provider "${input.provider}".`,
  121. );
  122. }
  123. const configHeaders = mergeProviderHeaders(
  124. readStringRecord(cfg.options?.headers),
  125. readStringRecord(modelConfig.headers),
  126. );
  127. const api = resolveCustomProviderApi(cfg.api);
  128. return {
  129. provider: input.provider,
  130. api,
  131. ...(apiKey ? { apiKey } : {}),
  132. ...(authProvider ? { authProvider, runtimeProvider: authProvider } : {}),
  133. baseUrl:
  134. api === 'openai-codex-responses'
  135. ? baseUrl.replace(/\/+$/u, '')
  136. : normalizeProviderBaseUrl(api as ModelProviderApi, baseUrl),
  137. contextWindow: modelConfig.limit?.context ?? BYOK_FALLBACK_MODEL_LIMITS.contextWindow,
  138. maxTokens: modelConfig.limit?.output ?? BYOK_FALLBACK_MODEL_LIMITS.maxTokens,
  139. ...(configHeaders ? { configHeaders } : {}),
  140. };
  141. }
  142. function resolveCustomProviderApi(value: unknown): Api {
  143. if (
  144. value === 'openai-completions' ||
  145. value === 'openai-responses' ||
  146. value === 'openai-codex-responses'
  147. ) {
  148. return value;
  149. }
  150. return 'anthropic-messages';
  151. }
  152. export function readStringRecord(value: unknown): Record<string, string> | undefined {
  153. if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
  154. const entries = Object.entries(value as Record<string, unknown>).filter(
  155. (entry): entry is [string, string] => typeof entry[1] === 'string',
  156. );
  157. return entries.length > 0 ? Object.fromEntries(entries) : undefined;
  158. }