agent-sync.mjs 19 KB

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