add.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import path from 'node:path';
  2. import { rm } from 'node:fs/promises';
  3. import { type Command } from 'commander';
  4. import { loadRegistry, resolveComponent, listComponents } from '../lib/registry.js';
  5. import { getPackageRoot, getBundledFilePath } from '../lib/bundled.js';
  6. import { installFile } from '../lib/installer.js';
  7. import {
  8. readManifest,
  9. writeManifest,
  10. addFileToManifest,
  11. removeFileFromManifest,
  12. createEmptyManifest,
  13. type ManifestFile,
  14. type FileEntry,
  15. } from '../lib/manifest.js';
  16. import { log, info, warn, error, success, verbose } from '../ui/logger.js';
  17. import { createSpinner } from '../ui/spinner.js';
  18. import { computeFileHash } from '../lib/sha256.js';
  19. import { readCliVersion } from '../lib/version.js';
  20. import type { RegistryComponent } from '../lib/registry.js';
  21. // ── Types ─────────────────────────────────────────────────────────────────────
  22. export type AddOptions = {
  23. yolo: boolean;
  24. dryRun: boolean;
  25. verbose: boolean;
  26. force: boolean;
  27. };
  28. export type RemoveOptions = {
  29. yolo: boolean;
  30. dryRun: boolean;
  31. verbose: boolean;
  32. };
  33. // ── Pure helpers ──────────────────────────────────────────────────────────────
  34. /** Returns the destination path (relative to project root) for a component.
  35. * Uses component.path directly if it already starts with .opencode/,
  36. * otherwise prefixes with the correct subdirectory. */
  37. const getDestRelativePath = (component: RegistryComponent): string => {
  38. if (component.path.startsWith('.opencode/')) return component.path;
  39. const base = component.type === 'skill' ? '.opencode/skills' :
  40. component.type === 'agent' ? '.opencode/agent' :
  41. '.opencode/context';
  42. return path.join(base, component.path);
  43. };
  44. /** Builds a FileEntry for a newly installed component. */
  45. const buildFileEntry = (
  46. sha256: string,
  47. component: RegistryComponent,
  48. ): FileEntry => ({
  49. sha256,
  50. type: component.type,
  51. source: 'registry',
  52. installedAt: new Date().toISOString(),
  53. });
  54. /** Returns true if the file at destPath is already tracked in the manifest. */
  55. const isAlreadyInstalled = (
  56. manifest: ManifestFile | null,
  57. destRelativePath: string,
  58. ): boolean => manifest?.files[destRelativePath] !== undefined;
  59. // ── List display ──────────────────────────────────────────────────────────────
  60. /** Prints all available components grouped by type. */
  61. const printAvailableComponents = async (_projectRoot: string): Promise<void> => {
  62. const packageRoot = getPackageRoot();
  63. const registry = await loadRegistry(packageRoot);
  64. const all = listComponents(registry);
  65. const byType = {
  66. agent: all.filter((c) => c.type === 'agent'),
  67. context: all.filter((c) => c.type === 'context'),
  68. skill: all.filter((c) => c.type === 'skill'),
  69. };
  70. log('');
  71. log('Available components:');
  72. log('');
  73. for (const [type, components] of Object.entries(byType)) {
  74. if (components.length === 0) continue;
  75. log(` ${type.toUpperCase()}S`);
  76. for (const c of components) {
  77. log(` oac add ${type}:${c.id} — ${c.description}`);
  78. }
  79. log('');
  80. }
  81. log(`Run 'oac add <type>:<name>' to install a component.`);
  82. log(`Example: oac add context:react-patterns`);
  83. };
  84. // ── Core install logic ────────────────────────────────────────────────────────
  85. /** Resolves the component from the registry or exits with a clear error. */
  86. const resolveOrFail = async (
  87. ref: string,
  88. ): Promise<{ component: RegistryComponent; packageRoot: string }> => {
  89. const packageRoot = getPackageRoot();
  90. const registry = await loadRegistry(packageRoot);
  91. const component = resolveComponent(registry, ref);
  92. if (component === null) {
  93. error(`Component '${ref}' not found. Run 'oac add' to see available components.`);
  94. process.exit(1);
  95. }
  96. return { component, packageRoot };
  97. };
  98. /** Checks if the component is already installed and handles --force / warning. */
  99. const checkAlreadyInstalled = (
  100. manifest: ManifestFile | null,
  101. destRelativePath: string,
  102. force: boolean,
  103. ): boolean => {
  104. if (!isAlreadyInstalled(manifest, destRelativePath)) return false;
  105. if (!force) {
  106. warn(`Already installed. Use --force to reinstall.`);
  107. return true; // signal: abort
  108. }
  109. info('Reinstalling (--force).');
  110. return false; // signal: proceed
  111. };
  112. /** Performs the actual file copy and manifest update. */
  113. const performInstall = async (
  114. component: RegistryComponent,
  115. packageRoot: string,
  116. projectRoot: string,
  117. destRelativePath: string,
  118. manifest: ManifestFile,
  119. opts: AddOptions,
  120. ): Promise<void> => {
  121. const sourcePath = getBundledFilePath(packageRoot, component.path);
  122. const destPath = path.join(projectRoot, destRelativePath);
  123. const destDir = path.dirname(destRelativePath);
  124. info(`Installing ${component.type}:${component.id} → ${destDir}/`);
  125. if (opts.verbose) {
  126. verbose(`Source: ${sourcePath}`);
  127. verbose(`Destination: ${destPath}`);
  128. }
  129. const installOpts = {
  130. projectRoot,
  131. packageRoot,
  132. dryRun: opts.dryRun,
  133. yolo: opts.yolo,
  134. verbose: opts.verbose,
  135. };
  136. await installFile(sourcePath, destPath, installOpts);
  137. if (opts.dryRun) {
  138. info(`[dry-run] Would install ${component.type}:${component.id} to ${destDir}/`);
  139. return;
  140. }
  141. const sha256 = await computeFileHash(destPath);
  142. const entry = buildFileEntry(sha256, component);
  143. const updatedManifest = addFileToManifest(manifest, destRelativePath, entry);
  144. await writeManifest(projectRoot, updatedManifest);
  145. success(`Added ${component.id} to ${destDir}/`);
  146. };
  147. // ── Public command functions ──────────────────────────────────────────────────
  148. /**
  149. * Implements `oac add [ref]`.
  150. * With no ref: lists available components grouped by type.
  151. * With ref (e.g. `context:react-patterns`): installs the component.
  152. */
  153. export async function addCommand(
  154. ref: string | undefined,
  155. options: AddOptions,
  156. ): Promise<void> {
  157. const projectRoot = process.cwd();
  158. if (ref === undefined) {
  159. await printAvailableComponents(projectRoot);
  160. return;
  161. }
  162. const spinner = createSpinner(`Resolving ${ref}…`, { dryRun: options.dryRun });
  163. spinner.start();
  164. try {
  165. const { component, packageRoot } = await resolveOrFail(ref);
  166. spinner.stop();
  167. const manifest = (await readManifest(projectRoot)) ?? createEmptyManifest(readCliVersion());
  168. const destRelativePath = getDestRelativePath(component);
  169. const shouldAbort = checkAlreadyInstalled(manifest, destRelativePath, options.force);
  170. if (shouldAbort) return;
  171. await performInstall(component, packageRoot, projectRoot, destRelativePath, manifest, options);
  172. } catch (err: unknown) {
  173. spinner.fail();
  174. const msg = err instanceof Error ? err.message : String(err);
  175. error(`Failed to add '${ref}': ${msg}`);
  176. process.exit(1);
  177. }
  178. }
  179. /**
  180. * Implements `oac remove [ref]`.
  181. * Removes the component file from disk and updates the manifest.
  182. */
  183. export async function removeCommand(
  184. ref: string | undefined,
  185. options: RemoveOptions,
  186. ): Promise<void> {
  187. const projectRoot = process.cwd();
  188. if (ref === undefined) {
  189. error('Please specify a component to remove. Example: oac remove context:react-patterns');
  190. process.exit(1);
  191. }
  192. const spinner = createSpinner(`Resolving ${ref}…`, { dryRun: options.dryRun });
  193. spinner.start();
  194. try {
  195. const { component } = await resolveOrFail(ref);
  196. spinner.stop();
  197. const manifest = await readManifest(projectRoot);
  198. const destRelativePath = getDestRelativePath(component);
  199. if (!isAlreadyInstalled(manifest, destRelativePath)) {
  200. warn(`'${ref}' is not installed — nothing to remove.`);
  201. return;
  202. }
  203. const destPath = path.join(projectRoot, destRelativePath);
  204. if (options.verbose) {
  205. verbose(`Removing: ${destPath}`);
  206. }
  207. info(`Removing ${component.type}:${component.id} from ${path.dirname(destRelativePath)}/`);
  208. if (!options.dryRun) {
  209. await rm(destPath, { recursive: true, force: true });
  210. const updatedManifest = removeFileFromManifest(manifest!, destRelativePath);
  211. await writeManifest(projectRoot, updatedManifest);
  212. success(`Removed ${component.id}`);
  213. } else {
  214. info(`[dry-run] Would remove ${destPath}`);
  215. }
  216. } catch (err: unknown) {
  217. spinner.fail();
  218. const msg = err instanceof Error ? err.message : String(err);
  219. error(`Failed to remove '${ref}': ${msg}`);
  220. process.exit(1);
  221. }
  222. }
  223. // ── Commander registration ────────────────────────────────────────────────────
  224. /**
  225. * Registers the `add` and `remove` subcommands on the given Commander program.
  226. */
  227. export function registerAddCommand(program: Command): void {
  228. program
  229. .command('add [ref]')
  230. .description('Add a component (agent, context, or skill). Example: oac add context:react-patterns')
  231. .option('--force', 'Reinstall even if already installed', false)
  232. .option('--dry-run', 'Show what would happen without making changes', false)
  233. .option('--yolo', 'Skip safety checks and overwrite user-modified files', false)
  234. .option('--verbose', 'Show source and destination paths', false)
  235. .action(async (ref: string | undefined, opts: { force?: boolean; dryRun?: boolean; yolo?: boolean; verbose?: boolean }) => {
  236. await addCommand(ref, {
  237. force: opts.force ?? false,
  238. dryRun: opts.dryRun ?? false,
  239. yolo: opts.yolo ?? false,
  240. verbose: opts.verbose ?? false,
  241. });
  242. });
  243. program
  244. .command('remove [ref]')
  245. .description('Remove an installed component. Example: oac remove context:react-patterns')
  246. .option('--dry-run', 'Show what would happen without making changes', false)
  247. .option('--yolo', 'Skip safety checks', false)
  248. .option('--verbose', 'Show file paths', false)
  249. .action(async (ref: string | undefined, opts: { dryRun?: boolean; yolo?: boolean; verbose?: boolean }) => {
  250. await removeCommand(ref, {
  251. dryRun: opts.dryRun ?? false,
  252. yolo: opts.yolo ?? false,
  253. verbose: opts.verbose ?? false,
  254. });
  255. });
  256. }