provider-command.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import { McodeProviderApplication } from '../provider/application.js';
  2. import type { McodeProviderApiFormat, McodeProviderSnapshot } from '../provider/contract.js';
  3. import { prepareTuiDataDir } from '../runtime/data-dir.js';
  4. import { createTuiRuntime, shutdownTuiRuntime } from '../runtime/lifecycle.js';
  5. import { formatTuiActionFailure } from '../user-facing-failure.js';
  6. export type McodeProviderCliRequest =
  7. | { readonly action: 'list'; readonly json?: boolean }
  8. | {
  9. readonly action: 'add';
  10. readonly name: string;
  11. readonly baseUrl: string;
  12. readonly apiFormat: McodeProviderApiFormat;
  13. readonly models: readonly string[];
  14. readonly contextLimit?: number;
  15. readonly outputLimit?: number;
  16. readonly supportImage?: boolean;
  17. readonly apiKeyEnv?: string;
  18. readonly saveAndUse?: boolean;
  19. }
  20. | { readonly action: 'remove'; readonly providerId: string; readonly confirmed: boolean }
  21. | {
  22. readonly action: 'test';
  23. readonly providerId: string;
  24. readonly modelId?: string;
  25. readonly json?: boolean;
  26. }
  27. | { readonly action: 'set-minimax-key'; readonly apiKeyEnv?: string }
  28. | { readonly action: 'use'; readonly source: 'token_plan' | 'minimax_api_key' };
  29. interface McodeProviderCommandContext {
  30. readonly application: McodeProviderApplication;
  31. shutdown(): Promise<void>;
  32. }
  33. export interface RunMcodeProviderCommandOptions {
  34. readonly version: string;
  35. readonly request: McodeProviderCliRequest;
  36. readonly environment?: Readonly<Record<string, string | undefined>>;
  37. readonly workspaceDir?: string;
  38. readonly lane?: string;
  39. readonly createContext?: (lane?: string) => Promise<McodeProviderCommandContext>;
  40. }
  41. export async function runMcodeProviderCommand(
  42. options: RunMcodeProviderCommandOptions,
  43. ): Promise<string> {
  44. const context = options.createContext
  45. ? await options.createContext(options.lane)
  46. : await createProviderCommandContext(options.version, options.workspaceDir, options.lane);
  47. try {
  48. const { request } = options;
  49. if (request.action === 'list') {
  50. return formatSnapshot(await context.application.snapshot(), Boolean(request.json));
  51. }
  52. if (request.action === 'add') {
  53. const envName = request.apiKeyEnv?.trim() || 'MCODE_PROVIDER_API_KEY';
  54. const apiKey = (options.environment ?? process.env)[envName]?.trim();
  55. if (!apiKey) {
  56. throw new Error(
  57. `Provider API key is missing. Set ${envName} or pass --api-key-env <name>.`,
  58. );
  59. }
  60. const input = {
  61. name: request.name,
  62. baseUrl: request.baseUrl,
  63. apiKey,
  64. apiFormat: request.apiFormat,
  65. models: request.models.map((modelId) => ({
  66. modelId,
  67. ...(request.supportImage ? { capabilities: { support_image: true } } : {}),
  68. ...(request.contextLimit !== undefined || request.outputLimit !== undefined
  69. ? {
  70. limit: {
  71. ...(request.contextLimit !== undefined ? { context: request.contextLimit } : {}),
  72. ...(request.outputLimit !== undefined ? { output: request.outputLimit } : {}),
  73. },
  74. }
  75. : {}),
  76. })),
  77. };
  78. if (request.saveAndUse) {
  79. const modelId = request.models[0];
  80. if (!modelId) throw new Error('At least one --model <id> is required.');
  81. const result = await context.application.saveCandidate({
  82. ...input,
  83. modelId,
  84. saveAndUse: true,
  85. });
  86. if (!result.success) {
  87. throw new Error(
  88. formatTuiActionFailure(
  89. result.status?.lastErrorMessage ?? result.status?.state ?? 'Connection unavailable',
  90. {
  91. summary: 'Provider connection test failed. Nothing was saved or selected.',
  92. nextStep:
  93. 'Check the URL, API key, and first model ID, then retry; omit --use to save without testing.',
  94. },
  95. ),
  96. );
  97. }
  98. return `Provider added and selected: ${request.name}`;
  99. }
  100. await context.application.create(input);
  101. return `Provider added: ${request.name}`;
  102. }
  103. if (request.action === 'remove') {
  104. if (!request.confirmed) {
  105. throw new Error('Refusing to remove a provider without --yes.');
  106. }
  107. await context.application.remove(request.providerId);
  108. return `Provider removed: ${request.providerId}`;
  109. }
  110. if (request.action === 'test') {
  111. if (request.providerId === 'minimax_oauth') {
  112. const message = 'MiniMax OAuth sign-in and connectivity are managed by /login.';
  113. if (request.json) {
  114. return JSON.stringify(
  115. {
  116. success: false,
  117. status: { state: 'unsupported', lastErrorMessage: message },
  118. },
  119. null,
  120. 2,
  121. );
  122. }
  123. return formatTuiActionFailure(message, {
  124. summary: 'MiniMax OAuth provider test skipped.',
  125. nextStep: 'Run /login to manage Token Plan sign-in.',
  126. });
  127. }
  128. const result = await context.application.test(request.providerId, request.modelId);
  129. if (request.json) return JSON.stringify(result, null, 2);
  130. return result.success
  131. ? `Provider available: ${request.providerId}${request.modelId ? `/${request.modelId}` : ''}`
  132. : formatTuiActionFailure(result.status.lastErrorMessage ?? result.status.state, {
  133. summary: 'Provider test failed.',
  134. nextStep: 'Check the URL, API key, and model ID, then retry.',
  135. });
  136. }
  137. if (request.action === 'set-minimax-key') {
  138. const envName = request.apiKeyEnv?.trim() || 'MCODE_PROVIDER_API_KEY';
  139. const apiKey = (options.environment ?? process.env)[envName]?.trim();
  140. if (!apiKey) {
  141. throw new Error(`MiniMax API key is missing. Set ${envName} or pass --api-key-env <name>.`);
  142. }
  143. await context.application.setMiniMaxApiKey(apiKey);
  144. return 'MiniMax API Key saved and selected.';
  145. }
  146. await context.application.setMiniMaxSource(request.source);
  147. return request.source === 'token_plan' ? 'Using MiniMax Token Plan.' : 'Using MiniMax API Key.';
  148. } finally {
  149. await context.shutdown();
  150. }
  151. }
  152. async function createProviderCommandContext(
  153. version: string,
  154. workspaceDir = process.cwd(),
  155. lane?: string,
  156. ): Promise<McodeProviderCommandContext> {
  157. const runtime = await createTuiRuntime({
  158. dataDir: await prepareTuiDataDir(),
  159. workspaceDir,
  160. version,
  161. surface: 'headless',
  162. ...(lane ? { lane } : {}),
  163. });
  164. return {
  165. application: new McodeProviderApplication(runtime.adapter),
  166. shutdown: async () => {
  167. await shutdownTuiRuntime(runtime);
  168. },
  169. };
  170. }
  171. function formatSnapshot(snapshot: McodeProviderSnapshot, json: boolean): string {
  172. if (json) return JSON.stringify(snapshot, null, 2);
  173. const lines = snapshot.providers.map((provider) => {
  174. const state = provider.active ? 'active' : provider.enabled ? 'enabled' : 'disabled';
  175. const credential =
  176. provider.kind === 'minimax-oauth'
  177. ? 'managed login'
  178. : provider.hasApiKey
  179. ? (provider.maskedApiKey ?? 'key saved')
  180. : 'no key';
  181. return `${provider.active ? '*' : ' '} ${provider.providerId}\t${state}\t${credential}`;
  182. });
  183. return lines.join('\n');
  184. }