parallel-web-tools 0.8.1rc1__tar.gz → 0.9.2__tar.gz

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.
Files changed (55) hide show
  1. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/PKG-INFO +3 -3
  2. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/__init__.py +1 -1
  3. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/cli/commands.py +10 -8
  4. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/cli/skills.py +41 -16
  5. parallel_web_tools-0.9.2/parallel_web_tools/core/skills.py +532 -0
  6. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/bigquery/cloud_function/requirements.txt +1 -1
  7. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/pyproject.toml +2 -2
  8. parallel_web_tools-0.8.1rc1/parallel_web_tools/core/skills.py +0 -305
  9. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/.gitignore +0 -0
  10. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/README.md +0 -0
  11. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/cli/__init__.py +0 -0
  12. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/cli/planner.py +0 -0
  13. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/cli/updater.py +0 -0
  14. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/__init__.py +0 -0
  15. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/auth.py +0 -0
  16. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/batch.py +0 -0
  17. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/credentials.py +0 -0
  18. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/endpoints.py +0 -0
  19. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/findall.py +0 -0
  20. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/memory.py +0 -0
  21. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/monitor.py +0 -0
  22. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/polling.py +0 -0
  23. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/research.py +0 -0
  24. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/result.py +0 -0
  25. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/runner.py +0 -0
  26. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/schema.py +0 -0
  27. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/service.py +0 -0
  28. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/service_types.py +0 -0
  29. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/sql_utils.py +0 -0
  30. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/core/user_agent.py +0 -0
  31. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/__init__.py +0 -0
  32. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/bigquery/__init__.py +0 -0
  33. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/bigquery/cloud_function/main.py +0 -0
  34. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/bigquery/deploy.py +0 -0
  35. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/bigquery/sql/create_functions.sql +0 -0
  36. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/duckdb/__init__.py +0 -0
  37. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/duckdb/batch.py +0 -0
  38. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/duckdb/findall.py +0 -0
  39. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/duckdb/udf.py +0 -0
  40. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/polars/__init__.py +0 -0
  41. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/polars/enrich.py +0 -0
  42. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/snowflake/__init__.py +0 -0
  43. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/snowflake/deploy.py +0 -0
  44. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/snowflake/sql/01_setup.sql +0 -0
  45. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/snowflake/sql/02_create_udf.sql +0 -0
  46. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/snowflake/sql/03_cleanup.sql +0 -0
  47. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/spark/__init__.py +0 -0
  48. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/spark/streaming.py +0 -0
  49. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/spark/udf.py +0 -0
  50. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/integrations/utils.py +0 -0
  51. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/processors/__init__.py +0 -0
  52. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/processors/bigquery.py +0 -0
  53. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/processors/csv.py +0 -0
  54. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/processors/duckdb.py +0 -0
  55. {parallel_web_tools-0.8.1rc1 → parallel_web_tools-0.9.2}/parallel_web_tools/processors/json.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: parallel-web-tools
3
- Version: 0.8.1rc1
3
+ Version: 0.9.2
4
4
  Summary: Parallel Tools: CLI and Python SDK for AI-powered web intelligence
5
5
  Project-URL: Homepage, https://github.com/parallel-web/parallel-web-tools
6
6
  Project-URL: Documentation, https://docs.parallel.ai
@@ -24,7 +24,7 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
24
  Requires-Python: >=3.10
25
25
  Requires-Dist: click>=8.1.0
26
26
  Requires-Dist: httpx>=0.25.0
27
- Requires-Dist: parallel-web<2,>=1.2.0
27
+ Requires-Dist: parallel-web<2,>=1.3.0
28
28
  Requires-Dist: python-dotenv>=1.0.0
29
29
  Requires-Dist: rich>=13.0.0
30
30
  Provides-Extra: all
@@ -43,7 +43,7 @@ from parallel_web_tools.core import (
43
43
  update_monitor,
44
44
  )
45
45
 
46
- __version__ = "0.8.1rc1"
46
+ __version__ = "0.9.2"
47
47
 
