agent-sync.mjs 18 KB

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