agent-sync.mjs 15 KB

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