application.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import type {
  2. McodeCodexOAuthStartResult,
  3. McodeCodexOAuthLoginOptions,
  4. McodeCodexOAuthStatus,
  5. McodeCreateProviderInput,
  6. McodeMiniMaxModelSource,
  7. McodeProviderRuntimePort,
  8. McodeSaveProviderCandidateInput,
  9. McodeSaveProviderCandidateResult,
  10. McodeProviderSnapshot,
  11. McodeProviderTestResult,
  12. McodeProviderView,
  13. McodeRuntimeProviderView,
  14. McodeUpdateProviderInput,
  15. } from './contract.js';
  16. import { isModelProviderApiFormat } from './contract.js';
  17. export class McodeProviderApplication {
  18. constructor(private readonly port: McodeProviderRuntimePort) {}
  19. async snapshot(
  20. options: { readonly includeCodexOAuth?: boolean } = {},
  21. ): Promise<McodeProviderSnapshot> {
  22. const [customProviders, minimaxStatus, minimaxModelSource, codexOAuthStatus] =
  23. await Promise.all([
  24. this.port.listUserModelProviders(),
  25. this.port.getMiniMaxApiKeyStatus(),
  26. this.port.getMiniMaxModelSource(),
  27. options.includeCodexOAuth ? this.port.getCodexOAuthStatus() : undefined,
  28. ]);
  29. return {
  30. minimaxModelSource,
  31. providers: [
  32. ...(!codexOAuthStatus || codexOAuthStatus.state === 'hidden'
  33. ? []
  34. : [normalizeCodexOAuthProvider(codexOAuthStatus)]),
  35. {
  36. providerId: 'minimax_oauth',
  37. name: 'MiniMax OAuth',
  38. kind: 'minimax-oauth',
  39. active: minimaxModelSource === 'token_plan',
  40. enabled: true,
  41. readOnly: true,
  42. hasApiKey: false,
  43. models: [],
  44. },
  45. {
  46. providerId: 'minimax_api',
  47. name: 'MiniMax API Key',
  48. kind: 'minimax-api-key',
  49. active: minimaxModelSource === 'minimax_api_key',
  50. enabled: true,
  51. readOnly: false,
  52. hasApiKey: minimaxStatus.hasApiKey,
  53. ...(minimaxStatus.maskedApiKey ? { maskedApiKey: minimaxStatus.maskedApiKey } : {}),
  54. ...(minimaxStatus.cachedStatus ? { status: minimaxStatus.cachedStatus } : {}),
  55. models: [],
  56. },
  57. ...customProviders.map(normalizeCustomProvider),
  58. ],
  59. };
  60. }
  61. setMiniMaxSource(source: McodeMiniMaxModelSource): Promise<McodeMiniMaxModelSource> {
  62. return this.port.setMiniMaxModelSource(source);
  63. }
  64. connectCodexOAuth(options?: McodeCodexOAuthLoginOptions): Promise<McodeCodexOAuthStartResult> {
  65. return this.port.startCodexOAuthLogin(options);
  66. }
  67. getCodexOAuthStatus(): Promise<McodeCodexOAuthStatus> {
  68. return this.port.getCodexOAuthStatus();
  69. }
  70. cancelCodexOAuthLogin(loginId: string): Promise<McodeCodexOAuthStatus> {
  71. return this.port.cancelCodexOAuthLogin(loginId);
  72. }
  73. async setMiniMaxApiKey(apiKey: string, saveAndUse = true): Promise<void> {
  74. await this.port.upsertMiniMaxApiKey({ apiKey, saveAndUse });
  75. }
  76. async create(input: McodeCreateProviderInput): Promise<void> {
  77. await this.port.createUserModelProvider(input);
  78. }
  79. saveCandidate(input: McodeSaveProviderCandidateInput): Promise<McodeSaveProviderCandidateResult> {
  80. return this.port.saveUserModelProviderCandidate(input);
  81. }
  82. async refreshModels(provider: McodeProviderView): Promise<number> {
  83. if (
  84. provider.kind !== 'custom' ||
  85. provider.readOnly ||
  86. !provider.baseUrl ||
  87. !provider.configRevision
  88. ) {
  89. throw new Error('Reopen /provider and select an editable connection.');
  90. }
  91. const candidate = {
  92. providerId: provider.providerId,
  93. expectedRevision: provider.configRevision,
  94. baseUrl: provider.baseUrl,
  95. };
  96. const discovered = await this.port.discoverUserModelsCandidate(candidate);
  97. const ids = new Set(provider.models.map(({ modelId }) => modelId));
  98. const added = discovered
  99. .map(({ modelId, displayName }) => ({
  100. modelId: modelId.trim(),
  101. ...(displayName ? { displayName } : {}),
  102. }))
  103. .filter(({ modelId }) => {
  104. if (!modelId || ids.has(modelId)) return false;
  105. ids.add(modelId);
  106. return true;
  107. });
  108. const firstAdded = added[0];
  109. if (!firstAdded) return 0;
  110. const result = await this.port.saveUserModelProviderCandidate({
  111. ...candidate,
  112. // IDs retain every saved model field, including disabled state and limits.
  113. models: [
  114. ...provider.models.map(({ modelId }) => ({ modelId })),
  115. ...added.map((model) => ({ ...model, configurationSource: 'discovered' as const })),
  116. ],
  117. modelId: firstAdded.modelId,
  118. skipConnectionTest: true,
  119. saveAndUse: false,
  120. });
  121. if (!result.success)
  122. throw new Error(result.status?.lastErrorMessage ?? 'Could not save refreshed models.');
  123. return added.length;
  124. }
  125. async update(input: McodeUpdateProviderInput): Promise<void> {
  126. await this.port.updateUserModelProvider(input);
  127. }
  128. async remove(providerId: string): Promise<void> {
  129. await this.port.deleteUserModelProvider(providerId);
  130. }
  131. test(providerId: string, modelId?: string): Promise<McodeProviderTestResult> {
  132. return modelId
  133. ? this.port.testUserModel(providerId, modelId)
  134. : this.port.testUserModelProvider(providerId);
  135. }
  136. }
  137. function normalizeCodexOAuthProvider(status: McodeCodexOAuthStatus): McodeProviderView {
  138. return {
  139. providerId: status.providerId,
  140. name: 'OpenAI Codex',
  141. kind: 'codex-oauth',
  142. active: false,
  143. enabled: true,
  144. readOnly: true,
  145. hasApiKey: false,
  146. models: [],
  147. status: {
  148. state: status.state,
  149. ...(status.error ? { lastErrorMessage: status.error } : {}),
  150. },
  151. };
  152. }
  153. function normalizeCustomProvider(provider: McodeRuntimeProviderView): McodeProviderView {
  154. const apiFormat = isModelProviderApiFormat(provider.apiFormat) ? provider.apiFormat : undefined;
  155. return {
  156. providerId: provider.providerId,
  157. name: provider.name?.trim() || provider.providerId,
  158. kind: 'custom',
  159. // A disabled provider is never "in use": Runtime drops it from the model
  160. // roster (`enabledCustomProviders`) and BYOK resolution refuses it, so a
  161. // leftover `selected` model must not render as the active source.
  162. active: Boolean(
  163. provider.enabled !== false &&
  164. provider.models?.some((model) => 'selected' in model && model.selected),
  165. ),
  166. enabled: provider.enabled !== false,
  167. readOnly: provider.kind === 'oauth',
  168. ...(provider.configRevision ? { configRevision: provider.configRevision } : {}),
  169. ...(apiFormat ? { apiFormat } : {}),
  170. ...(provider.baseUrl ? { baseUrl: provider.baseUrl } : {}),
  171. hasApiKey: Boolean(provider.hasApiKey),
  172. ...(provider.maskedApiKey ? { maskedApiKey: provider.maskedApiKey } : {}),
  173. models: (provider.models ?? []).map((model) => ({
  174. modelId: model.modelId,
  175. ...(model.displayName ? { displayName: model.displayName } : {}),
  176. ...(model.selected !== undefined ? { selected: model.selected } : {}),
  177. ...(model.contextLimit !== undefined ? { contextLimit: model.contextLimit } : {}),
  178. ...(model.maxOutputTokens !== undefined ? { maxOutputTokens: model.maxOutputTokens } : {}),
  179. ...(model.status ? { status: model.status } : {}),
  180. })),
  181. ...(provider.status ? { status: provider.status } : {}),
  182. };
  183. }
  184. export type {
  185. McodeCreateProviderInput,
  186. McodeProviderRuntimePort,
  187. McodeProviderSnapshot,
  188. McodeUpdateProviderInput,
  189. } from './contract.js';