agent-sync.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. #!/usr/bin/env node
  2. // agent-sync — installs the bundled skills and agent prompts into the canonical
  3. // user-level directory (~/.agents) and links the skills into every detected AI
  4. // agent's own directory (same architecture as the vercel-labs/skills CLI).
  5. // Agent prompts are managed only inside ~/.agents/agents via plain copies
  6. // (file links on windows require privileges).
  7. // Selection is explicit (--all, --skills, --agents, --targets): without a
  8. // selection flag the tool prints its help. See HELP for the full surface.
  9. import { createHash } from 'node:crypto';
  10. import {
  11. cpSync, copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync,
  12. readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync,
  13. } from 'node:fs';
  14. import { homedir, platform } from 'node:os';
  15. import { basename, dirname, join, relative } from 'node:path';
  16. import { fileURLToPath } from 'node:url';
  17. const EXIT_OK = 0;
  18. const EXIT_FAILURE = 1;
  19. const EXIT_USAGE = 2;
  20. const IS_WINDOWS = platform() === 'win32';
  21. const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
  22. const SOURCE_SKILLS_DIR = join(PACKAGE_ROOT, 'skills');
  23. const SOURCE_AGENTS_DIR = join(PACKAGE_ROOT, 'agents');
  24. const SOURCE_SYSTEM_PROMPT = join(PACKAGE_ROOT, 'SYSTEM_PROMPT.md');
  25. const CANONICAL_SKILLS_DIR = join(homedir(), '.agents', 'skills');
  26. const CANONICAL_AGENTS_DIR = join(homedir(), '.agents', 'agents');
  27. // Frontmatter prepended to SYSTEM_PROMPT.md for rule-based agents that require
  28. // an always-on wrapper (cursor .mdc, windsurf rules).
  29. const SYS_CURSOR_FRONTMATTER = '---\ndescription: oh-my-skills system prompt\nalwaysApply: true\n---\n\n';
  30. const SYS_WINDSURF_FRONTMATTER = '---\ntrigger: always_on\n---\n\n';
  31. const HELP = `agent-sync — installs bundled skills and agent prompts into the
  32. canonical ~/.agents directory and links them into the AI agents detected
  33. on the machine.
  34. Usage:
  35. agent-sync --all [--check] [--targets [<names>]]
  36. agent-sync --skills [<names>] [--agents [<names>]] [--sys] [--check] [--targets [<names>]]
  37. agent-sync --list
  38. agent-sync --help
  39. A selection flag without a value covers its whole dimension: --skills alone
  40. selects every bundled skill, --agents alone every prompt, --sys the system
  41. prompt, --targets alone every detected agent. With a comma-separated value
  42. only the listed names are used. Flags combine: --skills commit --targets
  43. claude,pi syncs just the commit skill into Claude Code and pi. Without any
  44. selection flag agent-sync prints this help.
  45. The --sys dimension installs the repository-level SYSTEM_PROMPT.md as the
  46. global system prompt of every detected agent, renamed to each target's
  47. standard filename (CLAUDE.md, APPEND_SYSTEM.md, AGENTS.md, *.mdc, ...).
  48. It is always copied, never linked, and never stored in ~/.agents.
  49. --check dry-run, reports drift without writing anything (exit 1 on drift)
  50. Exit codes: ${EXIT_OK} ok or help, ${EXIT_FAILURE} drift (dry-run) or failure, ${EXIT_USAGE} usage error.`;
  51. // Resolves the Claude Code config dir, honoring CLAUDE_CONFIG_DIR when set.
  52. function claudeBase() {
  53. return process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude');
  54. }
  55. // Resolves a fixed directory under the user home (lazy, re-evaluated per run).
  56. function homeDir(dir) {
  57. return () => join(homedir(), dir);
  58. }
  59. // Supported AI agents: base() proves installation when the directory exists,
  60. // skillsSub/agentsSub are the subdirectories receiving our links. Agent prompts
  61. // are linked only where the convention is verified (claude); pi gets a minimal
  62. // manifest instead (see writePiManifests) because its manifests carry
  63. // per-machine config such as model and thinking.
  64. // sys is the --sys destination relative to base(): the bundled SYSTEM_PROMPT.md
  65. // is copied there (renamed, plain copy, never linked) or wrapped with a
  66. // frontmatter when the target expects one. null = no system prompt support.
  67. const AGENT_REGISTRY = [
  68. { name: 'claude', base: claudeBase, skillsSub: 'skills', agentsSub: 'agents', sys: { file: 'CLAUDE.md' } },
  69. { name: 'pi', base: homeDir(join('.pi', 'agent')), skillsSub: 'skills', agentsSub: 'agents', sys: { file: 'APPEND_SYSTEM.md' } },
  70. { name: 'codex', base: homeDir('.codex'), skillsSub: 'skills', sys: { file: 'AGENTS.md' } },
  71. { name: 'opencode', base: homeDir('.opencode'), skillsSub: 'skills', sys: { file: 'AGENTS.md' } },
  72. { name: 'cursor', base: homeDir('.cursor'), skillsSub: 'skills', sys: { file: join('rules', 'oh-my-skills.mdc'), frontmatter: SYS_CURSOR_FRONTMATTER } },
  73. { name: 'trae', base: homeDir('.trae'), skillsSub: 'skills', sys: null },
  74. { name: 'windsurf', base: homeDir('.windsurf'), skillsSub: 'skills', sys: { file: join('rules', 'oh-my-skills.md'), frontmatter: SYS_WINDSURF_FRONTMATTER } },
  75. { name: 'aider-desk', base: homeDir('.aider-desk'), skillsSub: 'skills', sys: null },
  76. ];
  77. // Prints a usage error and exits with the usage exit code.
  78. function fail(message) {
  79. console.error(`${message}\nRun 'agent-sync --help' for usage.`);
  80. process.exit(EXIT_USAGE);
  81. }
  82. // Returns the names of the bundled skills (directories under skills/).
  83. function bundledSkillNames() {
  84. return readdirSync(SOURCE_SKILLS_DIR, { withFileTypes: true })
  85. .filter((entry) => entry.isDirectory())
  86. .map((entry) => entry.name);
  87. }
  88. // Returns the file names of the bundled agent prompts (*.md under agents/).
  89. function bundledAgentFiles() {
  90. return readdirSync(SOURCE_AGENTS_DIR).filter((name) => name.endsWith('.md'));
  91. }
  92. // Dimension flags hold three states: null (flag absent), true (whole
  93. // dimension) or an array of names. A repeated flag accumulates names, and a
  94. // valueless occurrence widens the dimension to everything.
  95. function mergeDimension(current, value) {
  96. if (current === true || value === null) return true;
  97. return [...(current ?? []), ...value];
  98. }
  99. const DIMENSION_FLAGS = { '--skills': 'skills', '--agents': 'agents', '--targets': 'targets', '--sys': 'sys' };
  100. // Parses the command line into a run plan (syntax only: names are validated
  101. // later against the bundled content). Selection flags are --all, --skills,
  102. // --agents, --targets and --sys; every other flag is a modifier.
  103. function parseArgs(argv) {
  104. const plan = { help: false, list: false, dryRun: false, all: false, skills: null, agents: null, targets: null, sys: null };
  105. const optionalList = (index, flag) => {
  106. const value = argv[index + 1];
  107. if (!value || value.startsWith('--')) return null;
  108. const names = value.split(',').map((name) => name.trim()).filter(Boolean);
  109. if (names.length === 0) fail(`error: ${flag} received an empty list of names`);
  110. return names;
  111. };
  112. for (let i = 0; i < argv.length; i += 1) {
  113. const arg = argv[i];
  114. if (arg === '--help' || arg === '-h') plan.help = true;
  115. else if (arg === '--list') plan.list = true;
  116. else if (arg === '--check') plan.dryRun = true;
  117. else if (arg === '--all') plan.all = true;
  118. else if (DIMENSION_FLAGS[arg]) {
  119. const key = DIMENSION_FLAGS[arg];
  120. const value = optionalList(i, arg);
  121. if (key === 'sys' && value !== null) fail('error: --sys takes no value');
  122. plan[key] = mergeDimension(plan[key], value);
  123. if (value !== null) i += 1;
  124. }
  125. else fail(`error: unknown argument '${arg}'`);
  126. }
  127. return plan;
  128. }
  129. // Validates the requested names against the bundled content and the agent
  130. // registry, then resolves the effective selection. A dimension set to true
  131. // expands to everything; prompt names are given without extension (gv-dev)
  132. // and mapped to their bundled files (gv-dev.md).
  133. function resolveSelection(plan) {
  134. const skillNames = bundledSkillNames();
  135. const agentFiles = bundledAgentFiles();
  136. const registryNames = AGENT_REGISTRY.map((agent) => agent.name);
  137. const pickSkill = (name) => {
  138. if (!skillNames.includes(name)) fail(`error: unknown skill '${name}' (available: ${skillNames.join(', ')})`);
  139. return name;
  140. };
  141. const pickAgent = (name) => {
  142. const file = agentFiles.find((candidate) => basename(candidate, '.md') === name);
  143. if (!file) fail(`error: unknown agent '${name}' (available: ${agentFiles.map((f) => basename(f, '.md')).join(', ')})`);
  144. return file;
  145. };
  146. const pickTarget = (name) => {
  147. if (!registryNames.includes(name)) fail(`error: unknown target '${name}' (available: ${registryNames.join(', ')})`);
  148. return name;
  149. };
  150. return {
  151. skills: plan.all || plan.skills === true ? skillNames : (plan.skills ?? []).map(pickSkill),
  152. agents: plan.all || plan.agents === true ? agentFiles : (plan.agents ?? []).map(pickAgent),
  153. targets: plan.targets === true || !plan.targets ? null : plan.targets.map(pickTarget),
  154. sys: Boolean(plan.all || plan.sys),
  155. };
  156. }
  157. // Prints the bundled catalog plus the AI agents detected on this machine.
  158. function printCatalog() {
  159. const detected = AGENT_REGISTRY.filter((agent) => existsSync(agent.base())).map((agent) => agent.name);
  160. console.log(`skills: ${bundledSkillNames().join(', ')}`);
  161. console.log(`agents: ${bundledAgentFiles().map((file) => basename(file, '.md')).join(', ')}`);
  162. console.log(`targets: ${AGENT_REGISTRY.map((agent) => `${agent.name}${detected.includes(agent.name) ? '*' : ''}`).join(', ')} (* = detected)`);
  163. }
  164. // Returns the SHA-256 hex digest of a file, or null when the file does not exist.
  165. function fileHash(filePath) {
  166. if (!existsSync(filePath)) return null;
  167. return createHash('sha256').update(readFileSync(filePath)).digest('hex');
  168. }
  169. // Returns a stable digest of a directory: sorted list of "relative path:hash"
  170. // for every file, so any content or structure change alters the result.
  171. function dirHash(dirPath) {
  172. if (!existsSync(dirPath)) return null;
  173. const parts = [];
  174. const walk = (dir, prefix) => {
  175. for (const entry of readdirSync(dir, { withFileTypes: true })) {
  176. const full = join(dir, entry.name);
  177. if (entry.isDirectory()) walk(full, `${prefix}${entry.name}/`);
  178. else parts.push(`${prefix}${entry.name}:${fileHash(full)}`);
  179. }
  180. };
  181. walk(dirPath, '');
  182. return createHash('sha256').update(parts.sort().join('\n')).digest('hex');
  183. }
  184. // Returns the lstat of a path, or null when it does not exist (broken links included).
  185. function lstatOrNull(path) {
  186. try {
  187. return lstatSync(path);
  188. } catch {
  189. return null;
  190. }
  191. }
  192. // Tells whether the entry at linkPath is a symlink resolving to targetPath.
  193. function pointsTo(linkPath, targetPath) {
  194. try {
  195. return realpathSync(linkPath) === realpathSync(targetPath);
  196. } catch {
  197. return false;
  198. }
  199. }
  200. // Ensures the canonical agents directory exists as a real directory receiving
  201. // the copied prompt files. An earlier version linked the whole folder with a
  202. // junction: such a link to our own source is unwound here (removing the
  203. // junction never touches the source files).
  204. function ensureCanonicalAgentsDir() {
  205. const current = lstatOrNull(CANONICAL_AGENTS_DIR);
  206. if (!current) {
  207. if (DRY_RUN) return { label: 'agents', status: 'link' };
  208. mkdirSync(CANONICAL_AGENTS_DIR, { recursive: true });
  209. return { label: 'agents', status: 'added' };
  210. }
  211. if (current.isSymbolicLink()) {
  212. if (DRY_RUN) return { label: 'agents', status: 'relink' };
  213. rmSync(CANONICAL_AGENTS_DIR, { recursive: true, force: true });
  214. mkdirSync(CANONICAL_AGENTS_DIR, { recursive: true });
  215. return { label: 'agents', status: 'relinked' };
  216. }
  217. return current.isDirectory() ? { label: 'agents', status: 'up-to-date' } : { label: 'agents', status: 'skipped' };
  218. }
  219. // Copies the selected skills into the canonical directory and copies the
  220. // agent prompts into ~/.agents/agents (files on windows cannot be linked
  221. // without privileges, so agents use plain copies). Returns the list of actions.
  222. function syncCanonical(skills, agentFiles) {
  223. const actions = [];
  224. for (const name of skills) {
  225. const source = join(SOURCE_SKILLS_DIR, name);
  226. const dest = join(CANONICAL_SKILLS_DIR, name);
  227. const status = dirHash(source) === dirHash(dest) ? 'up-to-date' : existsSync(dest) ? 'updated' : 'added';
  228. if (status !== 'up-to-date' && !DRY_RUN) {
  229. rmSync(dest, { recursive: true, force: true });
  230. cpSync(source, dest, { recursive: true });
  231. }
  232. actions.push({ label: `skills/${name}`, status });
  233. }
  234. for (const file of agentFiles) {
  235. const source = join(SOURCE_AGENTS_DIR, file);
  236. const dest = join(CANONICAL_AGENTS_DIR, file);
  237. const status = fileHash(source) === fileHash(dest) ? 'up-to-date' : existsSync(dest) ? 'updated' : 'added';
  238. if (status !== 'up-to-date' && !DRY_RUN) {
  239. copyFileSync(source, dest);
  240. }
  241. actions.push({ label: `agents/${file}`, status });
  242. }
  243. return actions;
  244. }
  245. // Detects installed agents by probing their config directory, optionally
  246. // restricted to the requested target names.
  247. function detectAgents(targetNames) {
  248. return AGENT_REGISTRY
  249. .filter((agent) => (!targetNames || targetNames.includes(agent.name)) && existsSync(agent.base()))
  250. .map((agent) => ({ ...agent, baseDir: agent.base() }));
  251. }
  252. // Ensures linkPath points to targetPath via a symlink: junctions for
  253. // directories on windows (no privileges needed), file symlinks everywhere
  254. // else. There is no fallback: if the symlink cannot be created (EPERM without
  255. // Developer Mode/privileges, cross-filesystem restrictions) the sync aborts
  256. // with an explicit error — copies are never made. A pre-existing regular file
  257. // is a leftover from older copy/hardlink installs and is replaced by the
  258. // symlink; directories or foreign symlinks are skipped, never touched.
  259. function ensureLink(linkPath, targetPath) {
  260. const current = lstatOrNull(linkPath);
  261. if (current) {
  262. if (current.isSymbolicLink() && pointsTo(linkPath, targetPath)) return 'up-to-date';
  263. if (current.isFile()) {
  264. if (DRY_RUN) return 'relink';
  265. rmSync(linkPath, { force: true });
  266. } else {
  267. return 'skipped';
  268. }
  269. }
  270. if (DRY_RUN) return 'link';
  271. mkdirSync(dirname(linkPath), { recursive: true });
  272. const isDirectory = statSync(targetPath).isDirectory();
  273. try {
  274. if (IS_WINDOWS && isDirectory) symlinkSync(targetPath, linkPath, 'junction');
  275. else symlinkSync(relative(dirname(linkPath), targetPath), linkPath);
  276. return 'linked';
  277. } catch (error) {
  278. throw new Error(`cannot create symlink '${linkPath}' (no fallback, no copy: ${error.message})`);
  279. }
  280. }
  281. // Links the selected skills (source package names only, so third-party
  282. // content in the canonical directory is never propagated) into one detected
  283. // agent's directories. Agent prompts are deliberately not linked here: they
  284. // are managed only inside the canonical ~/.agents/agents directory.
  285. function linkForAgent(agent, skills) {
  286. const actions = [];
  287. for (const name of skills) {
  288. actions.push({
  289. label: `${agent.name}:skills/${name}`,
  290. status: ensureLink(join(agent.baseDir, agent.skillsSub, name), join(CANONICAL_SKILLS_DIR, name)),
  291. });
  292. }
  293. return actions;
  294. }
  295. // Copies the bundled SYSTEM_PROMPT.md into every detected agent that supports
  296. // a global system prompt (sys mapping), renamed to its standard filename and
  297. // always as a plain copy (never linked, never through ~/.agents). Cursor and
  298. // windsurf receive the content wrapped in an always-on rule frontmatter.
  299. function syncSystemPrompts(detected, systemPrompt) {
  300. const actions = [];
  301. for (const agent of detected) {
  302. if (!agent.sys) continue;
  303. const expected = (agent.sys.frontmatter ?? '') + systemPrompt;
  304. const dest = join(agent.base(), agent.sys.file);
  305. const expectedHash = createHash('sha256').update(expected).digest('hex');
  306. const status = expectedHash === fileHash(dest) ? 'up-to-date' : existsSync(dest) ? 'updated' : 'added';
  307. if (status !== 'up-to-date' && !DRY_RUN) {
  308. mkdirSync(dirname(dest), { recursive: true });
  309. writeFileSync(dest, expected);
  310. }
  311. actions.push({ label: `${agent.name}:sys/${basename(agent.sys.file)}`, status });
  312. }
  313. return actions;
  314. }
  315. // Orchestrates the sync and prints a per-entry report with a final summary.
  316. function main() {
  317. if (PLAN.help) {
  318. console.log(HELP);
  319. process.exit(EXIT_OK);
  320. }
  321. if (!existsSync(SOURCE_SKILLS_DIR) || !existsSync(SOURCE_AGENTS_DIR)) {
  322. console.error(`error: bundled content not found under ${PACKAGE_ROOT}`);
  323. process.exit(EXIT_FAILURE);
  324. }
  325. const hasContent = PLAN.all || PLAN.skills || PLAN.agents || PLAN.sys;
  326. if ((PLAN.all || PLAN.sys) && !existsSync(SOURCE_SYSTEM_PROMPT)) {
  327. console.error(`error: SYSTEM_PROMPT.md not found under ${PACKAGE_ROOT}`);
  328. process.exit(EXIT_FAILURE);
  329. }
  330. if (PLAN.list && (hasContent || PLAN.targets)) fail('error: --list cannot be combined with selection flags');
  331. if (PLAN.all && (PLAN.skills || PLAN.agents || PLAN.sys)) fail('error: --all cannot be combined with --skills, --agents or --sys');
  332. if (PLAN.targets && !hasContent) fail('error: --targets requires --all, --skills, --agents or --sys');
  333. if (PLAN.list) {
  334. printCatalog();
  335. process.exit(EXIT_OK);
  336. }
  337. if (!hasContent) {
  338. console.log(HELP);
  339. process.exit(EXIT_OK);
  340. }
  341. const { skills, agents: agentFiles, targets, sys } = resolveSelection(PLAN);
  342. const detected = detectAgents(targets);
  343. if (targets && detected.length === 0) {
  344. fail(`error: none of the requested targets is installed (${targets.join(', ')})`);
  345. }
  346. if ((skills.length > 0 || PLAN.all) && !DRY_RUN) {
  347. mkdirSync(CANONICAL_SKILLS_DIR, { recursive: true });
  348. }
  349. const report = [...(agentFiles.length > 0 ? [ensureCanonicalAgentsDir()] : []), ...syncCanonical(skills, agentFiles)];
  350. if (sys) {
  351. report.push(...syncSystemPrompts(detected, readFileSync(SOURCE_SYSTEM_PROMPT, 'utf8')));
  352. }
  353. for (const agent of detected) {
  354. report.push(...linkForAgent(agent, skills));
  355. }
  356. for (const { label, status } of report) {
  357. console.log(`${status.padEnd(12)} ${label}`);
  358. }
  359. console.log(`\nagents detected: ${detected.map((agent) => agent.name).join(', ') || 'none'}`);
  360. const drift = report.filter((entry) => entry.status !== 'up-to-date' && entry.status !== 'skipped').length;
  361. if (drift === 0) {
  362. console.log('Everything up to date.');
  363. } else {
  364. console.log(DRY_RUN ? `${drift} entr${drift === 1 ? 'y' : 'ies'} out of sync (dry-run, nothing written).` : `${drift} entr${drift === 1 ? 'y' : 'ies'} synced.`);
  365. }
  366. if (DRY_RUN && drift > 0) {
  367. process.exit(EXIT_FAILURE);
  368. }
  369. }
  370. const PLAN = parseArgs(process.argv.slice(2));
  371. const DRY_RUN = PLAN.dryRun;
  372. try {
  373. main();
  374. } catch (error) {
  375. console.error(`error: ${error.message}`);
  376. process.exit(EXIT_FAILURE);
  377. }