model-availability.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. // Route-aware model availability.
  2. //
  3. // A model id alone says nothing about whether it can be called: the same
  4. // `minimax/MiniMax-M2.7` is a retired token-plan model on one backend and a
  5. // perfectly callable BYOK model on a user's own API key. This module owns the
  6. // one answer to "may this route call this model", so the local model list, the
  7. // save entry (`selectModel`) and the Turn execution gate cannot disagree and
  8. // let a locally-known model reach a backend that retired it.
  9. //
  10. // Pure by contract: no fs, no process state, no runtime types. Callers pass a
  11. // structured read-only view of the effective config plus the runtime PresetKey.
  12. // Do not use a resolver's generic limit fallback as a validity signal — an
  13. // unknown model resolving to default limits is exactly the bug this replaces.
  14. import { MINIMAX_API_MODEL_CATALOG, type PresetKey } from './config.js';
  15. import { resolveProviderAuthMode } from './provider-auth-mode.js';
  16. /** Reserved provider ids, mirrored by the local-runtime model-key parsers. */
  17. export const MANAGED_MINIMAX_PROVIDER_ID = 'minimax';
  18. export const MINIMAX_API_PROVIDER_ID = 'minimax_api';
  19. export const CUSTOM_PROVIDER_ID_PREFIX = 'custom_provider:';
  20. /** Which upstream a selected model would actually be called through. */
  21. export type ModelCallRoute =
  22. | 'managed_token_plan'
  23. | 'minimax_api_key'
  24. | 'custom_provider'
  25. | 'configured_provider';
  26. /** Where the selected model came from; decides the failure handling. */
  27. export type ModelSelectionSource = 'explicit_request' | 'session_override' | 'config_default';
  28. export type ModelAvailabilityErrorCode =
  29. | 'MODEL_NOT_AVAILABLE_FOR_ROUTE'
  30. | 'DEFAULT_MODEL_NOT_AVAILABLE_FOR_ROUTE';
  31. export interface ModelAvailabilityProviderView {
  32. readonly options?: {
  33. readonly authMode?: unknown;
  34. readonly baseURL?: unknown;
  35. readonly [key: string]: unknown;
  36. };
  37. readonly models?: Readonly<Record<string, { readonly enabled?: unknown }>>;
  38. readonly model_order?: unknown;
  39. }
  40. export interface ModelAvailabilityCustomProviderView extends ModelAvailabilityProviderView {
  41. readonly enabled?: boolean;
  42. }
  43. /** Read-only projection of the effective config this module needs. */
  44. export interface ModelAvailabilityConfigView {
  45. readonly provider?: Readonly<Record<string, ModelAvailabilityProviderView>>;
  46. readonly minimax_api?: { readonly apiKey?: string; readonly baseURL?: string };
  47. readonly custom_provider?: Readonly<Record<string, ModelAvailabilityCustomProviderView>>;
  48. readonly minimaxModelSource?: 'token_plan' | 'minimax_api_key';
  49. }
  50. export interface ModelAvailabilityInput {
  51. readonly config: ModelAvailabilityConfigView;
  52. readonly providerId: string;
  53. readonly modelId: string;
  54. readonly preset: PresetKey;
  55. readonly source: ModelSelectionSource;
  56. }
  57. export type ModelAvailability =
  58. | { readonly available: true; readonly route: ModelCallRoute }
  59. | {
  60. readonly available: false;
  61. readonly route: ModelCallRoute;
  62. readonly code: ModelAvailabilityErrorCode;
  63. readonly message: string;
  64. };
  65. /** Shared cache-compatibility policy for MiniMax's first-party Messages route. */
  66. export function isFirstPartyMinimaxMessagesRoute(api: string, providerId: string): boolean {
  67. return (
  68. api === 'anthropic-messages' &&
  69. (providerId === MANAGED_MINIMAX_PROVIDER_ID || providerId === MINIMAX_API_PROVIDER_ID)
  70. );
  71. }
  72. /**
  73. * The route a provider id resolves to. `provider.minimax` is not a fixed
  74. * route: with `minimaxModelSource = 'minimax_api_key'` the very same builtin
  75. * entry is called with the user's own key, so it must be judged against the
  76. * API catalog rather than the managed active set.
  77. */
  78. export function resolveModelCallRoute(
  79. config: ModelAvailabilityConfigView,
  80. providerId: string,
  81. ): ModelCallRoute {
  82. if (providerId === MINIMAX_API_PROVIDER_ID) return 'minimax_api_key';
  83. if (providerId.startsWith(CUSTOM_PROVIDER_ID_PREFIX)) return 'custom_provider';
  84. if (providerId !== MANAGED_MINIMAX_PROVIDER_ID) return 'configured_provider';
  85. if (config.minimaxModelSource === 'minimax_api_key') return 'minimax_api_key';
  86. const options = config.provider?.[providerId]?.options;
  87. const authMode = resolveProviderAuthMode({
  88. authMode: options?.authMode,
  89. baseURL: options?.baseURL,
  90. }).authMode;
  91. return authMode === 'managed-login' ? 'managed_token_plan' : 'configured_provider';
  92. }
  93. /**
  94. * Model ids the given provider id may actually call right now. The managed
  95. * token-plan route is capped by the preset active set; every other route keeps
  96. * what the user configured (a token-plan retirement must not shrink a BYOK
  97. * route).
  98. */
  99. export function listRouteModelIds(
  100. config: ModelAvailabilityConfigView,
  101. providerId: string,
  102. _preset: PresetKey,
  103. ): readonly string[] {
  104. const route = resolveModelCallRoute(config, providerId);
  105. switch (route) {
  106. case 'managed_token_plan': {
  107. return configuredModelIds(config.provider?.[providerId], true);
  108. }
  109. case 'minimax_api_key': {
  110. return Object.keys(MINIMAX_API_MODEL_CATALOG);
  111. }
  112. case 'custom_provider': {
  113. const provider = config.custom_provider?.[providerId.slice(CUSTOM_PROVIDER_ID_PREFIX.length)];
  114. if (!provider || provider.enabled === false) return [];
  115. return configuredModelIds(provider);
  116. }
  117. case 'configured_provider':
  118. return configuredModelIds(config.provider?.[providerId]);
  119. }
  120. }
  121. /** The single availability answer shared by list, save and Turn execution. */
  122. export function resolveModelAvailability(input: ModelAvailabilityInput): ModelAvailability {
  123. const route = resolveModelCallRoute(input.config, input.providerId);
  124. const modelId = input.modelId.trim();
  125. if (
  126. modelId.length > 0 &&
  127. listRouteModelIds(input.config, input.providerId, input.preset).includes(modelId)
  128. ) {
  129. return { available: true, route };
  130. }
  131. return {
  132. available: false,
  133. route,
  134. code:
  135. input.source === 'config_default'
  136. ? 'DEFAULT_MODEL_NOT_AVAILABLE_FOR_ROUTE'
  137. : 'MODEL_NOT_AVAILABLE_FOR_ROUTE',
  138. message: `Model "${input.providerId}/${input.modelId}" is not available for the "${route}" route (preset ${input.preset}).`,
  139. };
  140. }
  141. function configuredModelIds(
  142. provider: ModelAvailabilityProviderView | undefined,
  143. applyModelOrder = false,
  144. ): readonly string[] {
  145. const configured = Object.entries(provider?.models ?? {})
  146. .filter(([, model]) => model?.enabled !== false)
  147. .map(([modelId]) => modelId);
  148. const order = provider?.model_order;
  149. if (!applyModelOrder || !Array.isArray(order) || !order.every((id) => typeof id === 'string')) {
  150. return configured;
  151. }
  152. const remaining = new Set(configured);
  153. const ordered = order.filter((modelId) => remaining.delete(modelId));
  154. return [...ordered, ...configured.filter((modelId) => remaining.has(modelId))];
  155. }