agent-sync.mjs 15 KB

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