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