@workingpayload/agent-skills 2.0.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,437 +1,486 @@
1
- #!/usr/bin/env python3
2
- """
3
- install.py - Install Agent Skills to Claude or Gemini commands directories.
4
-
5
- Usage:
6
- python scripts/install.py # install all skills (auto-detect target)
7
- python scripts/install.py --target claude # install to Claude
8
- python scripts/install.py --target gemini # install to Gemini
9
- python scripts/install.py --skills CodeSage,UISmith # install specific skills
10
- python scripts/install.py --force # overwrite existing installs
11
- python scripts/install.py --dry-run # preview without writing
12
- python scripts/install.py --validate # validate before installing
13
- python scripts/install.py --list-installed # show installed skills
14
- python scripts/install.py --uninstall CodeSage # remove specific skills
15
- """
16
-
17
- import argparse
18
- import hashlib
19
- import json
20
- import os
21
- import shutil
22
- import subprocess
23
- import sys
24
- from datetime import datetime, timezone
25
- from pathlib import Path
26
-
27
- # ---------------------------------------------------------------------------
28
- # Constants
29
- # ---------------------------------------------------------------------------
30
-
31
- SKILL_FILENAMES = ("skill.md", "SKILL.md")
32
- META_FILE = ".skills-meta.json"
33
-
34
- INSTALL_DIRS = {
35
- "claude": Path.home() / ".claude" / "commands",
36
- "gemini": Path.home() / ".gemini" / "skills",
37
- "antigravity": Path.home() / ".gemini" / "antigravity" / "skills",
38
- }
39
-
40
- # Targets that use directory-based skill format (skill-name/SKILL.md)
41
- DIR_FORMAT_TARGETS = {"gemini", "antigravity"}
42
-
43
- POST_INSTALL_INSTRUCTIONS = {
44
- "claude": "Use skills by typing /skill-name in Claude Code",
45
- "gemini": "Gemini CLI will automatically activate skills matching your task",
46
- "antigravity": "Skills are available in Google Antigravity via semantic triggering",
47
- }
48
-
49
- # ---------------------------------------------------------------------------
50
- # Repo helpers
51
- # ---------------------------------------------------------------------------
52
-
53
- def repo_root() -> Path:
54
- """Return the root of this repository (parent of this script's directory)."""
55
- return Path(__file__).resolve().parent.parent
56
-
57
-
58
- def find_all_skill_dirs(root: Path) -> dict[str, Path]:
59
- """
60
- Scan repo root for directories containing a skill file.
61
- Returns {skill_name: skill_file_path}.
62
- Skill name is derived from the directory name (lowercased, spaces→hyphens).
63
- """
64
- skills: dict[str, Path] = {}
65
- for d in sorted(root.iterdir()):
66
- if not d.is_dir():
67
- continue
68
- # Skip hidden dirs and the scripts dir itself
69
- if d.name.startswith(".") or d.name == "scripts":
70
- continue
71
- for filename in SKILL_FILENAMES:
72
- candidate = d / filename
73
- if candidate.is_file():
74
- skill_name = d.name.lower().replace(" ", "-")
75
- skills[skill_name] = candidate
76
- break
77
- return skills
78
-
79
-
80
- def git_hash(path: Path) -> str:
81
- """Return the git object hash for a file, or a content SHA256 fallback."""
82
- try:
83
- result = subprocess.run(
84
- ["git", "hash-object", str(path)],
85
- capture_output=True,
86
- text=True,
87
- cwd=str(path.parent),
88
- )
89
- if result.returncode == 0:
90
- return result.stdout.strip()
91
- except FileNotFoundError:
92
- pass # git not available
93
- # Fallback: SHA256 of file content
94
- digest = hashlib.sha256(path.read_bytes()).hexdigest()
95
- return f"sha256:{digest[:16]}"
96
-
97
-
98
- # ---------------------------------------------------------------------------
99
- # Meta file helpers
100
- # ---------------------------------------------------------------------------
101
-
102
- def load_meta(install_dir: Path) -> dict:
103
- meta_path = install_dir / META_FILE
104
- if meta_path.is_file():
105
- try:
106
- return json.loads(meta_path.read_text(encoding="utf-8"))
107
- except json.JSONDecodeError:
108
- return {}
109
- return {}
110
-
111
-
112
- def save_meta(install_dir: Path, meta: dict) -> None:
113
- install_dir.mkdir(parents=True, exist_ok=True)
114
- meta_path = install_dir / META_FILE
115
- meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8")
116
-
117
-
118
- # ---------------------------------------------------------------------------
119
- # Validation helper (delegates to scripts/validate.py if available)
120
- # ---------------------------------------------------------------------------
121
-
122
- def validate_skill(skill_file: Path) -> tuple[bool, str]:
123
- """
124
- Run a lightweight inline validation on a single skill file.
125
- Returns (passed, message).
126
- """
127
- try:
128
- text = skill_file.read_text(encoding="utf-8")
129
- except OSError as exc:
130
- return False, f"Cannot read file: {exc}"
131
-
132
- lines = text.splitlines()
133
- if len(lines) < 10:
134
- return False, f"Too short ({len(lines)} lines)"
135
-
136
- # Check for frontmatter
137
- if not lines or lines[0].strip() != "---":
138
- return False, "Missing YAML frontmatter (file must start with ---)"
139
-
140
- # Extract frontmatter fields
141
- end_idx = None
142
- for i, line in enumerate(lines[1:], start=1):
143
- if line.strip() == "---":
144
- end_idx = i
145
- break
146
- if end_idx is None:
147
- return False, "Unclosed YAML frontmatter"
148
-
149
- fm_text = "\n".join(lines[1:end_idx])
150
- if "name:" not in fm_text:
151
- return False, "Frontmatter missing 'name' field"
152
- if "description:" not in fm_text:
153
- return False, "Frontmatter missing 'description' field"
154
-
155
- return True, "OK"
156
-
157
-
158
- # ---------------------------------------------------------------------------
159
- # Auto-detect target
160
- # ---------------------------------------------------------------------------
161
-
162
- def auto_detect_target() -> str | None:
163
- """Return 'claude' or 'gemini' based on which install dirs already exist."""
164
- for target, path in INSTALL_DIRS.items():
165
- if path.exists():
166
- return target
167
- # Fall back to claude as the primary target
168
- return "claude"
169
-
170
-
171
- # ---------------------------------------------------------------------------
172
- # Core operations
173
- # ---------------------------------------------------------------------------
174
-
175
- def list_installed(install_dir: Path) -> None:
176
- meta = load_meta(install_dir)
177
- if not meta:
178
- print("No skills installed.")
179
- return
180
-
181
- print(f"Installed skills in {install_dir}:\n")
182
- header = f"{'Skill':<30} {'Version':<20} {'Installed At'}"
183
- print(header)
184
- print("-" * len(header))
185
- for name, info in sorted(meta.items()):
186
- version = info.get("version", "unknown")[:12]
187
- installed_at = info.get("installed_at", "unknown")
188
- print(f"{name:<30} {version:<20} {installed_at}")
189
-
190
-
191
- def uninstall_skills(names: list[str], install_dir: Path, dry_run: bool) -> None:
192
- meta = load_meta(install_dir)
193
- removed, missing = 0, 0
194
-
195
- for name in names:
196
- dest = install_dir / f"{name}.md"
197
- if dest.exists():
198
- print(f" {'[dry-run] ' if dry_run else ''}Removing {dest}")
199
- if not dry_run:
200
- dest.unlink()
201
- removed += 1
202
- else:
203
- print(f" Skill not installed: {name}")
204
- missing += 1
205
-
206
- if name in meta and not dry_run:
207
- del meta[name]
208
-
209
- if not dry_run:
210
- save_meta(install_dir, meta)
211
-
212
- print(f"\nUninstall summary: {removed} removed, {missing} not found.")
213
-
214
-
215
- def install_skills(
216
- skill_map: dict[str, Path],
217
- install_dir: Path,
218
- target: str,
219
- force: bool,
220
- dry_run: bool,
221
- do_validate: bool,
222
- ) -> None:
223
- install_dir.mkdir(parents=True, exist_ok=True)
224
- meta = load_meta(install_dir)
225
-
226
- installed_count = 0
227
- skipped_count = 0
228
- failed_count = 0
229
-
230
- for skill_name, skill_file in sorted(skill_map.items()):
231
- dest = install_dir / f"{skill_name}.md"
232
-
233
- # Validation gate
234
- if do_validate:
235
- passed, msg = validate_skill(skill_file)
236
- if not passed:
237
- print(f" FAIL {skill_name}: validation error — {msg}")
238
- failed_count += 1
239
- continue
240
-
241
- # Skip if already installed and not forcing
242
- uses_dir_format = target in DIR_FORMAT_TARGETS
243
- exists_already = (
244
- (install_dir / skill_name / "SKILL.md").exists()
245
- if uses_dir_format
246
- else dest.exists()
247
- )
248
- if exists_already and not force:
249
- print(f" SKIP {skill_name} (already installed; use --force to overwrite)")
250
- skipped_count += 1
251
- continue
252
-
253
- if uses_dir_format:
254
- # Gemini and Antigravity: directory-based skills with SKILL.md
255
- skill_dir = install_dir / skill_name
256
- dest_file = skill_dir / "SKILL.md"
257
- action = "Would install" if dry_run else "Installing"
258
- print(f" {action} {skill_name}")
259
- print(f" src : {skill_file}")
260
- print(f" dest: {dest_file}")
261
-
262
- if not dry_run:
263
- skill_dir.mkdir(parents=True, exist_ok=True)
264
- shutil.copy2(str(skill_file), str(dest_file))
265
- # Copy optional asset directories (scripts/, references/, assets/)
266
- src_dir = skill_file.parent
267
- for subdir_name in ("scripts", "references", "assets"):
268
- src_sub = src_dir / subdir_name
269
- if src_sub.is_dir():
270
- dest_sub = skill_dir / subdir_name
271
- if dest_sub.exists():
272
- shutil.rmtree(str(dest_sub))
273
- shutil.copytree(str(src_sub), str(dest_sub))
274
- meta[skill_name] = {
275
- "name": skill_name,
276
- "version": git_hash(skill_file),
277
- "installed_at": datetime.now(timezone.utc).isoformat(),
278
- "source_path": str(skill_file),
279
- }
280
- else:
281
- action = "Would install" if dry_run else "Installing"
282
- print(f" {action} {skill_name}")
283
- print(f" src : {skill_file}")
284
- print(f" dest: {dest}")
285
-
286
- if not dry_run:
287
- shutil.copy2(str(skill_file), str(dest))
288
- meta[skill_name] = {
289
- "name": skill_name,
290
- "version": git_hash(skill_file),
291
- "installed_at": datetime.now(timezone.utc).isoformat(),
292
- "source_path": str(skill_file),
293
- }
294
-
295
- installed_count += 1
296
-
297
- if not dry_run:
298
- save_meta(install_dir, meta)
299
-
300
- prefix = "[dry-run] " if dry_run else ""
301
- print(
302
- f"\n{prefix}Summary: {installed_count} installed, "
303
- f"{skipped_count} skipped (already exists), "
304
- f"{failed_count} failed."
305
- )
306
-
307
- if not dry_run and installed_count > 0:
308
- instruction = POST_INSTALL_INSTRUCTIONS.get(target, "")
309
- print(f"\nHow to use your skills ({target}):")
310
- if target == "claude":
311
- print(f" {instruction}")
312
- print(f" Example: /codesage, /uismith, /bugHunter-pro")
313
- elif target in DIR_FORMAT_TARGETS:
314
- print(f" {instruction}")
315
- print(f" Skills installed as directories with SKILL.md files.")
316
- print(f"\nInstall directory: {install_dir}")
317
-
318
-
319
- # ---------------------------------------------------------------------------
320
- # CLI
321
- # ---------------------------------------------------------------------------
322
-
323
- def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
324
- parser = argparse.ArgumentParser(
325
- description="Install Agent Skills to Claude or Gemini commands directories.",
326
- formatter_class=argparse.RawDescriptionHelpFormatter,
327
- epilog=__doc__,
328
- )
329
-
330
- parser.add_argument(
331
- "--target", "-t",
332
- choices=["claude", "gemini", "antigravity"],
333
- default=None,
334
- help="Target platform (default: auto-detect based on existing directories).",
335
- )
336
- parser.add_argument(
337
- "--skills", "-s",
338
- default=None,
339
- help="Comma-separated skill names to install (default: all).",
340
- )
341
- parser.add_argument(
342
- "--force",
343
- action="store_true",
344
- help="Overwrite existing installed skills.",
345
- )
346
- parser.add_argument(
347
- "--dry-run",
348
- action="store_true",
349
- help="Show what would be done without making any changes.",
350
- )
351
- parser.add_argument(
352
- "--validate",
353
- action="store_true",
354
- help="Run validation on each skill before installing; skip invalid skills.",
355
- )
356
- parser.add_argument(
357
- "--list-installed",
358
- action="store_true",
359
- help="Show currently installed skills with version info.",
360
- )
361
- parser.add_argument(
362
- "--uninstall",
363
- metavar="NAMES",
364
- default=None,
365
- help="Comma-separated skill names to uninstall.",
366
- )
367
-
368
- return parser.parse_args(argv)
369
-
370
-
371
- def main(argv: list[str] | None = None) -> int:
372
- args = parse_args(argv)
373
-
374
- # Resolve target platform
375
- target = args.target or auto_detect_target()
376
- install_dir = INSTALL_DIRS[target]
377
-
378
- print(f"Target : {target}")
379
- print(f"Install: {install_dir}")
380
- print()
381
-
382
- # --list-installed
383
- if args.list_installed:
384
- list_installed(install_dir)
385
- return 0
386
-
387
- # --uninstall
388
- if args.uninstall:
389
- names = [n.strip().lower().replace(" ", "-") for n in args.uninstall.split(",") if n.strip()]
390
- print(f"Uninstalling {len(names)} skill(s) from {install_dir}:\n")
391
- uninstall_skills(names, install_dir, dry_run=args.dry_run)
392
- return 0
393
-
394
- # Discover all skills in the repo
395
- root = repo_root()
396
- all_skills = find_all_skill_dirs(root)
397
-
398
- if not all_skills:
399
- print("ERROR: No skill files found in the repository.")
400
- return 1
401
-
402
- # Filter to requested skills if --skills was given
403
- if args.skills:
404
- requested = {
405
- n.strip().lower().replace(" ", "-")
406
- for n in args.skills.split(",")
407
- if n.strip()
408
- }
409
- unknown = requested - all_skills.keys()
410
- if unknown:
411
- print(f"WARNING: Unknown skill(s): {', '.join(sorted(unknown))}")
412
- skill_map = {k: v for k, v in all_skills.items() if k in requested}
413
- if not skill_map:
414
- print("ERROR: No matching skills found.")
415
- return 1
416
- else:
417
- skill_map = all_skills
418
-
419
- print(f"Skills to process: {len(skill_map)}")
420
- if args.dry_run:
421
- print("[DRY RUN — no files will be written]\n")
422
- print()
423
-
424
- install_skills(
425
- skill_map=skill_map,
426
- install_dir=install_dir,
427
- target=target,
428
- force=args.force,
429
- dry_run=args.dry_run,
430
- do_validate=args.validate,
431
- )
432
-
433
- return 0
434
-
435
-
436
- if __name__ == "__main__":
437
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ """
3
+ install.py - Install Agent Skills to supported AI CLI skill directories.
4
+
5
+ Usage:
6
+ python scripts/install.py # store once and link every target
7
+ python scripts/install.py --target claude # install to Claude
8
+ python scripts/install.py --target gemini # install to Gemini
9
+ python scripts/install.py --skills CodeSage,UISmith # install specific skills
10
+ python scripts/install.py --force # overwrite existing installs
11
+ python scripts/install.py --dry-run # preview without writing
12
+ python scripts/install.py --validate # validate before installing
13
+ python scripts/install.py --list-installed # show installed skills
14
+ python scripts/install.py --uninstall CodeSage # remove specific skills
15
+ """
16
+
17
+ import argparse
18
+ import hashlib
19
+ import json
20
+ import os
21
+ import shutil
22
+ import subprocess
23
+ import sys
24
+ from datetime import datetime, timezone
25
+ from pathlib import Path
26
+
27
+ # ---------------------------------------------------------------------------
28
+ # Constants
29
+ # ---------------------------------------------------------------------------
30
+
31
+ SKILL_FILENAMES = ("skill.md", "SKILL.md")
32
+ META_FILE = ".skills-meta.json"
33
+
34
+ INSTALL_DIRS = {
35
+ "agents": Path.home() / ".agents" / "skills",
36
+ "claude": Path.home() / ".claude" / "skills",
37
+ "copilot": Path.home() / ".copilot" / "skills",
38
+ "codex": Path.home() / ".codex" / "skills",
39
+ "gemini": Path.home() / ".gemini" / "skills",
40
+ "antigravity": Path.home() / ".gemini" / "antigravity" / "skills",
41
+ }
42
+
43
+ CANONICAL_TARGET = "agents"
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # Repo helpers
47
+ # ---------------------------------------------------------------------------
48
+
49
+ def repo_root() -> Path:
50
+ """Return the root of this repository (parent of this script's directory)."""
51
+ return Path(__file__).resolve().parent.parent
52
+
53
+
54
+ def find_all_skill_dirs(root: Path) -> dict[str, Path]:
55
+ """
56
+ Scan repo root for directories containing a skill file.
57
+ Returns {skill_name: skill_file_path}.
58
+ Skill name is derived from the directory name (lowercased, spaces→hyphens).
59
+ """
60
+ skills: dict[str, Path] = {}
61
+ for d in sorted(root.iterdir()):
62
+ if not d.is_dir():
63
+ continue
64
+ # Skip hidden dirs and the scripts dir itself
65
+ if d.name.startswith(".") or d.name == "scripts":
66
+ continue
67
+ for filename in SKILL_FILENAMES:
68
+ candidate = d / filename
69
+ if candidate.is_file():
70
+ skill_name = d.name.lower().replace(" ", "-")
71
+ skills[skill_name] = candidate
72
+ break
73
+ return skills
74
+
75
+
76
+ def git_hash(path: Path) -> str:
77
+ """Return the git object hash for a file, or a content SHA256 fallback."""
78
+ try:
79
+ result = subprocess.run(
80
+ ["git", "hash-object", str(path)],
81
+ capture_output=True,
82
+ text=True,
83
+ cwd=str(path.parent),
84
+ )
85
+ if result.returncode == 0:
86
+ return result.stdout.strip()
87
+ except FileNotFoundError:
88
+ pass # git not available
89
+ # Fallback: SHA256 of file content
90
+ digest = hashlib.sha256(path.read_bytes()).hexdigest()
91
+ return f"sha256:{digest[:16]}"
92
+
93
+
94
+ # ---------------------------------------------------------------------------
95
+ # Meta file helpers
96
+ # ---------------------------------------------------------------------------
97
+
98
+ def load_meta(install_dir: Path) -> dict:
99
+ meta_path = install_dir / META_FILE
100
+ if meta_path.is_file():
101
+ try:
102
+ return json.loads(meta_path.read_text(encoding="utf-8"))
103
+ except json.JSONDecodeError:
104
+ return {}
105
+ return {}
106
+
107
+
108
+ def save_meta(install_dir: Path, meta: dict) -> None:
109
+ install_dir.mkdir(parents=True, exist_ok=True)
110
+ meta_path = install_dir / META_FILE
111
+ meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8")
112
+
113
+
114
+ # ---------------------------------------------------------------------------
115
+ # Validation helper (delegates to scripts/validate.py if available)
116
+ # ---------------------------------------------------------------------------
117
+
118
+ def validate_skill(skill_file: Path) -> tuple[bool, str]:
119
+ """
120
+ Run a lightweight inline validation on a single skill file.
121
+ Returns (passed, message).
122
+ """
123
+ try:
124
+ text = skill_file.read_text(encoding="utf-8")
125
+ except OSError as exc:
126
+ return False, f"Cannot read file: {exc}"
127
+
128
+ lines = text.splitlines()
129
+ if len(lines) < 10:
130
+ return False, f"Too short ({len(lines)} lines)"
131
+
132
+ # Check for frontmatter
133
+ if not lines or lines[0].strip() != "---":
134
+ return False, "Missing YAML frontmatter (file must start with ---)"
135
+
136
+ # Extract frontmatter fields
137
+ end_idx = None
138
+ for i, line in enumerate(lines[1:], start=1):
139
+ if line.strip() == "---":
140
+ end_idx = i
141
+ break
142
+ if end_idx is None:
143
+ return False, "Unclosed YAML frontmatter"
144
+
145
+ fm_text = "\n".join(lines[1:end_idx])
146
+ if "name:" not in fm_text:
147
+ return False, "Frontmatter missing 'name' field"
148
+ if "description:" not in fm_text:
149
+ return False, "Frontmatter missing 'description' field"
150
+
151
+ return True, "OK"
152
+
153
+
154
+ # ---------------------------------------------------------------------------
155
+ # Core operations
156
+ # ---------------------------------------------------------------------------
157
+
158
+ def list_installed(install_dir: Path) -> None:
159
+ meta = load_meta(install_dir)
160
+ if not meta:
161
+ print("No skills installed.")
162
+ return
163
+
164
+ print("Installed skills:\n")
165
+ header = f"{'Skill':<30} {'Version':<20} {'Installed At'}"
166
+ print(header)
167
+ print("-" * len(header))
168
+ for name, info in sorted(meta.items()):
169
+ version = info.get("version", "unknown")[:12]
170
+ installed_at = info.get("installed_at", "unknown")
171
+ print(f"{name:<30} {version:<20} {installed_at}")
172
+
173
+
174
+ def remove_directory_entry(path: Path) -> None:
175
+ """Remove a real directory or a directory link without traversing links."""
176
+ is_junction = getattr(path, "is_junction", lambda: False)()
177
+ if is_junction:
178
+ os.rmdir(path)
179
+ elif path.is_symlink() or not path.is_dir():
180
+ path.unlink()
181
+ else:
182
+ shutil.rmtree(path)
183
+
184
+
185
+ def uninstall_skills(names: list[str], install_dir: Path, dry_run: bool) -> None:
186
+ meta = load_meta(install_dir)
187
+ removed, missing = 0, 0
188
+
189
+ for name in names:
190
+ dest = install_dir / name
191
+ if os.path.lexists(dest):
192
+ print(f" {'[dry-run] ' if dry_run else ''}Removing {name}")
193
+ if not dry_run:
194
+ remove_directory_entry(dest)
195
+ removed += 1
196
+ else:
197
+ print(f" Skill not installed: {name}")
198
+ missing += 1
199
+
200
+ if name in meta and not dry_run:
201
+ del meta[name]
202
+
203
+ if not dry_run:
204
+ save_meta(install_dir, meta)
205
+
206
+ print(f"\nUninstall summary: {removed} removed, {missing} not found.")
207
+
208
+
209
+ def install_skills(
210
+ skill_map: dict[str, Path],
211
+ install_dir: Path,
212
+ force: bool,
213
+ dry_run: bool,
214
+ do_validate: bool,
215
+ ) -> dict[str, int]:
216
+ if not dry_run:
217
+ install_dir.mkdir(parents=True, exist_ok=True)
218
+ meta = load_meta(install_dir)
219
+
220
+ installed_count = 0
221
+ skipped_count = 0
222
+ failed_count = 0
223
+
224
+ for skill_name, skill_file in sorted(skill_map.items()):
225
+ skill_dir = install_dir / skill_name
226
+ dest_file = skill_dir / "SKILL.md"
227
+
228
+ # Validation gate
229
+ if do_validate:
230
+ passed, msg = validate_skill(skill_file)
231
+ if not passed:
232
+ print(f" FAIL {skill_name}: validation error — {msg}")
233
+ failed_count += 1
234
+ continue
235
+
236
+ # Skip if already installed and not forcing
237
+ if dest_file.exists() and not force:
238
+ print(f" SKIP {skill_name} (already installed; use --force to overwrite)")
239
+ skipped_count += 1
240
+ continue
241
+
242
+ action = "Would store" if dry_run else "Storing"
243
+ print(f" {action} {skill_name}")
244
+
245
+ if not dry_run:
246
+ skill_dir.mkdir(parents=True, exist_ok=True)
247
+ shutil.copy2(str(skill_file), str(dest_file))
248
+ src_dir = skill_file.parent
249
+ for subdir_name in ("scripts", "references", "assets"):
250
+ src_sub = src_dir / subdir_name
251
+ if src_sub.is_dir():
252
+ dest_sub = skill_dir / subdir_name
253
+ if dest_sub.exists():
254
+ shutil.rmtree(str(dest_sub))
255
+ shutil.copytree(str(src_sub), str(dest_sub))
256
+ meta[skill_name] = {
257
+ "name": skill_name,
258
+ "version": git_hash(skill_file),
259
+ "installed_at": datetime.now(timezone.utc).isoformat(),
260
+ "source_path": str(skill_file),
261
+ "filename": str(Path(skill_name) / "SKILL.md"),
262
+ }
263
+
264
+ installed_count += 1
265
+
266
+ if not dry_run:
267
+ save_meta(install_dir, meta)
268
+
269
+ prefix = "[dry-run] " if dry_run else ""
270
+ print(
271
+ f"\n{prefix}Summary: {installed_count} installed, "
272
+ f"{skipped_count} skipped (already exists), "
273
+ f"{failed_count} failed."
274
+ )
275
+
276
+ return {
277
+ "stored": installed_count,
278
+ "skipped": skipped_count,
279
+ "failed": failed_count,
280
+ }
281
+
282
+
283
+ def create_directory_link(source: Path, link: Path) -> None:
284
+ """Create a directory link, using a junction on Windows."""
285
+ if sys.platform == "win32":
286
+ command = os.environ.get("COMSPEC", "cmd.exe")
287
+ result = subprocess.run(
288
+ [command, "/c", "mklink", "/J", str(link), str(source)],
289
+ capture_output=True,
290
+ text=True,
291
+ )
292
+ if result.returncode != 0:
293
+ raise OSError((result.stderr or result.stdout).strip())
294
+ else:
295
+ link.symlink_to(source, target_is_directory=True)
296
+
297
+
298
+ def link_skills(
299
+ skill_map: dict[str, Path],
300
+ target: str,
301
+ force: bool,
302
+ dry_run: bool,
303
+ ) -> dict[str, int]:
304
+ install_dir = INSTALL_DIRS[target]
305
+ canonical_dir = INSTALL_DIRS[CANONICAL_TARGET]
306
+ if not dry_run:
307
+ install_dir.mkdir(parents=True, exist_ok=True)
308
+ meta = load_meta(install_dir)
309
+ linked = skipped = failed = 0
310
+
311
+ print(f"\nTarget: {target}")
312
+ for skill_name, skill_file in sorted(skill_map.items()):
313
+ source = canonical_dir / skill_name
314
+ link = install_dir / skill_name
315
+ if os.path.lexists(link) and not force:
316
+ print(f" SKIP {skill_name} (already exists; use --force to replace with a link)")
317
+ skipped += 1
318
+ continue
319
+ if dry_run:
320
+ print(f" Would link {skill_name}")
321
+ linked += 1
322
+ continue
323
+ try:
324
+ if not (source / "SKILL.md").is_file():
325
+ raise FileNotFoundError("canonical skill is missing")
326
+ if os.path.lexists(link):
327
+ remove_directory_entry(link)
328
+ create_directory_link(source, link)
329
+ meta[skill_name] = {
330
+ "name": skill_name,
331
+ "version": git_hash(skill_file),
332
+ "installed_at": datetime.now(timezone.utc).isoformat(),
333
+ "source_path": str(skill_file),
334
+ "filename": str(Path(skill_name) / "SKILL.md"),
335
+ "linked_from": str(source),
336
+ }
337
+ print(f" OK {skill_name}")
338
+ linked += 1
339
+ except OSError as exc:
340
+ print(f" FAIL {skill_name}: {exc}")
341
+ failed += 1
342
+
343
+ if not dry_run:
344
+ save_meta(install_dir, meta)
345
+ print(f"Summary: {linked} linked, {skipped} skipped, {failed} failed.")
346
+ return {"linked": linked, "skipped": skipped, "failed": failed}
347
+
348
+
349
+ # ---------------------------------------------------------------------------
350
+ # CLI
351
+ # ---------------------------------------------------------------------------
352
+
353
+ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
354
+ parser = argparse.ArgumentParser(
355
+ description="Install Agent Skills to supported AI CLI skill directories.",
356
+ formatter_class=argparse.RawDescriptionHelpFormatter,
357
+ epilog=__doc__,
358
+ )
359
+
360
+ parser.add_argument(
361
+ "--target", "-t",
362
+ choices=["all", *INSTALL_DIRS.keys()],
363
+ default="all",
364
+ help="Target platform (default: all supported AI CLIs).",
365
+ )
366
+ parser.add_argument(
367
+ "--skills", "-s",
368
+ default=None,
369
+ help="Comma-separated skill names to install (default: all).",
370
+ )
371
+ parser.add_argument(
372
+ "--force",
373
+ action="store_true",
374
+ help="Overwrite existing installed skills.",
375
+ )
376
+ parser.add_argument(
377
+ "--dry-run",
378
+ action="store_true",
379
+ help="Show what would be done without making any changes.",
380
+ )
381
+ parser.add_argument(
382
+ "--validate",
383
+ action="store_true",
384
+ help="Run validation on each skill before installing; skip invalid skills.",
385
+ )
386
+ parser.add_argument(
387
+ "--list-installed",
388
+ action="store_true",
389
+ help="Show currently installed skills with version info.",
390
+ )
391
+ parser.add_argument(
392
+ "--uninstall",
393
+ metavar="NAMES",
394
+ default=None,
395
+ help="Comma-separated skill names to uninstall.",
396
+ )
397
+
398
+ return parser.parse_args(argv)
399
+
400
+
401
+ def main(argv: list[str] | None = None) -> int:
402
+ args = parse_args(argv)
403
+
404
+ targets = list(INSTALL_DIRS) if args.target == "all" else [args.target]
405
+
406
+ # --list-installed
407
+ if args.list_installed:
408
+ for target in targets:
409
+ print(f"\nTarget: {target}")
410
+ list_installed(INSTALL_DIRS[target])
411
+ return 0
412
+
413
+ # --uninstall
414
+ if args.uninstall:
415
+ names = [n.strip().lower().replace(" ", "-") for n in args.uninstall.split(",") if n.strip()]
416
+ removal_order = [target for target in targets if target != CANONICAL_TARGET]
417
+ if CANONICAL_TARGET in targets:
418
+ removal_order.append(CANONICAL_TARGET)
419
+ for target in removal_order:
420
+ install_dir = INSTALL_DIRS[target]
421
+ print(f"\nUninstalling {len(names)} skill(s) from {target}:\n")
422
+ uninstall_skills(names, install_dir, dry_run=args.dry_run)
423
+ return 0
424
+
425
+ # Discover all skills in the repo
426
+ root = repo_root()
427
+ all_skills = find_all_skill_dirs(root)
428
+
429
+ if not all_skills:
430
+ print("ERROR: No skill files found in the repository.")
431
+ return 1
432
+
433
+ # Filter to requested skills if --skills was given
434
+ if args.skills:
435
+ requested = {
436
+ n.strip().lower().replace(" ", "-")
437
+ for n in args.skills.split(",")
438
+ if n.strip()
439
+ }
440
+ unknown = requested - all_skills.keys()
441
+ if unknown:
442
+ print(f"WARNING: Unknown skill(s): {', '.join(sorted(unknown))}")
443
+ skill_map = {k: v for k, v in all_skills.items() if k in requested}
444
+ if not skill_map:
445
+ print("ERROR: No matching skills found.")
446
+ return 1
447
+ else:
448
+ skill_map = all_skills
449
+
450
+ print(f"Skills to process: {len(skill_map)}")
451
+ if args.dry_run:
452
+ print("[DRY RUN — no files will be written]\n")
453
+ print()
454
+
455
+ print("\nCanonical skill store")
456
+ stored = install_skills(
457
+ skill_map=skill_map,
458
+ install_dir=INSTALL_DIRS[CANONICAL_TARGET],
459
+ force=args.force,
460
+ dry_run=args.dry_run,
461
+ do_validate=args.validate,
462
+ )
463
+ totals = {"linked": 0, "skipped": stored["skipped"], "failed": stored["failed"]}
464
+ for target in targets:
465
+ if target == CANONICAL_TARGET:
466
+ continue
467
+ result = link_skills(
468
+ skill_map=skill_map,
469
+ target=target,
470
+ force=args.force,
471
+ dry_run=args.dry_run,
472
+ )
473
+ totals["linked"] += result["linked"]
474
+ totals["skipped"] += result["skipped"]
475
+ totals["failed"] += result["failed"]
476
+
477
+ print(
478
+ f"\nTotal: {stored['stored']} stored, {totals['linked']} linked, "
479
+ f"{totals['skipped']} skipped, {totals['failed']} failed."
480
+ )
481
+
482
+ return 1 if totals["failed"] else 0
483
+
484
+
485
+ if __name__ == "__main__":
486
+ sys.exit(main())