parallel-web-tools 0.8.1__tar.gz → 0.8.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.1 → parallel_web_tools-0.8.2}/PKG-INFO +1 -1
  2. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/__init__.py +1 -1
  3. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/cli/skills.py +37 -13
  4. parallel_web_tools-0.8.2/parallel_web_tools/core/skills.py +521 -0
  5. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/bigquery/cloud_function/requirements.txt +1 -1
  6. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/pyproject.toml +1 -1
  7. parallel_web_tools-0.8.1/parallel_web_tools/core/skills.py +0 -305
  8. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/.gitignore +0 -0
  9. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/README.md +0 -0
  10. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/cli/__init__.py +0 -0
  11. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/cli/commands.py +0 -0
  12. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/cli/planner.py +0 -0
  13. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/cli/updater.py +0 -0
  14. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/__init__.py +0 -0
  15. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/auth.py +0 -0
  16. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/batch.py +0 -0
  17. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/credentials.py +0 -0
  18. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/endpoints.py +0 -0
  19. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/findall.py +0 -0
  20. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/memory.py +0 -0
  21. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/monitor.py +0 -0
  22. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/polling.py +0 -0
  23. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/research.py +0 -0
  24. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/result.py +0 -0
  25. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/runner.py +0 -0
  26. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/schema.py +0 -0
  27. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/service.py +0 -0
  28. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/service_types.py +0 -0
  29. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/sql_utils.py +0 -0
  30. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/core/user_agent.py +0 -0
  31. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/__init__.py +0 -0
  32. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/bigquery/__init__.py +0 -0
  33. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/bigquery/cloud_function/main.py +0 -0
  34. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/bigquery/deploy.py +0 -0
  35. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/bigquery/sql/create_functions.sql +0 -0
  36. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/duckdb/__init__.py +0 -0
  37. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/duckdb/batch.py +0 -0
  38. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/duckdb/findall.py +0 -0
  39. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/duckdb/udf.py +0 -0
  40. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/polars/__init__.py +0 -0
  41. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/polars/enrich.py +0 -0
  42. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/snowflake/__init__.py +0 -0
  43. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/snowflake/deploy.py +0 -0
  44. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/snowflake/sql/01_setup.sql +0 -0
  45. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/snowflake/sql/02_create_udf.sql +0 -0
  46. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/snowflake/sql/03_cleanup.sql +0 -0
  47. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/spark/__init__.py +0 -0
  48. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/spark/streaming.py +0 -0
  49. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/spark/udf.py +0 -0
  50. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/integrations/utils.py +0 -0
  51. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/processors/__init__.py +0 -0
  52. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/processors/bigquery.py +0 -0
  53. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/processors/csv.py +0 -0
  54. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/processors/duckdb.py +0 -0
  55. {parallel_web_tools-0.8.1 → parallel_web_tools-0.8.2}/parallel_web_tools/processors/json.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: parallel-web-tools
3
- Version: 0.8.1
3
+ Version: 0.8.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
@@ -43,7 +43,7 @@ from parallel_web_tools.core import (
43
43
  update_monitor,
44
44
  )
45
45
 
46
- __version__ = "0.8.1"
46
+ __version__ = "0.8.2"
47
47
 