48
48
  __all__ = [
49
49
  # Auth
@@ -1088,18 +1088,19 @@ def memory_clear(memory_scope_key: str | None, confirm_clear: bool, output_json:
1088
1088
  # Search Command
1089
1089
  # =============================================================================
1090
1090
 
1091
- # Beta -> V1 mode mapping. Beta had three modes; V1 has three (turbo/basic/
1092
- # advanced). We keep the old values as accepted CLI inputs and translate them so
1093
- # existing scripts work.
1091
+ # Search mode translation. V1 accepts turbo/fast/basic/advanced natively; the
1092
+ # Beta-only values stay accepted CLI inputs and are translated so existing
1093
+ # scripts keep working. Beta's `fast` used to downgrade to basic, but V1 now has
1094
+ # a native fast mode of its own, so the name passes through.
1094
1095
  _SEARCH_MODE_MAP = {
1095
- "fast": "basic",
1096
- "one-shot": "basic",
1097
- "agentic": "advanced",
1098
1096
  "turbo": "turbo",
1097
+ "fast": "fast",
1099
1098
  "basic": "basic",
1100
1099
  "advanced": "advanced",
1100
+ "one-shot": "basic",
1101
+ "agentic": "advanced",
1101
1102
  }
1102
- _DEPRECATED_SEARCH_MODES = {"fast", "one-shot", "agentic"}
1103
+ _DEPRECATED_SEARCH_MODES = {"one-shot", "agentic"}
1103
1104
 
1104
1105
 
1105
1106
  def _emit_deprecation(message: str) -> None:
@@ -1166,7 +1167,8 @@ def build_search_v1_kwargs(
1166
1167
  "--mode",
1167
1168
  type=click.Choice(list(_SEARCH_MODE_MAP.keys())),
1168
1169
  default="basic",
1169
- help="Search mode: turbo (fastest), basic, or advanced (one-shot/fast → basic, agentic → advanced)",
1170
+ help="Search mode: turbo (fastest), fast (high quality within ~1s), basic, "
1171
+ "or advanced (highest quality; one-shot → basic, agentic → advanced)",
1170
1172
  show_default=True,
1171
1173
  )
1172
1174
  @click.option("--max-results", type=int, help="Maximum results (defaults to server-side default of 10)")
@@ -36,9 +36,29 @@ def create_skills_group(
36
36
  """Install and manage Parallel agent skills.
37
37
 
38
38
  Downloads come from skills.parallel.ai. Set PARALLEL_SKILLS_INDEX_URL to use a custom index.
39
+
40
+ Skills install to .agents/skills, and also to .claude/skills when a Claude Code
41
+ configuration directory is present, since Claude Code reads only its own directory.
39
42
  """
40
43
  pass
41
44
 
45
+ def print_locations(result: dict) -> None:
46
+ locations = result["install_dirs"]
47
+ label = "Locations" if len(locations) > 1 else "Location"
48
+ console.print(f"{label}: [cyan]{', '.join(locations)}[/cyan]")
49
+
50
+ def print_skipped(result: dict) -> None:
51
+ skipped = result.get("skipped_skills") or []
52
+ if not skipped:
53
+ return
54
+
55
+ console.print(f"[yellow]Skipped ({len(skipped)}):[/yellow]")
56
+ for entry in skipped:
57
+ console.print(
58
+ f"[yellow] {entry['skill']} — {entry['install_dir']}/{entry['skill']} already exists "
59
+ f"and was not installed by parallel-cli, so it was left untouched[/yellow]"
60
+ )
61
+
42
62
  @skills.command(name="list")
43
63
  @click.option("--json", "output_json", is_flag=True, help="Output as JSON")
44
64
  def skills_list(output_json: bool) -> None:
@@ -66,7 +86,8 @@ def create_skills_group(
66
86
  @click.option(
67
87
  "--project",
68
88
  is_flag=True,
69
- help="Install to .agents/skills in detected project root (default is global install).",
89
+ help="Install into the detected project root — .agents/skills, plus .claude/skills "
90
+ "when Claude Code is present (default is global install).",
70
91
  )
71
92
  @click.option(
72
93
  "--skill",
@@ -86,13 +107,13 @@ def create_skills_group(
86
107
  SkillsInputError,
87
108
  SkillsInstallLocationError,
88
109
  install_skills,
89
- resolve_install_dir,
110
+ resolve_install_dirs,
90
111
  )
91
112
 
92
113
  try:
93
- install_dir = resolve_install_dir(project=project)
114
+ install_dirs = resolve_install_dirs(project=project)
94
115
  result = install_skills(
95
- install_dir=install_dir,
116
+ install_dirs=install_dirs,
96
117
  selected_skills=list(skill_names) or None,
97
118
  )
98
119
  except SkillsInstallLocationError as e:
@@ -109,24 +130,26 @@ def create_skills_group(
109
130
  return
110
131
 
111
132
  console.print("[bold green]Skills installed[/bold green]")
112
- console.print(f"Location: [cyan]{result['install_dir']}[/cyan]")
133
+ print_locations(result)
113
134
  console.print(f"Ref: [cyan]{result['ref']}[/cyan]")
114
135
  console.print(f"Installed ({result['count']}): [cyan]{', '.join(result['installed_skills'])}[/cyan]")
136
+ console.print(f"Files written: [cyan]{result['file_count']}[/cyan]")
137
+ print_skipped(result)
115
138
 
116
139
  @skills.command(name="uninstall")
117
140
  @click.option(
118
141
  "--project",
119
142
  is_flag=True,
120
- help="Uninstall from .agents/skills in detected project root (default is global install).",
143
+ help="Uninstall from the detected project root's skill directories (default is global install).",
121
144
  )
122
145
  @click.option("--json", "output_json", is_flag=True, help="Output as JSON")
123
146
  def skills_uninstall(project: bool, output_json: bool) -> None:
124
147
  """Uninstall skills previously installed by parallel-cli."""
125
- from parallel_web_tools.core.skills import SkillsInstallLocationError, resolve_install_dir, uninstall_skills
148
+ from parallel_web_tools.core.skills import SkillsInstallLocationError, resolve_install_dirs, uninstall_skills
126
149
 
127
150
  try:
128
- install_dir = resolve_install_dir(project=project)
129
- result = uninstall_skills(install_dir=install_dir)
151
+ install_dirs = resolve_install_dirs(project=project)
152
+ result = uninstall_skills(install_dirs=install_dirs)
130
153
  except SkillsInstallLocationError as e:
131
154
  handle_error(e, output_json=output_json, exit_code=exit_bad_input, prefix="Skills uninstall failed")
132
155
  except Exception as e:
@@ -138,18 +161,18 @@ def create_skills_group(
138
161
 
139
162
  if result["count"] == 0:
140
163
  console.print("[yellow]No managed skills found to uninstall[/yellow]")
141
- console.print(f"Location: [cyan]{result['install_dir']}[/cyan]")
164
+ print_locations(result)
142
165
  return
143
166
 
144
167
  console.print("[bold green]Skills uninstalled[/bold green]")
145
- console.print(f"Location: [cyan]{result['install_dir']}[/cyan]")
168
+ print_locations(result)
146
169
  console.print(f"Removed ({result['count']}): [cyan]{', '.join(result['removed_skills'])}[/cyan]")
147
170
 
148
171
  @skills.command(name="reinstall")
149
172
  @click.option(
150
173
  "--project",
151
174
  is_flag=True,
152
- help="Reinstall in .agents/skills in detected project root (default is global install).",
175
+ help="Reinstall in the detected project root's skill directories (default is global install).",
153
176
  )
154
177
  @click.option(
155
178
  "--skill",
@@ -169,13 +192,13 @@ def create_skills_group(
169
192
  SkillsInputError,
170
193
  SkillsInstallLocationError,
171
194
  reinstall_skills,
172
- resolve_install_dir,
195
+ resolve_install_dirs,
173
196
  )
174
197
 
175
198
  try:
176
- install_dir = resolve_install_dir(project=project)
199
+ install_dirs = resolve_install_dirs(project=project)
177
200
  result = reinstall_skills(
178
- install_dir=install_dir,
201
+ install_dirs=install_dirs,
179
202
  selected_skills=list(skill_names) or None,
180
203
  )
181
204
  except SkillsInstallLocationError as e:
@@ -192,9 +215,11 @@ def create_skills_group(
192
215
  return
193
216
 
194
217
  console.print("[bold green]Skills reinstalled[/bold green]")
195
- console.print(f"Location: [cyan]{result['install_dir']}[/cyan]")
218
+ print_locations(result)
196
219
  console.print(f"Ref: [cyan]{result['ref']}[/cyan]")
197
220
  console.print(f"Removed ({result['removed_count']}): [cyan]{', '.join(result['removed_skills'])}[/cyan]")
198
221
  console.print(f"Installed ({result['installed_count']}): [cyan]{', '.join(result['installed_skills'])}[/cyan]")
222
+ console.print(f"Files written: [cyan]{result['file_count']}[/cyan]")
223
+ print_skipped(result)
199
224
 
200
225
  return skills
@@ -0,0 +1,532 @@
1
+ """Skill installation helpers for parallel-cli."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import shutil
9
+ import time
10
+ from collections.abc import Iterable, Iterator
11
+ from contextlib import contextmanager
12
+ from pathlib import Path, PurePosixPath, PureWindowsPath
13
+ from typing import Any
14
+
15
+ import httpx
16
+
17
+ DEFAULT_SKILLS_INDEX_URL = "https://skills.parallel.ai/index.json"
18
+ SKILLS_INDEX_URL_ENV = "PARALLEL_SKILLS_INDEX_URL"
19
+ DEFAULT_SKILLS_REPO_REF = "main"
20
+ SKILLS_REPO_REF_ENV = "PARALLEL_SKILLS_REPO_REF"
21
+ GLOBAL_SKILLS_DIR_ENV = "PARALLEL_SKILLS_GLOBAL_DIR"
22
+ CLAUDE_CONFIG_DIR_ENV = "CLAUDE_CONFIG_DIR"
23
+
24
+ PROJECT_ROOT_MARKERS = (".git", "pyproject.toml", "package.json")
25
+ MANIFEST_FILE_NAME = ".parallel-cli-skills-manifest.json"
26
+
27
+
28
+ class SkillsError(Exception):
29
+ """Base error for skills operations."""
30
+
31
+
32
+ class SkillsInstallLocationError(SkillsError):
33
+ """Raised when a project-local install directory cannot be determined."""
34
+
35
+
36
+ class SkillsDownloadError(SkillsError):
37
+ """Raised when remote skills metadata or files cannot be fetched."""
38
+
39
+
40
+ class SkillsInputError(SkillsError):
41
+ """Raised when caller-provided skill arguments are invalid."""
42
+
43
+
44
+ def get_skills_repo_ref() -> str:
45
+ """Return the legacy requested skills channel/ref override.
46
+
47
+ CDN-backed installs ignore this value and always use the channel advertised by
48
+ the remote index, but we keep the helper for backwards compatibility.
49
+ """
50
+ configured = os.environ.get(SKILLS_REPO_REF_ENV)
51
+ if configured and configured.strip():
52
+ return configured.strip()
53
+ return DEFAULT_SKILLS_REPO_REF
54
+
55
+
56
+ def get_skills_index_url() -> str:
57
+ """Return the CDN index URL used for skills downloads."""
58
+ configured = os.environ.get(SKILLS_INDEX_URL_ENV)
59
+ if configured and configured.strip():
60
+ return configured.strip()
61
+ return DEFAULT_SKILLS_INDEX_URL
62
+
63
+
64
+ def get_global_skills_dir() -> Path:
65
+ """Return the global skills directory path."""
66
+ configured = os.environ.get(GLOBAL_SKILLS_DIR_ENV)
67
+ if configured:
68
+ return Path(configured).expanduser()
69
+ return Path.home() / ".agents" / "skills"
70
+
71
+
72
+ def get_claude_config_dir() -> Path:
73
+ """Return the Claude Code configuration directory."""
74
+ configured = os.environ.get(CLAUDE_CONFIG_DIR_ENV)
75
+ if configured and configured.strip():
76
+ return Path(configured.strip()).expanduser()
77
+ return Path.home() / ".claude"
78
+
79
+
80
+ def find_project_root(start: Path | None = None) -> Path | None:
81
+ """Find a project root by walking upward for known root markers."""
82
+ cursor = (start or Path.cwd()).resolve()
83
+ for candidate in (cursor, *cursor.parents):
84
+ for marker in PROJECT_ROOT_MARKERS:
85
+ if (candidate / marker).exists():
86
+ return candidate
87
+ return None
88
+
89
+
90
+ def resolve_install_dir(project: bool, start: Path | None = None) -> Path:
91
+ """Resolve the canonical ``.agents/skills`` install directory."""
92
+ if not project:
93
+ return get_global_skills_dir()
94
+
95
+ root = find_project_root(start=start)
96
+ if root is None:
97
+ raise SkillsInstallLocationError(
98
+ "Could not determine project root from current directory. "
99
+ "Run this inside a project containing one of: .git, pyproject.toml, package.json."
100
+ )
101
+ return root / ".agents" / "skills"
102
+
103
+
104
+ def resolve_install_dirs(project: bool, start: Path | None = None) -> list[Path]:
105
+ """Resolve every directory skills should be installed into.
106
+
107
+ ``.agents/skills`` is the canonical cross-agent location and always comes first.
108
+ Claude Code does not read it — it only discovers skills under ``.claude/skills`` —
109
+ so when Claude Code is present we install there too. Agents that read both
110
+ (Cursor, for example) de-duplicate by skill name.
111
+
112
+ Global installs mirror into the Claude Code configuration directory when it
113
+ exists; its absence means no Claude Code on this machine. Project installs
114
+ mirror into ``<root>/.claude/skills``, created if needed whenever the machine
115
+ has Claude Code — a repo missing ``.claude`` just hasn't stored Claude settings
116
+ yet, and skipping it would leave the skills invisible to Claude Code there.
117
+
118
+ An explicit ``PARALLEL_SKILLS_GLOBAL_DIR`` override targets exactly one directory,
119
+ on the assumption that a caller naming a path wants only that path written.
120
+ """
121
+ canonical = resolve_install_dir(project=project, start=start)
122
+ if not project and os.environ.get(GLOBAL_SKILLS_DIR_ENV):
123
+ return [canonical]
124
+
125
+ if project:
126
+ claude_config_dir = canonical.parent.parent / ".claude"
127
+ if not claude_config_dir.is_dir() and not get_claude_config_dir().is_dir():
128
+ return [canonical]
129
+ else:
130
+ claude_config_dir = get_claude_config_dir()
131
+ if not claude_config_dir.is_dir():
132
+ return [canonical]
133
+
134
+ return _dedupe_dirs([canonical, claude_config_dir / "skills"])
135
+
136
+
137
+ def _dedupe_dirs(dirs: Iterable[Path]) -> list[Path]:
138
+ """Drop directories that resolve to the same location, preserving order.
139
+
140
+ A user who symlinked ``~/.claude/skills`` at ``~/.agents/skills`` would otherwise
141
+ have the same tree installed, and its manifest rewritten, twice.
142
+ """
143
+ seen: set[Path] = set()
144
+ unique: list[Path] = []
145
+ for directory in dirs:
146
+ resolved = Path(directory).expanduser().resolve()
147
+ if resolved in seen:
148
+ continue
149
+ seen.add(resolved)
150
+ unique.append(Path(directory))
151
+ return unique
152
+
153
+
154
+ def _normalize_install_dirs(install_dirs: Path | str | Iterable[Path | str]) -> list[Path]:
155
+ """Accept a single directory or a collection of them and return a clean list."""
156
+ if isinstance(install_dirs, (str, Path)):
157
+ candidates: list[Path | str] = [install_dirs]
158
+ else:
159
+ candidates = list(install_dirs)
160
+
161
+ if not candidates:
162
+ raise SkillsInstallLocationError("No skills install directory was provided.")
163
+
164
+ return _dedupe_dirs(Path(candidate) for candidate in candidates)
165
+
166
+
167
+ @contextmanager
168
+ def _skills_client() -> Iterator[httpx.Client]:
169
+ with httpx.Client(timeout=30, follow_redirects=True) as client:
170
+ yield client
171
+
172
+
173
+ def _fetch_json(client: httpx.Client, url: str, description: str) -> dict[str, Any]:
174
+ response = client.get(url)
175
+ if response.status_code >= 400:
176
+ raise SkillsDownloadError(f"Failed to download {description} from {url}: HTTP {response.status_code}")
177
+
178
+ try:
179
+ data = response.json()
180
+ except ValueError as e:
181
+ raise SkillsDownloadError(f"Failed to parse {description} from {url} as JSON") from e
182
+
183
+ if not isinstance(data, dict):
184
+ raise SkillsDownloadError(f"Expected {description} at {url} to be a JSON object")
185
+ return data
186
+
187
+
188
+ def _fetch_skills_index(client: httpx.Client) -> dict[str, Any]:
189
+ return _fetch_json(client, get_skills_index_url(), "skills index")
190
+
191
+
192
+ def _index_channel(index: dict[str, Any]) -> str:
193
+ channel = index.get("channel")
194
+ if isinstance(channel, str) and channel.strip():
195
+ return channel.strip()
196
+ return DEFAULT_SKILLS_REPO_REF
197
+
198
+
199
+ def _skills_from_index(index: dict[str, Any]) -> dict[str, dict[str, str]]:
200
+ raw_skills = index.get("skills")
201
+ if not isinstance(raw_skills, list):
202
+ raise SkillsDownloadError("Skills index is missing a valid 'skills' list")
203
+
204
+ parsed: dict[str, dict[str, str]] = {}
205
+ for raw_skill in raw_skills:
206
+ if not isinstance(raw_skill, dict):
207
+ raise SkillsDownloadError("Skills index contained an invalid skill entry")
208
+
209
+ name = raw_skill.get("name")
210
+ skill_url = raw_skill.get("skill_url")
211
+ if not isinstance(name, str) or not name.strip():
212
+ raise SkillsDownloadError("Skills index contained a skill with an invalid name")
213
+ if not isinstance(skill_url, str) or not skill_url.strip():
214
+ raise SkillsDownloadError(f"Skills index entry '{name}' is missing a valid skill_url")
215
+
216
+ entry = {
217
+ "name": name.strip(),
218
+ "skill_url": skill_url.strip(),
219
+ }
220
+
221
+ manifest_url = raw_skill.get("manifest_url")
222
+ if isinstance(manifest_url, str) and manifest_url.strip():
223
+ entry["manifest_url"] = manifest_url.strip()
224
+
225
+ parsed[name.strip()] = entry
226
+
227
+ return parsed
228
+
229
+
230
+ def _list_skills_from_index(index: dict[str, Any]) -> list[str]:
231
+ return sorted(_skills_from_index(index))
232
+
233
+
234
+ def _download_skill_file(client: httpx.Client, skill_name: str, skill_url: str) -> bytes:
235
+ response = client.get(skill_url)
236
+ if response.status_code >= 400:
237
+ raise SkillsDownloadError(
238
+ f"Failed to download skill '{skill_name}' from {skill_url}: HTTP {response.status_code}"
239
+ )
240
+ return response.content
241
+
242
+
243
+ def _safe_skill_file_path(skill_name: str, raw_path: str) -> str:
244
+ """Validate a manifest-declared relative path stays inside the skill directory.
245
+
246
+ Both path flavours are checked, not just the host's. POSIX rules alone accept
247
+ ``C:/outside/payload``, which pathlib then joins on Windows by discarding the
248
+ skill directory entirely — so a drive letter has to be rejected here even when
249
+ this code is running on Linux or macOS.
250
+ """
251
+ candidate = raw_path.strip().replace("\\", "/")
252
+ if not candidate:
253
+ raise SkillsDownloadError(f"Manifest for skill '{skill_name}' contained an empty file path")
254
+
255
+ posix_path = PurePosixPath(candidate)
256
+ windows_path = PureWindowsPath(candidate)
257
+ unsafe = (
258
+ posix_path.is_absolute()
259
+ or windows_path.is_absolute()
260
+ or bool(windows_path.drive)
261
+ or bool(windows_path.root)
262
+ or any(part in ("..", "") for part in posix_path.parts)
263
+ )
264
+ if unsafe:
265
+ raise SkillsDownloadError(f"Manifest for skill '{skill_name}' contained an unsafe file path: {raw_path}")
266
+
267
+ return str(posix_path)
268
+
269
+
270
+ def _contained_target(skill_name: str, skill_dir: Path, relative_path: str) -> Path:
271
+ """Join relative_path onto skill_dir, refusing anything that lands outside it.
272
+
273
+ A backstop for _safe_skill_file_path: string validation has to anticipate every
274
+ platform's join semantics, whereas this compares the resolved result.
275
+ """
276
+ target = skill_dir / relative_path
277
+ resolved_root = skill_dir.resolve()
278
+ if not target.resolve().is_relative_to(resolved_root):
279
+ raise SkillsDownloadError(f"Manifest for skill '{skill_name}' resolved outside its directory: {relative_path}")
280
+ return target
281
+
282
+
283
+ def _resolve_skill_files(client: httpx.Client, skill_name: str, entry: dict[str, str]) -> list[dict[str, str]]:
284
+ """Resolve every file belonging to a skill.
285
+
286
+ Indexes that advertise a ``manifest_url`` carry the full file list (references,
287
+ scripts, bundled agents). Older or custom indexes without one fall back to the
288
+ single ``SKILL.md`` document.
289
+ """
290
+ skill_only = [{"path": "SKILL.md", "url": entry["skill_url"], "sha256": ""}]
291
+
292
+ manifest_url = entry.get("manifest_url")
293
+ if not manifest_url:
294
+ return skill_only
295
+
296
+ manifest = _fetch_json(client, manifest_url, f"manifest for skill '{skill_name}'")
297
+ raw_files = manifest.get("files")
298
+ if not isinstance(raw_files, list) or not raw_files:
299
+ return skill_only
300
+
301
+ resolved: list[dict[str, str]] = []
302
+ for raw_file in raw_files:
303
+ if not isinstance(raw_file, dict):
304
+ raise SkillsDownloadError(f"Manifest for skill '{skill_name}' contained an invalid file entry")
305
+
306
+ raw_path = raw_file.get("path")
307
+ file_url = raw_file.get("url")
308
+ if not isinstance(raw_path, str) or not isinstance(file_url, str) or not file_url.strip():
309
+ raise SkillsDownloadError(f"Manifest for skill '{skill_name}' contained a file entry missing path or url")
310
+
311
+ checksum = raw_file.get("sha256")
312
+ resolved.append(
313
+ {
314
+ "path": _safe_skill_file_path(skill_name, raw_path),
315
+ "url": file_url.strip(),
316
+ "sha256": checksum.strip().lower() if isinstance(checksum, str) else "",
317
+ }
318
+ )
319
+
320
+ if not any(file_entry["path"] == "SKILL.md" for file_entry in resolved):
321
+ raise SkillsDownloadError(f"Manifest for skill '{skill_name}' does not include a SKILL.md entry")
322
+
323
+ return resolved
324
+
325
+
326
+ def _verify_skill_file_checksum(skill_name: str, file_entry: dict[str, str], content: bytes) -> None:
327
+ expected = file_entry.get("sha256")
328
+ if not expected:
329
+ return
330
+
331
+ actual = hashlib.sha256(content).hexdigest()
332
+ if actual != expected:
333
+ raise SkillsDownloadError(
334
+ f"Checksum mismatch for '{skill_name}/{file_entry['path']}': expected {expected}, got {actual}"
335
+ )
336
+
337
+
338
+ def get_remote_skills_channel() -> str:
339
+ """Return the channel advertised by the remote CDN index."""
340
+ with _skills_client() as client:
341
+ index = _fetch_skills_index(client)
342
+ return _index_channel(index)
343
+
344
+
345
+ def list_remote_skills(ref: str | None = None) -> list[str]:
346
+ """Return available skill names from the CDN index.
347
+
348
+ The ref argument is ignored for CDN-backed installs.
349
+ """
350
+ del ref
351
+ with _skills_client() as client:
352
+ index = _fetch_skills_index(client)
353
+ return _list_skills_from_index(index)
354
+
355
+
356
+ def _manifest_path(install_dir: Path) -> Path:
357
+ return install_dir / MANIFEST_FILE_NAME
358
+
359
+
360
+ def _write_manifest(install_dir: Path, ref: str, installed_skills: list[str]) -> None:
361
+ data = {
362
+ "source": get_skills_index_url(),
363
+ "ref": ref,
364
+ "installed_skills": sorted(installed_skills),
365
+ "installed_at": int(time.time()),
366
+ "managed_by": "parallel-cli",
367
+ }
368
+ install_dir.mkdir(parents=True, exist_ok=True)
369
+ _manifest_path(install_dir).write_text(json.dumps(data, indent=2))
370
+
371
+
372
+ def _read_manifest(install_dir: Path) -> dict:
373
+ path = _manifest_path(install_dir)
374
+ if not path.exists():
375
+ return {}
376
+ try:
377
+ data = json.loads(path.read_text())
378
+ except Exception:
379
+ return {}
380
+ return data if isinstance(data, dict) else {}
381
+
382
+
383
+ def _managed_skills(install_dir: Path) -> list[str]:
384
+ """Return the skill names parallel-cli previously installed into install_dir."""
385
+ managed_raw = _read_manifest(install_dir).get("installed_skills")
386
+ if not isinstance(managed_raw, list):
387
+ return []
388
+ return [name for name in managed_raw if isinstance(name, str)]
389
+
390
+
391
+ def install_skills(
392
+ install_dirs: Path | str | Iterable[Path | str],
393
+ selected_skills: list[str] | None = None,
394
+ ref: str | None = None,
395
+ ) -> dict:
396
+ """Install selected (or all) skills into every directory in install_dirs.
397
+
398
+ Only skills previously managed by parallel-cli are reconciled. Unmanaged skill
399
+ directories are left untouched, including one that merely shares a name with a
400
+ skill being installed — that one is reported in ``skipped_skills`` instead. Every
401
+ file is downloaded once and written to each directory, so a mid-download failure
402
+ leaves no location partially installed.
403
+ """
404
+ del ref
405
+
406
+ targets = _normalize_install_dirs(install_dirs)
407
+
408
+ with _skills_client() as client:
409
+ index = _fetch_skills_index(client)
410
+ resolved_ref = _index_channel(index)
411
+ available_skills = _skills_from_index(index)
412
+ available = sorted(available_skills)
413
+ requested = sorted(set(selected_skills or available))
414
+ missing = sorted(name for name in requested if name not in available_skills)
415
+ if missing:
416
+ raise SkillsInputError(
417
+ f"Unknown skills requested: {', '.join(missing)}. Available skills: {', '.join(available)}"
418
+ )
419
+
420
+ downloads: dict[str, list[tuple[str, bytes]]] = {}
421
+ for skill_name in requested:
422
+ skill_files = _resolve_skill_files(client, skill_name, available_skills[skill_name])
423
+ payload: list[tuple[str, bytes]] = []
424
+ for file_entry in skill_files:
425
+ content = _download_skill_file(client, skill_name, file_entry["url"])
426
+ _verify_skill_file_checksum(skill_name, file_entry, content)
427
+ payload.append((file_entry["path"], content))
428
+ downloads[skill_name] = payload
429
+
430
+ file_count = 0
431
+ installed_anywhere: set[str] = set()
432
+ skipped: list[dict[str, str]] = []
433
+ for install_dir in targets:
434
+ previously_managed = set(_managed_skills(install_dir))
435
+ install_dir.mkdir(parents=True, exist_ok=True)
436
+
437
+ for skill_name in previously_managed:
438
+ if skill_name not in requested:
439
+ stale_dir = install_dir / skill_name
440
+ if stale_dir.exists() and stale_dir.is_dir():
441
+ shutil.rmtree(stale_dir)
442
+
443
+ # Ownership is decided before anything is written. A directory we did not
444
+ # install is someone else's skill: overwriting it would destroy their work,
445
+ # and recording it would make uninstall delete it later, so it is left alone
446
+ # and kept out of the manifest.
447
+ to_install: list[str] = []
448
+ for skill_name in downloads:
449
+ skill_dir = install_dir / skill_name
450
+ if skill_dir.exists() and skill_name not in previously_managed:
451
+ skipped.append({"skill": skill_name, "install_dir": str(install_dir)})
452
+ continue
453
+ to_install.append(skill_name)
454
+
455
+ # Claim ownership up front. An install killed partway through — Ctrl-C, full
456
+ # disk — then leaves directories this CLI still recognizes as its own, so the
457
+ # next install replaces them and uninstall can clean them up. Writing the
458
+ # manifest afterwards instead would strand those partial trees: absent from
459
+ # the manifest, they would be mistaken for a user's work and skipped forever.
460
+ _write_manifest(install_dir, resolved_ref, to_install)
461
+
462
+ for skill_name in to_install:
463
+ skill_dir = install_dir / skill_name
464
+ if skill_dir.exists():
465
+ shutil.rmtree(skill_dir)
466
+ skill_dir.mkdir(parents=True, exist_ok=True)
467
+
468
+ for relative_path, content in downloads[skill_name]:
469
+ target = _contained_target(skill_name, skill_dir, relative_path)
470
+ target.parent.mkdir(parents=True, exist_ok=True)
471
+ target.write_bytes(content)
472
+
473
+ installed_anywhere.add(skill_name)
474
+ file_count += len(downloads[skill_name])
475
+
476
+ return {
477
+ "install_dirs": [str(directory) for directory in targets],
478
+ "ref": resolved_ref,
479
+ "installed_skills": sorted(installed_anywhere),
480
+ "count": len(installed_anywhere),
481
+ "skipped_skills": skipped,
482
+ "file_count": file_count,
483
+ }
484
+
485
+
486
+ def uninstall_skills(install_dirs: Path | str | Iterable[Path | str]) -> dict:
487
+ """Uninstall only manifest-managed skills from every directory in install_dirs."""
488
+ targets = _normalize_install_dirs(install_dirs)
489
+ removed: set[str] = set()
490
+
491
+ for install_dir in targets:
492
+ for skill_name in _managed_skills(install_dir):
493
+ skill_path = install_dir / skill_name
494
+ if skill_path.exists() and skill_path.is_dir():
495
+ shutil.rmtree(skill_path)
496
+ removed.add(skill_name)
497
+
498
+ manifest_path = _manifest_path(install_dir)
499
+ if manifest_path.exists():
500
+ manifest_path.unlink()
501
+
502
+ return {
503
+ "install_dirs": [str(directory) for directory in targets],
504
+ "removed_skills": sorted(removed),
505
+ "count": len(removed),
506
+ }
507
+
508
+
509
+ def reinstall_skills(
510
+ install_dirs: Path | str | Iterable[Path | str],
511
+ selected_skills: list[str] | None = None,
512
+ ref: str | None = None,
513
+ ) -> dict:
514
+ """Reinstall skills by uninstalling managed set then installing fresh.
515
+
516
+ Targets are normalized once up front: a one-shot iterable would otherwise be
517
+ consumed by the uninstall, leaving the install with nothing to write after the
518
+ existing skills had already been removed.
519
+ """
520
+ targets = _normalize_install_dirs(install_dirs)
521
+ uninstall_result = uninstall_skills(targets)
522
+ install_result = install_skills(targets, selected_skills=selected_skills, ref=ref)
523
+ return {
524
+ "install_dirs": install_result["install_dirs"],
525
+ "ref": install_result["ref"],
526
+ "removed_skills": uninstall_result["removed_skills"],
527
+ "installed_skills": install_result["installed_skills"],
528
+ "skipped_skills": install_result["skipped_skills"],
529
+ "removed_count": uninstall_result["count"],
530
+ "installed_count": install_result["count"],
531
+ "file_count": install_result["file_count"],
532
+ }
@@ -1,5 +1,5 @@
1
1
  # Cloud Function dependencies for BigQuery Remote Function
2
2
  functions-framework>=3.0.0
3
3
  flask>=3.0.0
4
- parallel-web-tools>=0.8.1rc1
4
+ parallel-web-tools>=0.9.2
5
5
  google-cloud-secret-manager>=2.20.0
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "parallel-web-tools"
7
- version = "0.8.1rc1"
7
+ version = "0.9.2"
8
8
  description = "Parallel Tools: CLI and Python SDK for AI-powered web intelligence"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -29,7 +29,7 @@ classifiers = [
29
29
  ]
30
30
 
31
31
  dependencies = [
32
- "parallel-web>=1.2.0,<2",
32
+ "parallel-web>=1.3.0,<2",
33
33
  "python-dotenv>=1.0.0",
34
34
  # CLI dependencies (minimal - search, extract, enrich with CLI args)
35
35
  "click>=8.1.0",
@@ -1,305 +0,0 @@
1
- """Skill installation helpers for parallel-cli."""
2
-
3
- from __future__ import annotations
4
-
5
- import json
6
- import os
7
- import shutil
8
- import time
9
- from collections.abc import Iterator
10
- from contextlib import contextmanager
11
- from pathlib import Path
12
- from typing import Any
13
-
14
- import httpx
15
-
16
- DEFAULT_SKILLS_INDEX_URL = "https://skills.parallel.ai/index.json"
17
- SKILLS_INDEX_URL_ENV = "PARALLEL_SKILLS_INDEX_URL"
18
- DEFAULT_SKILLS_REPO_REF = "main"
19
- SKILLS_REPO_REF_ENV = "PARALLEL_SKILLS_REPO_REF"
20
- GLOBAL_SKILLS_DIR_ENV = "PARALLEL_SKILLS_GLOBAL_DIR"
21
-
22
- PROJECT_ROOT_MARKERS = (".git", "pyproject.toml", "package.json")
23
- MANIFEST_FILE_NAME = ".parallel-cli-skills-manifest.json"
24
-
25
-
26
- class SkillsError(Exception):
27
- """Base error for skills operations."""
28
-
29
-
30
- class SkillsInstallLocationError(SkillsError):
31
- """Raised when a project-local install directory cannot be determined."""
32
-
33
-
34
- class SkillsDownloadError(SkillsError):
35
- """Raised when remote skills metadata or files cannot be fetched."""
36
-
37
-
38
- class SkillsInputError(SkillsError):
39
- """Raised when caller-provided skill arguments are invalid."""
40
-
41
-
42
- def get_skills_repo_ref() -> str:
43
- """Return the legacy requested skills channel/ref override.
44
-
45
- CDN-backed installs ignore this value and always use the channel advertised by
46
- the remote index, but we keep the helper for backwards compatibility.
47
- """
48
- configured = os.environ.get(SKILLS_REPO_REF_ENV)
49
- if configured and configured.strip():
50
- return configured.strip()
51
- return DEFAULT_SKILLS_REPO_REF
52
-
53
-
54
- def get_skills_index_url() -> str:
55
- """Return the CDN index URL used for skills downloads."""
56
- configured = os.environ.get(SKILLS_INDEX_URL_ENV)
57
- if configured and configured.strip():
58
- return configured.strip()
59
- return DEFAULT_SKILLS_INDEX_URL
60
-
61
-
62
- def get_global_skills_dir() -> Path:
63
- """Return the global skills directory path."""
64
- configured = os.environ.get(GLOBAL_SKILLS_DIR_ENV)
65
- if configured:
66
- return Path(configured).expanduser()
67
- return Path.home() / ".agents" / "skills"
68
-
69
-
70
- def find_project_root(start: Path | None = None) -> Path | None:
71
- """Find a project root by walking upward for known root markers."""
72
- cursor = (start or Path.cwd()).resolve()
73
- for candidate in (cursor, *cursor.parents):
74
- for marker in PROJECT_ROOT_MARKERS:
75
- if (candidate / marker).exists():
76
- return candidate
77
- return None
78
-
79
-
80
- def resolve_install_dir(project: bool, start: Path | None = None) -> Path:
81
- """Resolve install directory for global or project-local skills."""
82
- if not project:
83
- return get_global_skills_dir()
84
-
85
- root = find_project_root(start=start)
86
- if root is None:
87
- raise SkillsInstallLocationError(
88
- "Could not determine project root from current directory. "
89
- "Run this inside a project containing one of: .git, pyproject.toml, package.json."
90
- )
91
- return root / ".agents" / "skills"
92
-
93
-
94
- @contextmanager
95
- def _skills_client() -> Iterator[httpx.Client]:
96
- with httpx.Client(timeout=30, follow_redirects=True) as client:
97
- yield client
98
-
99
-
100
- def _fetch_json(client: httpx.Client, url: str, description: str) -> dict[str, Any]:
101
- response = client.get(url)
102
- if response.status_code >= 400:
103
- raise SkillsDownloadError(f"Failed to download {description} from {url}: HTTP {response.status_code}")
104
-
105
- try:
106
- data = response.json()
107
- except ValueError as e:
108
- raise SkillsDownloadError(f"Failed to parse {description} from {url} as JSON") from e
109
-
110
- if not isinstance(data, dict):
111
- raise SkillsDownloadError(f"Expected {description} at {url} to be a JSON object")
112
- return data
113
-
114
-
115
- def _fetch_skills_index(client: httpx.Client) -> dict[str, Any]:
116
- return _fetch_json(client, get_skills_index_url(), "skills index")
117
-
118
-
119
- def _index_channel(index: dict[str, Any]) -> str:
120
- channel = index.get("channel")
121
- if isinstance(channel, str) and channel.strip():
122
- return channel.strip()
123
- return DEFAULT_SKILLS_REPO_REF
124
-
125
-
126
- def _skills_from_index(index: dict[str, Any]) -> dict[str, dict[str, str]]:
127
- raw_skills = index.get("skills")
128
- if not isinstance(raw_skills, list):
129
- raise SkillsDownloadError("Skills index is missing a valid 'skills' list")
130
-
131
- parsed: dict[str, dict[str, str]] = {}
132
- for raw_skill in raw_skills:
133
- if not isinstance(raw_skill, dict):
134
- raise SkillsDownloadError("Skills index contained an invalid skill entry")
135
-
136
- name = raw_skill.get("name")
137
- skill_url = raw_skill.get("skill_url")
138
- if not isinstance(name, str) or not name.strip():
139
- raise SkillsDownloadError("Skills index contained a skill with an invalid name")
140
- if not isinstance(skill_url, str) or not skill_url.strip():
141
- raise SkillsDownloadError(f"Skills index entry '{name}' is missing a valid skill_url")
142
-
143
- parsed[name.strip()] = {
144
- "name": name.strip(),
145
- "skill_url": skill_url.strip(),
146
- }
147
-
148
- return parsed
149
-
150
-
151
- def _list_skills_from_index(index: dict[str, Any]) -> list[str]:
152
- return sorted(_skills_from_index(index))
153
-
154
-
155
- def _download_skill_markdown(client: httpx.Client, skill_name: str, skill_url: str) -> bytes:
156
- response = client.get(skill_url)
157
- if response.status_code >= 400:
158
- raise SkillsDownloadError(
159
- f"Failed to download skill '{skill_name}' from {skill_url}: HTTP {response.status_code}"
160
- )
161
- return response.content
162
-
163
-
164
- def get_remote_skills_channel() -> str:
165
- """Return the channel advertised by the remote CDN index."""
166
- with _skills_client() as client:
167
- index = _fetch_skills_index(client)
168
- return _index_channel(index)
169
-
170
-
171
- def list_remote_skills(ref: str | None = None) -> list[str]:
172
- """Return available skill names from the CDN index.
173
-
174
- The ref argument is ignored for CDN-backed installs.
175
- """
176
- del ref
177
- with _skills_client() as client:
178
- index = _fetch_skills_index(client)
179
- return _list_skills_from_index(index)
180
-
181
-
182
- def _manifest_path(install_dir: Path) -> Path:
183
- return install_dir / MANIFEST_FILE_NAME
184
-
185
-
186
- def _write_manifest(install_dir: Path, ref: str, installed_skills: list[str]) -> None:
187
- data = {
188
- "source": get_skills_index_url(),
189
- "ref": ref,
190
- "installed_skills": sorted(installed_skills),
191
- "installed_at": int(time.time()),
192
- "managed_by": "parallel-cli",
193
- }
194
- install_dir.mkdir(parents=True, exist_ok=True)
195
- _manifest_path(install_dir).write_text(json.dumps(data, indent=2))
196
-
197
-
198
- def _read_manifest(install_dir: Path) -> dict:
199
- path = _manifest_path(install_dir)
200
- if not path.exists():
201
- return {}
202
- try:
203
- data = json.loads(path.read_text())
204
- except Exception:
205
- return {}
206
- return data if isinstance(data, dict) else {}
207
-
208
-
209
- def install_skills(
210
- install_dir: Path,
211
- selected_skills: list[str] | None = None,
212
- ref: str | None = None,
213
- ) -> dict:
214
- """Install selected (or all) skills into install_dir.
215
-
216
- Only skills previously managed by parallel-cli are reconciled. Unmanaged skill
217
- directories are left untouched.
218
- """
219
- del ref
220
-
221
- with _skills_client() as client:
222
- index = _fetch_skills_index(client)
223
- resolved_ref = _index_channel(index)
224
- available_skills = _skills_from_index(index)
225
- available = sorted(available_skills)
226
- requested = sorted(set(selected_skills or available))
227
- missing = sorted(name for name in requested if name not in available_skills)
228
- if missing:
229
- raise SkillsInputError(
230
- f"Unknown skills requested: {', '.join(missing)}. Available skills: {', '.join(available)}"
231
- )
232
-
233
- manifest = _read_manifest(install_dir)
234
- managed_raw = manifest.get("installed_skills")
235
- previously_managed: list[str] = (
236
- [name for name in managed_raw if isinstance(name, str)] if isinstance(managed_raw, list) else []
237
- )
238
-
239
- install_dir.mkdir(parents=True, exist_ok=True)
240
-
241
- for skill_name in previously_managed:
242
- if skill_name not in requested:
243
- skill_dir = install_dir / skill_name
244
- if skill_dir.exists() and skill_dir.is_dir():
245
- shutil.rmtree(skill_dir)
246
-
247
- for skill_name in requested:
248
- skill_dir = install_dir / skill_name
249
- if skill_dir.exists():
250
- shutil.rmtree(skill_dir)
251
- skill_dir.mkdir(parents=True, exist_ok=True)
252
- skill_bytes = _download_skill_markdown(client, skill_name, available_skills[skill_name]["skill_url"])
253
- (skill_dir / "SKILL.md").write_bytes(skill_bytes)
254
-
255
- _write_manifest(install_dir, resolved_ref, requested)
256
- return {
257
- "install_dir": str(install_dir),
258
- "ref": resolved_ref,
259
- "installed_skills": requested,
260
- "count": len(requested),
261
- }
262
-
263
-
264
- def uninstall_skills(install_dir: Path) -> dict:
265
- """Uninstall only manifest-managed skills from install_dir."""
266
- manifest = _read_manifest(install_dir)
267
- managed_raw = manifest.get("installed_skills")
268
- managed: list[str] = (
269
- [name for name in managed_raw if isinstance(name, str)] if isinstance(managed_raw, list) else []
270
- )
271
- removed: list[str] = []
272
-
273
- for skill_name in managed:
274
- skill_path = install_dir / skill_name
275
- if skill_path.exists() and skill_path.is_dir():
276
- shutil.rmtree(skill_path)
277
- removed.append(skill_name)
278
-
279
- manifest_path = _manifest_path(install_dir)
280
- if manifest_path.exists():
281
- manifest_path.unlink()
282
-
283
- return {
284
- "install_dir": str(install_dir),
285
- "removed_skills": sorted(removed),
286
- "count": len(removed),
287
- }
288
-
289
-
290
- def reinstall_skills(
291
- install_dir: Path,
292
- selected_skills: list[str] | None = None,
293
- ref: str | None = None,
294
- ) -> dict:
295
- """Reinstall skills by uninstalling managed set then installing fresh."""
296
- uninstall_result = uninstall_skills(install_dir)
297
- install_result = install_skills(install_dir, selected_skills=selected_skills, ref=ref)
298
- return {
299
- "install_dir": install_result["install_dir"],
300
- "ref": install_result["ref"],
301
- "removed_skills": uninstall_result["removed_skills"],
302
- "installed_skills": install_result["installed_skills"],
303
- "removed_count": uninstall_result["count"],
304
- "installed_count": install_result["count"],
305
- }