Repository navigation
Expand file tree
/
Copy pathskill_manager.py
More file actions
executable file
·263 lines (238 loc) · 10.5 KB
/
Copy pathskill_manager.py
File metadata and controls
executable file
·263 lines (238 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#!/usr/bin/env python3
"""Browse, install, and remove local skills for Codex and Claude Code."""
import json
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import sys
import tarfile
import tempfile
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
CATALOG = ROOT / "skills.catalog.json"
AGENTS = {"codex": "Codex", "claude": "Claude Code"}
MAX_ARCHIVE = 150 * 1024 * 1024
MAX_SKILL = 80 * 1024 * 1024
def choose(title, options):
print("\n" + title)
for i, label in enumerate(options, 1):
print(f" {i}. {label}")
while True:
answer = input("Choose a number (or q to cancel): ").strip().lower()
if answer in ("q", ""):
return None
if answer.isdigit() and 1 <= int(answer) <= len(options):
return int(answer) - 1
print("Choose one of the displayed numbers.")
def choose_many(title, options):
print("\n" + title)
for i, label in enumerate(options, 1):
print(f" {i}. {label}")
while True:
answer = input("Numbers separated by commas (or Enter to cancel): ").strip()
if not answer or answer.lower() == "q":
return []
try:
numbers = [int(part.strip()) for part in answer.replace(" ", ",").split(",") if part.strip()]
if not numbers or any(n < 1 or n > len(options) for n in numbers):
raise ValueError
return list(dict.fromkeys(n - 1 for n in numbers))
except ValueError:
print("Enter numbers from the list, separated by commas.")
def confirm(prompt):
while True:
answer = input(prompt + " [y/N] ").strip().lower()
if answer in ("", "n", "no"):
return False
if answer in ("y", "yes"):
return True
print("Please answer yes or no.")
def destination(agent, scope, project=None):
if agent not in AGENTS or scope not in ("global", "project"):
raise ValueError("Unsupported agent or scope")
if scope == "global":
return Path.home() / (".agents/skills" if agent == "codex" else ".claude/skills")
if not project or not Path(project).expanduser().is_dir():
raise ValueError("Project path must be an existing directory")
return Path(project).expanduser().resolve() / (".agents/skills" if agent == "codex" else ".claude/skills")
def get_archive(repository, commit, directory):
if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository) or not re.fullmatch(r"[0-9a-f]{40}", commit):
raise ValueError("Invalid catalog repository or commit")
archive = Path(directory) / (repository.replace("/", "--") + ".tar.gz")
if archive.exists():
return archive
request = urllib.request.Request(f"https://codeload.github.com/{repository}/tar.gz/{commit}", headers={"User-Agent": "linux-setup/1"})
try:
with urllib.request.urlopen(request, timeout=90) as response, archive.open("wb") as out:
total = 0
while True:
chunk = response.read(1024 * 1024)
if not chunk:
break
total += len(chunk)
if total > MAX_ARCHIVE:
raise ValueError("Skill archive exceeds the download limit")
out.write(chunk)
except BaseException:
archive.unlink(missing_ok=True)
raise
return archive
def unpack_skill(archive, item, stage):
"""Copy regular files from exactly one skill directory, without following links."""
prefix = PurePosixPath(item["path"])
if prefix.is_absolute() or ".." in prefix.parts:
raise ValueError("Invalid skill path in catalog")
seen, total = set(), 0
with tarfile.open(archive, "r:gz") as bundle:
for member in bundle:
parts = PurePosixPath(member.name).parts
if len(parts) < 2:
continue
relative = PurePosixPath(*parts[1:])
if relative.is_absolute() or ".." in relative.parts:
raise ValueError("Unsafe path in skill archive")
try:
target_path = relative.relative_to(prefix)
except ValueError:
continue
if str(target_path) == "." or member.isdir():
continue
if item.get("root_files") and str(target_path) not in item["root_files"]:
continue
if not member.isfile() or str(target_path) in seen:
raise ValueError(f"Unsafe or duplicate skill file: {target_path}")
seen.add(str(target_path))
total += member.size
if total > MAX_SKILL:
raise ValueError("Skill exceeds the extracted size limit")
target = stage.joinpath(*target_path.parts)
target.parent.mkdir(parents=True, exist_ok=True)
with bundle.extractfile(member) as source, target.open("wb") as out:
shutil.copyfileobj(source, out)
target.chmod(0o755 if member.mode & 0o111 else 0o644)
if not (stage / "SKILL.md").is_file():
raise ValueError("Selected source does not contain SKILL.md")
def install_skill(item, repository, root, temp):
name = item["id"]
if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", name):
raise ValueError("Invalid skill name in catalog")
target = root / name
if target.exists() or target.is_symlink():
print(f"Keeping existing skill: {target}")
return False
print(f"Downloading {name} from https://github.com/{repository['repo']} at {repository['commit']} ...", flush=True)
archive = get_archive(repository["repo"], repository["commit"], temp)
with tempfile.TemporaryDirectory(prefix="linux-skill-stage-") as staged:
stage = Path(staged)
unpack_skill(archive, item, stage)
if item.get("adapt_uiux"):
skill = stage / "SKILL.md"
text = skill.read_text()
old = '${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max'
if old not in text:
raise ValueError("UI/UX Pro Max path format changed; catalog needs review")
escaped = str(target).replace('\\', '\\\\').replace('"', '\\"').replace('$', '\\$').replace('`', '\\`')
skill.write_text(text.replace(old, escaped))
root.mkdir(parents=True, exist_ok=True)
target.mkdir() # Exclusive: do not replace an existing skill.
try:
shutil.copytree(stage, target, dirs_exist_ok=True)
except BaseException:
shutil.rmtree(target)
raise
print(f"Installed {name}: {target}")
return True
def list_installed(root):
if not root.is_dir():
return []
return sorted((p for p in root.iterdir() if not p.name.startswith('.') and p.is_dir() and (p / 'SKILL.md').is_file()), key=lambda p: p.name.lower())
def remove_skills(root):
installed = list_installed(root)
if not installed:
print(f"No skills found in {root}.")
return
selected = choose_many("Select installed skills to remove", [p.name + (" (symlink; target kept)" if p.is_symlink() else "") for p in installed])
if not selected:
return
chosen = [installed[i] for i in selected]
print("The following skill directories will be deleted:")
for path in chosen:
print(" " + str(path))
if confirm("Remove these skills?"):
for path in chosen:
if path.is_symlink():
path.unlink()
elif path.is_dir():
shutil.rmtree(path)
else:
print(f"Skipping changed path: {path}")
continue
print(f"Removed {path.name}")
def install_menu(catalog, agent, root):
available = [item for item in catalog['skills'] if agent in item['agents']]
areas = sorted({area for item in available for area in item['areas']})
area = choose("Choose your area", areas + ["All skills"])
if area is None:
return
entries = available if area == len(areas) else [item for item in available if areas[area] in item['areas']]
labels = [f"{item['id']} — {item['description']} ({catalog['repositories'][item['repository']]['repo']})" for item in entries]
selected = choose_many("Select skills to install", labels)
if not selected:
return
print(f"Destination: {root}")
print("Skills are third-party instructions and may include scripts. Review their sources before use.")
for i in selected:
item = entries[i]
repo = catalog['repositories'][item['repository']]
print(f" {item['id']}: https://github.com/{repo['repo']}/tree/{repo['commit']}/{item['path']}")
if not confirm("Install these skills?"):
return
with tempfile.TemporaryDirectory(prefix="linux-skills-download-") as temp:
for i in selected:
item = entries[i]
try:
install_skill(item, catalog['repositories'][item['repository']], root, temp)
except (OSError, ValueError, tarfile.TarError) as error:
print(f"Could not install {item['id']}: {error}", file=sys.stderr)
print("Restart your agent session if it does not discover new skills immediately.")
def main():
if not sys.stdin.isatty():
print("skill-manager requires an interactive terminal.", file=sys.stderr)
return 1
catalog = json.loads(CATALOG.read_text())
while True:
action = choose("AI skill manager", ["Install skills", "Review or remove installed skills", "Exit"])
if action is None or action == 2:
return 0
agent_index = choose("Choose your AI agent", list(AGENTS.values()))
if agent_index is None:
continue
agent = list(AGENTS)[agent_index]
scope = choose("Choose the scope", ["Global (all projects)", "Project"])
if scope is None:
continue
project = None
if scope == 1:
project = input("Existing project directory (absolute path, or . for current directory): ").strip()
if not project:
continue
try:
root = destination(agent, "global" if scope == 0 else "project", project)
except ValueError as error:
print(error)
continue
print(f"Skill directory: {root}")
if action == 0:
install_menu(catalog, agent, root)
else:
remove_skills(root)
if __name__ == "__main__":
try:
sys.exit(main())
except (EOFError, KeyboardInterrupt):
print("\nCancelled.")
sys.exit(0)
except (OSError, ValueError, json.JSONDecodeError) as error:
print(f"skill-manager: {error}", file=sys.stderr)
sys.exit(1)