48
48
  __all__ = [
49
49
  # Auth
@@ -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:
@@ -86,13 +106,13 @@ def create_skills_group(
86
106
  SkillsInputError,
87
107
  SkillsInstallLocationError,
88
108
  install_skills,
89
- resolve_install_dir,
109
+ resolve_install_dirs,
90
110
  )
91
111
 
92
112
  try:
93
- install_dir = resolve_install_dir(project=project)
113
+ install_dirs = resolve_install_dirs(project=project)
94
114
  result = install_skills(
95
- install_dir=install_dir,
115
+ install_dirs=install_dirs,
96
116
  selected_skills=list(skill_names) or None,
97
117
  )
98
118
  except SkillsInstallLocationError as e:
@@ -109,9 +129,11 @@ def create_skills_group(
109
129
  return
110
130
 
111
131
  console.print("[bold green]Skills installed[/bold green]")
112
- console.print(f"Location: [cyan]{result['install_dir']}[/cyan]")
132
+ print_locations(result)
113
133
  console.print(f"Ref: [cyan]{result['ref']}[/cyan]")
114
134
  console.print(f"Installed ({result['count']}): [cyan]{', '.join(result['installed_skills'])}[/cyan]")
135
+ console.print(f"Files written: [cyan]{result['file_count']}[/cyan]")
136
+ print_skipped(result)
115
137
 
116
138
  @skills.command(name="uninstall")
117
139
  @click.option(
@@ -122,11 +144,11 @@ def create_skills_group(
122
144
  @click.option("--json", "output_json", is_flag=True, help="Output as JSON")
123
145
  def skills_uninstall(project: bool, output_json: bool) -> None:
124
146
  """Uninstall skills previously installed by parallel-cli."""
125
- from parallel_web_tools.core.skills import SkillsInstallLocationError, resolve_install_dir, uninstall_skills
147
+ from parallel_web_tools.core.skills import SkillsInstallLocationError, resolve_install_dirs, uninstall_skills
126
148
 
127
149
  try:
128
- install_dir = resolve_install_dir(project=project)
129
- result = uninstall_skills(install_dir=install_dir)
150
+ install_dirs = resolve_install_dirs(project=project)
151
+ result = uninstall_skills(install_dirs=install_dirs)
130
152
  except SkillsInstallLocationError as e:
131
153
  handle_error(e, output_json=output_json, exit_code=exit_bad_input, prefix="Skills uninstall failed")
132
154
  except Exception as e:
@@ -138,11 +160,11 @@ def create_skills_group(
138
160
 
139
161
  if result["count"] == 0:
140
162
  console.print("[yellow]No managed skills found to uninstall[/yellow]")
141
- console.print(f"Location: [cyan]{result['install_dir']}[/cyan]")
163
+ print_locations(result)
142
164
  return
143
165
 
144
166
  console.print("[bold green]Skills uninstalled[/bold green]")
145
- console.print(f"Location: [cyan]{result['install_dir']}[/cyan]")
167
+ print_locations(result)
146
168
  console.print(f"Removed ({result['count']}): [cyan]{', '.join(result['removed_skills'])}[/cyan]")
147
169
 
148
170
  @skills.command(name="reinstall")
@@ -169,13 +191,13 @@ def create_skills_group(
169
191
  SkillsInputError,
170
192
  SkillsInstallLocationError,
171
193
  reinstall_skills,
172
- resolve_install_dir,
194
+ resolve_install_dirs,
173
195
  )
174
196
 
175
197
  try:
176
- install_dir = resolve_install_dir(project=project)
198
+ install_dirs = resolve_install_dirs(project=project)
177
199
  result = reinstall_skills(
178
- install_dir=install_dir,
200
+ install_dirs=install_dirs,
179
201
  selected_skills=list(skill_names) or None,
180
202
  )
181
203
  except SkillsInstallLocationError as e:
@@ -192,9 +214,11 @@ def create_skills_group(
192
214
  return
193
215
 
194
216
  console.print("[bold green]Skills reinstalled[/bold green]")
195
- console.print(f"Location: [cyan]{result['install_dir']}[/cyan]")
217
+ print_locations(result)
196
218
  console.print(f"Ref: [cyan]{result['ref']}[/cyan]")
197
219
  console.print(f"Removed ({result['removed_count']}): [cyan]{', '.join(result['removed_skills'])}[/cyan]")
198
220
  console.print(f"Installed ({result['installed_count']}): [cyan]{', '.join(result['installed_skills'])}[/cyan]")
221
+ console.print(f"Files written: [cyan]{result['file_count']}[/cyan]")
222
+ print_skipped(result)
199
223
 
200
224
  return skills
@@ -0,0 +1,521 @@
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 a Claude Code configuration directory is present we install there too.
110
+ Agents that read both (Cursor, for example) de-duplicate by skill name.
111
+
112
+ An explicit ``PARALLEL_SKILLS_GLOBAL_DIR`` override targets exactly one directory,
113
+ on the assumption that a caller naming a path wants only that path written.
114
+ """
115
+ canonical = resolve_install_dir(project=project, start=start)
116
+ if not project and os.environ.get(GLOBAL_SKILLS_DIR_ENV):
117
+ return [canonical]
118
+
119
+ claude_config_dir = canonical.parent.parent / ".claude" if project else get_claude_config_dir()
120
+ if not claude_config_dir.is_dir():
121
+ return [canonical]
122
+
123
+ return _dedupe_dirs([canonical, claude_config_dir / "skills"])
124
+
125
+
126
+ def _dedupe_dirs(dirs: Iterable[Path]) -> list[Path]:
127
+ """Drop directories that resolve to the same location, preserving order.
128
+
129
+ A user who symlinked ``~/.claude/skills`` at ``~/.agents/skills`` would otherwise
130
+ have the same tree installed, and its manifest rewritten, twice.
131
+ """
132
+ seen: set[Path] = set()
133
+ unique: list[Path] = []
134
+ for directory in dirs:
135
+ resolved = Path(directory).expanduser().resolve()
136
+ if resolved in seen:
137
+ continue
138
+ seen.add(resolved)
139
+ unique.append(Path(directory))
140
+ return unique
141
+
142
+
143
+ def _normalize_install_dirs(install_dirs: Path | str | Iterable[Path | str]) -> list[Path]:
144
+ """Accept a single directory or a collection of them and return a clean list."""
145
+ if isinstance(install_dirs, (str, Path)):
146
+ candidates: list[Path | str] = [install_dirs]
147
+ else:
148
+ candidates = list(install_dirs)
149
+
150
+ if not candidates:
151
+ raise SkillsInstallLocationError("No skills install directory was provided.")
152
+
153
+ return _dedupe_dirs(Path(candidate) for candidate in candidates)
154
+
155
+
156
+ @contextmanager
157
+ def _skills_client() -> Iterator[httpx.Client]:
158
+ with httpx.Client(timeout=30, follow_redirects=True) as client:
159
+ yield client
160
+
161
+
162
+ def _fetch_json(client: httpx.Client, url: str, description: str) -> dict[str, Any]:
163
+ response = client.get(url)
164
+ if response.status_code >= 400:
165
+ raise SkillsDownloadError(f"Failed to download {description} from {url}: HTTP {response.status_code}")
166
+
167
+ try:
168
+ data = response.json()
169
+ except ValueError as e:
170
+ raise SkillsDownloadError(f"Failed to parse {description} from {url} as JSON") from e
171
+
172
+ if not isinstance(data, dict):
173
+ raise SkillsDownloadError(f"Expected {description} at {url} to be a JSON object")
174
+ return data
175
+
176
+
177
+ def _fetch_skills_index(client: httpx.Client) -> dict[str, Any]:
178
+ return _fetch_json(client, get_skills_index_url(), "skills index")
179
+
180
+
181
+ def _index_channel(index: dict[str, Any]) -> str:
182
+ channel = index.get("channel")
183
+ if isinstance(channel, str) and channel.strip():
184
+ return channel.strip()
185
+ return DEFAULT_SKILLS_REPO_REF
186
+
187
+
188
+ def _skills_from_index(index: dict[str, Any]) -> dict[str, dict[str, str]]:
189
+ raw_skills = index.get("skills")
190
+ if not isinstance(raw_skills, list):
191
+ raise SkillsDownloadError("Skills index is missing a valid 'skills' list")
192
+
193
+ parsed: dict[str, dict[str, str]] = {}
194
+ for raw_skill in raw_skills:
195
+ if not isinstance(raw_skill, dict):
196
+ raise SkillsDownloadError("Skills index contained an invalid skill entry")
197
+
198
+ name = raw_skill.get("name")
199
+ skill_url = raw_skill.get("skill_url")
200
+ if not isinstance(name, str) or not name.strip():
201
+ raise SkillsDownloadError("Skills index contained a skill with an invalid name")
202
+ if not isinstance(skill_url, str) or not skill_url.strip():
203
+ raise SkillsDownloadError(f"Skills index entry '{name}' is missing a valid skill_url")
204
+
205
+ entry = {
206
+ "name": name.strip(),
207
+ "skill_url": skill_url.strip(),
208
+ }
209
+
210
+ manifest_url = raw_skill.get("manifest_url")
211
+ if isinstance(manifest_url, str) and manifest_url.strip():
212
+ entry["manifest_url"] = manifest_url.strip()
213
+
214
+ parsed[name.strip()] = entry
215
+
216
+ return parsed
217
+
218
+
219
+ def _list_skills_from_index(index: dict[str, Any]) -> list[str]:
220
+ return sorted(_skills_from_index(index))
221
+
222
+
223
+ def _download_skill_file(client: httpx.Client, skill_name: str, skill_url: str) -> bytes:
224
+ response = client.get(skill_url)
225
+ if response.status_code >= 400:
226
+ raise SkillsDownloadError(
227
+ f"Failed to download skill '{skill_name}' from {skill_url}: HTTP {response.status_code}"
228
+ )
229
+ return response.content
230
+
231
+
232
+ def _safe_skill_file_path(skill_name: str, raw_path: str) -> str:
233
+ """Validate a manifest-declared relative path stays inside the skill directory.
234
+
235
+ Both path flavours are checked, not just the host's. POSIX rules alone accept
236
+ ``C:/outside/payload``, which pathlib then joins on Windows by discarding the
237
+ skill directory entirely — so a drive letter has to be rejected here even when
238
+ this code is running on Linux or macOS.
239
+ """
240
+ candidate = raw_path.strip().replace("\\", "/")
241
+ if not candidate:
242
+ raise SkillsDownloadError(f"Manifest for skill '{skill_name}' contained an empty file path")
243
+
244
+ posix_path = PurePosixPath(candidate)
245
+ windows_path = PureWindowsPath(candidate)
246
+ unsafe = (
247
+ posix_path.is_absolute()
248
+ or windows_path.is_absolute()
249
+ or bool(windows_path.drive)
250
+ or bool(windows_path.root)
251
+ or any(part in ("..", "") for part in posix_path.parts)
252
+ )
253
+ if unsafe:
254
+ raise SkillsDownloadError(f"Manifest for skill '{skill_name}' contained an unsafe file path: {raw_path}")
255
+
256
+ return str(posix_path)
257
+
258
+
259
+ def _contained_target(skill_name: str, skill_dir: Path, relative_path: str) -> Path:
260
+ """Join relative_path onto skill_dir, refusing anything that lands outside it.
261
+
262
+ A backstop for _safe_skill_file_path: string validation has to anticipate every
263
+ platform's join semantics, whereas this compares the resolved result.
264
+ """
265
+ target = skill_dir / relative_path
266
+ resolved_root = skill_dir.resolve()
267
+ if not target.resolve().is_relative_to(resolved_root):
268
+ raise SkillsDownloadError(f"Manifest for skill '{skill_name}' resolved outside its directory: {relative_path}")
269
+ return target
270
+
271
+
272
+ def _resolve_skill_files(client: httpx.Client, skill_name: str, entry: dict[str, str]) -> list[dict[str, str]]:
273
+ """Resolve every file belonging to a skill.
274
+
275
+ Indexes that advertise a ``manifest_url`` carry the full file list (references,
276
+ scripts, bundled agents). Older or custom indexes without one fall back to the
277
+ single ``SKILL.md`` document.
278
+ """
279
+ skill_only = [{"path": "SKILL.md", "url": entry["skill_url"], "sha256": ""}]
280
+
281
+ manifest_url = entry.get("manifest_url")
282
+ if not manifest_url:
283
+ return skill_only
284
+
285
+ manifest = _fetch_json(client, manifest_url, f"manifest for skill '{skill_name}'")
286
+ raw_files = manifest.get("files")
287
+ if not isinstance(raw_files, list) or not raw_files:
288
+ return skill_only
289
+
290
+ resolved: list[dict[str, str]] = []
291
+ for raw_file in raw_files:
292
+ if not isinstance(raw_file, dict):
293
+ raise SkillsDownloadError(f"Manifest for skill '{skill_name}' contained an invalid file entry")
294
+
295
+ raw_path = raw_file.get("path")
296
+ file_url = raw_file.get("url")
297
+ if not isinstance(raw_path, str) or not isinstance(file_url, str) or not file_url.strip():
298
+ raise SkillsDownloadError(f"Manifest for skill '{skill_name}' contained a file entry missing path or url")
299
+
300
+ checksum = raw_file.get("sha256")
301
+ resolved.append(
302
+ {
303
+ "path": _safe_skill_file_path(skill_name, raw_path),
304
+ "url": file_url.strip(),
305
+ "sha256": checksum.strip().lower() if isinstance(checksum, str) else "",
306
+ }
307
+ )
308
+
309
+ if not any(file_entry["path"] == "SKILL.md" for file_entry in resolved):
310
+ raise SkillsDownloadError(f"Manifest for skill '{skill_name}' does not include a SKILL.md entry")
311
+
312
+ return resolved
313
+
314
+
315
+ def _verify_skill_file_checksum(skill_name: str, file_entry: dict[str, str], content: bytes) -> None:
316
+ expected = file_entry.get("sha256")
317
+ if not expected:
318
+ return
319
+
320
+ actual = hashlib.sha256(content).hexdigest()
321
+ if actual != expected:
322
+ raise SkillsDownloadError(
323
+ f"Checksum mismatch for '{skill_name}/{file_entry['path']}': expected {expected}, got {actual}"
324
+ )
325
+
326
+
327
+ def get_remote_skills_channel() -> str:
328
+ """Return the channel advertised by the remote CDN index."""
329
+ with _skills_client() as client:
330
+ index = _fetch_skills_index(client)
331
+ return _index_channel(index)
332
+
333
+
334
+ def list_remote_skills(ref: str | None = None) -> list[str]:
335
+ """Return available skill names from the CDN index.
336
+
337
+ The ref argument is ignored for CDN-backed installs.
338
+ """
339
+ del ref
340
+ with _skills_client() as client:
341
+ index = _fetch_skills_index(client)
342
+ return _list_skills_from_index(index)
343
+
344
+
345
+ def _manifest_path(install_dir: Path) -> Path:
346
+ return install_dir / MANIFEST_FILE_NAME
347
+
348
+
349
+ def _write_manifest(install_dir: Path, ref: str, installed_skills: list[str]) -> None:
350
+ data = {
351
+ "source": get_skills_index_url(),
352
+ "ref": ref,
353
+ "installed_skills": sorted(installed_skills),
354
+ "installed_at": int(time.time()),
355
+ "managed_by": "parallel-cli",
356
+ }
357
+ install_dir.mkdir(parents=True, exist_ok=True)
358
+ _manifest_path(install_dir).write_text(json.dumps(data, indent=2))
359
+
360
+
361
+ def _read_manifest(install_dir: Path) -> dict:
362
+ path = _manifest_path(install_dir)
363
+ if not path.exists():
364
+ return {}
365
+ try:
366
+ data = json.loads(path.read_text())
367
+ except Exception:
368
+ return {}
369
+ return data if isinstance(data, dict) else {}
370
+
371
+
372
+ def _managed_skills(install_dir: Path) -> list[str]:
373
+ """Return the skill names parallel-cli previously installed into install_dir."""
374
+ managed_raw = _read_manifest(install_dir).get("installed_skills")
375
+ if not isinstance(managed_raw, list):
376
+ return []
377
+ return [name for name in managed_raw if isinstance(name, str)]
378
+
379
+
380
+ def install_skills(
381
+ install_dirs: Path | str | Iterable[Path | str],
382
+ selected_skills: list[str] | None = None,
383
+ ref: str | None = None,
384
+ ) -> dict:
385
+ """Install selected (or all) skills into every directory in install_dirs.
386
+
387
+ Only skills previously managed by parallel-cli are reconciled. Unmanaged skill
388
+ directories are left untouched, including one that merely shares a name with a
389
+ skill being installed — that one is reported in ``skipped_skills`` instead. Every
390
+ file is downloaded once and written to each directory, so a mid-download failure
391
+ leaves no location partially installed.
392
+ """
393
+ del ref
394
+
395
+ targets = _normalize_install_dirs(install_dirs)
396
+
397
+ with _skills_client() as client:
398
+ index = _fetch_skills_index(client)
399
+ resolved_ref = _index_channel(index)
400
+ available_skills = _skills_from_index(index)
401
+ available = sorted(available_skills)
402
+ requested = sorted(set(selected_skills or available))
403
+ missing = sorted(name for name in requested if name not in available_skills)
404
+ if missing:
405
+ raise SkillsInputError(
406
+ f"Unknown skills requested: {', '.join(missing)}. Available skills: {', '.join(available)}"
407
+ )
408
+
409
+ downloads: dict[str, list[tuple[str, bytes]]] = {}
410
+ for skill_name in requested:
411
+ skill_files = _resolve_skill_files(client, skill_name, available_skills[skill_name])
412
+ payload: list[tuple[str, bytes]] = []
413
+ for file_entry in skill_files:
414
+ content = _download_skill_file(client, skill_name, file_entry["url"])
415
+ _verify_skill_file_checksum(skill_name, file_entry, content)
416
+ payload.append((file_entry["path"], content))
417
+ downloads[skill_name] = payload
418
+
419
+ file_count = 0
420
+ installed_anywhere: set[str] = set()
421
+ skipped: list[dict[str, str]] = []
422
+ for install_dir in targets:
423
+ previously_managed = set(_managed_skills(install_dir))
424
+ install_dir.mkdir(parents=True, exist_ok=True)
425
+
426
+ for skill_name in previously_managed:
427
+ if skill_name not in requested:
428
+ stale_dir = install_dir / skill_name
429
+ if stale_dir.exists() and stale_dir.is_dir():
430
+ shutil.rmtree(stale_dir)
431
+
432
+ # Ownership is decided before anything is written. A directory we did not
433
+ # install is someone else's skill: overwriting it would destroy their work,
434
+ # and recording it would make uninstall delete it later, so it is left alone
435
+ # and kept out of the manifest.
436
+ to_install: list[str] = []
437
+ for skill_name in downloads:
438
+ skill_dir = install_dir / skill_name
439
+ if skill_dir.exists() and skill_name not in previously_managed:
440
+ skipped.append({"skill": skill_name, "install_dir": str(install_dir)})
441
+ continue
442
+ to_install.append(skill_name)
443
+
444
+ # Claim ownership up front. An install killed partway through — Ctrl-C, full
445
+ # disk — then leaves directories this CLI still recognizes as its own, so the
446
+ # next install replaces them and uninstall can clean them up. Writing the
447
+ # manifest afterwards instead would strand those partial trees: absent from
448
+ # the manifest, they would be mistaken for a user's work and skipped forever.
449
+ _write_manifest(install_dir, resolved_ref, to_install)
450
+
451
+ for skill_name in to_install:
452
+ skill_dir = install_dir / skill_name
453
+ if skill_dir.exists():
454
+ shutil.rmtree(skill_dir)
455
+ skill_dir.mkdir(parents=True, exist_ok=True)
456
+
457
+ for relative_path, content in downloads[skill_name]:
458
+ target = _contained_target(skill_name, skill_dir, relative_path)
459
+ target.parent.mkdir(parents=True, exist_ok=True)
460
+ target.write_bytes(content)
461
+
462
+ installed_anywhere.add(skill_name)
463
+ file_count += len(downloads[skill_name])
464
+
465
+ return {
466
+ "install_dirs": [str(directory) for directory in targets],
467
+ "ref": resolved_ref,
468
+ "installed_skills": sorted(installed_anywhere),
469
+ "count": len(installed_anywhere),
470
+ "skipped_skills": skipped,
471
+ "file_count": file_count,
472
+ }
473
+
474
+
475
+ def uninstall_skills(install_dirs: Path | str | Iterable[Path | str]) -> dict:
476
+ """Uninstall only manifest-managed skills from every directory in install_dirs."""
477
+ targets = _normalize_install_dirs(install_dirs)
478
+ removed: set[str] = set()
479
+
480
+ for install_dir in targets:
481
+ for skill_name in _managed_skills(install_dir):
482
+ skill_path = install_dir / skill_name
483
+ if skill_path.exists() and skill_path.is_dir():
484
+ shutil.rmtree(skill_path)
485
+ removed.add(skill_name)
486
+
487
+ manifest_path = _manifest_path(install_dir)
488
+ if manifest_path.exists():
489
+ manifest_path.unlink()
490
+
491
+ return {
492
+ "install_dirs": [str(directory) for directory in targets],
493
+ "removed_skills": sorted(removed),
494
+ "count": len(removed),
495
+ }
496
+
497
+
498
+ def reinstall_skills(
499
+ install_dirs: Path | str | Iterable[Path | str],
500
+ selected_skills: list[str] | None = None,
501
+ ref: str | None = None,
502
+ ) -> dict:
503
+ """Reinstall skills by uninstalling managed set then installing fresh.
504
+
505
+ Targets are normalized once up front: a one-shot iterable would otherwise be
506
+ consumed by the uninstall, leaving the install with nothing to write after the
507
+ existing skills had already been removed.
508
+ """
509
+ targets = _normalize_install_dirs(install_dirs)
510
+ uninstall_result = uninstall_skills(targets)
511
+ install_result = install_skills(targets, selected_skills=selected_skills, ref=ref)
512
+ return {
513
+ "install_dirs": install_result["install_dirs"],
514
+ "ref": install_result["ref"],
515
+ "removed_skills": uninstall_result["removed_skills"],
516
+ "installed_skills": install_result["installed_skills"],
517
+ "skipped_skills": install_result["skipped_skills"],
518
+ "removed_count": uninstall_result["count"],
519
+ "installed_count": install_result["count"],
520
+ "file_count": install_result["file_count"],
521
+ }
@@ -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.1
4
+ parallel-web-tools>=0.8.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.1"
7
+ version = "0.8.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"
@@ -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
- }