plugin-command.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import path from 'node:path';
  2. import { McodePluginApplication } from '../plugin/application.js';
  3. import type {
  4. McodePluginCatalog,
  5. McodePluginCliRequest,
  6. McodePluginMarketplace,
  7. McodePluginView,
  8. } from '../plugin/contract.js';
  9. import { prepareTuiDataDir } from '../runtime/data-dir.js';
  10. import { createTuiRuntime, shutdownTuiRuntime } from '../runtime/lifecycle.js';
  11. interface McodePluginCommandApplication {
  12. catalog(input: {
  13. readonly includeAvailable: boolean;
  14. readonly marketplace?: McodePluginMarketplace;
  15. }): Promise<McodePluginCatalog>;
  16. install(plugin: McodePluginView): Promise<McodePluginView>;
  17. remove(plugin: McodePluginView): Promise<McodePluginView>;
  18. setEnabled(plugin: McodePluginView, enabled: boolean): Promise<McodePluginView>;
  19. refresh(): Promise<void>;
  20. }
  21. interface McodePluginCommandContext {
  22. readonly application: McodePluginCommandApplication;
  23. readonly dataDir: string;
  24. shutdown(): Promise<void>;
  25. }
  26. export interface RunMcodePluginCommandOptions {
  27. readonly version: string;
  28. readonly request: McodePluginCliRequest;
  29. readonly lane?: string;
  30. readonly createContext?: (lane?: string) => Promise<McodePluginCommandContext>;
  31. }
  32. export async function runMcodePluginCommand(
  33. options: RunMcodePluginCommandOptions,
  34. ): Promise<string> {
  35. const context = options.createContext
  36. ? await options.createContext(options.lane)
  37. : await createPluginCommandContext(options.version, options.lane);
  38. try {
  39. const request = options.request;
  40. if (request.action === 'marketplace-list') {
  41. const marketplaces = [
  42. { name: 'official', kind: 'registry' },
  43. { name: 'local', kind: 'directory', path: path.join(context.dataDir, 'plugins') },
  44. ];
  45. return request.json
  46. ? JSON.stringify(marketplaces, null, 2)
  47. : marketplaces
  48. .map(
  49. (entry) => `${entry.name}\t${entry.kind}${'path' in entry ? `\t${entry.path}` : ''}`,
  50. )
  51. .join('\n');
  52. }
  53. if (request.action === 'marketplace-upgrade') {
  54. await context.application.refresh();
  55. const result = { marketplace: 'all', refreshed: true };
  56. return request.json ? JSON.stringify(result, null, 2) : 'Refreshed all Plugin sources.';
  57. }
  58. if (request.action !== 'list') {
  59. const { name, marketplace } = parseSelector(request.selector, request.marketplace);
  60. const catalog = await context.application.catalog({
  61. includeAvailable: request.action === 'add',
  62. marketplace,
  63. });
  64. const plugin = selectPlugin(
  65. request.action === 'add' ? [...catalog.installed, ...catalog.available] : catalog.installed,
  66. name,
  67. marketplace,
  68. );
  69. const result =
  70. request.action === 'add'
  71. ? await context.application.install(plugin)
  72. : request.action === 'remove'
  73. ? await context.application.remove(plugin)
  74. : await context.application.setEnabled(plugin, request.action === 'enable');
  75. return request.json ? JSON.stringify(toCliPlugin(result), null, 2) : formatPlugin(result);
  76. }
  77. const catalog = await context.application.catalog({
  78. includeAvailable: Boolean(request.available),
  79. marketplace: request.marketplace,
  80. });
  81. if (request.json) {
  82. return JSON.stringify(
  83. {
  84. installed: catalog.installed.map(toCliPlugin),
  85. available: catalog.available.map(toCliPlugin),
  86. },
  87. null,
  88. 2,
  89. );
  90. }
  91. return formatPluginRows(catalog);
  92. } finally {
  93. await context.shutdown();
  94. }
  95. }
  96. function toCliPlugin(plugin: McodePluginView) {
  97. return {
  98. pluginId: plugin.pluginId,
  99. name: plugin.name,
  100. displayName: plugin.displayName,
  101. marketplaceName: plugin.marketplace,
  102. ...(plugin.version ? { version: plugin.version } : {}),
  103. ...(plugin.description ? { description: plugin.description } : {}),
  104. ...(plugin.author ? { author: plugin.author } : {}),
  105. installed: plugin.installed,
  106. enabled: plugin.enabled,
  107. capabilities: plugin.capabilities,
  108. };
  109. }
  110. function formatPluginRows(catalog: McodePluginCatalog): string {
  111. return [...catalog.installed, ...catalog.available]
  112. .map((plugin) => {
  113. const marker = plugin.enabled ? '[*]' : plugin.installed ? '[-]' : '[ ]';
  114. const state = plugin.installed ? (plugin.enabled ? 'enabled' : 'disabled') : 'available';
  115. return `${marker} ${plugin.pluginId}\t${state}`;
  116. })
  117. .join('\n');
  118. }
  119. function formatPlugin(plugin: McodePluginView): string {
  120. return formatPluginRows({
  121. installed: plugin.installed ? [plugin] : [],
  122. available: plugin.installed ? [] : [plugin],
  123. });
  124. }
  125. function parseSelector(
  126. selector: string,
  127. explicitMarketplace?: McodePluginMarketplace,
  128. ): { readonly name: string; readonly marketplace?: McodePluginMarketplace } {
  129. const match = /^([^@]+?)(?:@(official|local))?$/.exec(selector.trim());
  130. if (!match?.[1]) throw new Error(`Invalid Plugin selector: ${selector}`);
  131. const marketplace = match[2] as McodePluginMarketplace | undefined;
  132. if (marketplace && explicitMarketplace && marketplace !== explicitMarketplace) {
  133. throw new Error(
  134. `Plugin selector marketplace conflicts with --marketplace ${explicitMarketplace}.`,
  135. );
  136. }
  137. return { name: match[1], marketplace: marketplace ?? explicitMarketplace };
  138. }
  139. function selectPlugin(
  140. plugins: readonly McodePluginView[],
  141. name: string,
  142. marketplace?: McodePluginMarketplace,
  143. ): McodePluginView {
  144. const matches = plugins.filter(
  145. (plugin) =>
  146. plugin.name === name && (marketplace === undefined || plugin.marketplace === marketplace),
  147. );
  148. if (matches.length === 0)
  149. throw new Error(`Plugin not found: ${name}${marketplace ? `@${marketplace}` : ''}`);
  150. if (matches.length > 1) {
  151. throw new Error(
  152. `Plugin ${name} matches multiple marketplaces; use ${name}@official or ${name}@local.`,
  153. );
  154. }
  155. return matches[0] as McodePluginView;
  156. }
  157. async function createPluginCommandContext(
  158. version: string = 'unknown',
  159. lane?: string,
  160. ): Promise<McodePluginCommandContext> {
  161. const dataDir = await prepareTuiDataDir();
  162. const runtime = await createTuiRuntime({
  163. dataDir,
  164. workspaceDir: process.cwd(),
  165. version,
  166. surface: 'headless',
  167. ...(lane ? { lane } : {}),
  168. });
  169. return {
  170. application: new McodePluginApplication(runtime.adapter),
  171. dataDir,
  172. shutdown: async () => {
  173. await shutdownTuiRuntime(runtime);
  174. },
  175. };
  176. }