tavily-cli 0.2.0__tar.gz → 0.2.1__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 (36) hide show
  1. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/PKG-INFO +10 -12
  2. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/README.md +9 -11
  3. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/pyproject.toml +1 -1
  4. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/commands/init.py +7 -34
  5. tavily_cli-0.2.1/tavily_cli/init_skills.py +111 -0
  6. tavily_cli-0.2.1/tests/test_init.py +176 -0
  7. tavily_cli-0.2.0/tavily_cli/init_skills.py +0 -390
  8. tavily_cli-0.2.0/tests/test_init.py +0 -292
  9. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/.gitignore +0 -0
  10. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/LICENSE +0 -0
  11. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/install.sh +0 -0
  12. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/__init__.py +0 -0
  13. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/cli.py +0 -0
  14. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/commands/__init__.py +0 -0
  15. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/commands/auth.py +0 -0
  16. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/commands/crawl.py +0 -0
  17. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/commands/defaults.py +0 -0
  18. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/commands/extract.py +0 -0
  19. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/commands/map_cmd.py +0 -0
  20. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/commands/research.py +0 -0
  21. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/commands/search.py +0 -0
  22. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/commands/update.py +0 -0
  23. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/common.py +0 -0
  24. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/config.py +0 -0
  25. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/keyless.py +0 -0
  26. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/mcp_client.py +0 -0
  27. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/oauth.py +0 -0
  28. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/output.py +0 -0
  29. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/repl.py +0 -0
  30. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tavily_cli/theme.py +0 -0
  31. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tests/test_cli.py +0 -0
  32. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tests/test_defaults.py +0 -0
  33. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tests/test_install_sh.py +0 -0
  34. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tests/test_oauth.py +0 -0
  35. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tests/test_output.py +0 -0
  36. {tavily_cli-0.2.0 → tavily_cli-0.2.1}/tests/test_update.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: tavily-cli
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: CLI and agent tools for the Tavily API — search, extract, crawl, map, and research from the command line.
5
5
  Project-URL: Homepage, https://tavily.com
6
6
  Project-URL: Documentation, https://docs.tavily.com
@@ -121,13 +121,12 @@ tvly search "latest AI trends"
121
121
  `tvly init` guides you through:
122
122
 
123
123
  1. **Authentication:** reuse an existing credential or sign in through browser OAuth.
124
- 2. **Agent setup:** detect Claude Code, Codex, and Cursor and install Tavily's eight core agent skills.
125
- 3. **Verification:** check the CLI and installed skills, then run a live search.
124
+ 2. **Agent setup:** detect Claude Code, Codex, and Cursor and install the Tavily agent skills.
125
+ 3. **Verification:** check the CLI, then run a live search.
126
126
 
127
- When Node.js is available, skills are installed with the
128
- [skills.sh CLI](https://skills.sh) (`npx skills add tavily-ai/skills`). Without
129
- Node.js, `tvly init` installs the skills pinned to your CLI release instead.
130
- Restart your agent after new skills are installed.
127
+ Skills are installed with the [skills.sh CLI](https://skills.sh)
128
+ (`npx skills add tavily-ai/skills`), so skill setup requires Node.js. Without
129
+ Node.js, use `--skip-skills`. Restart your agent after new skills are installed.
131
130
 
132
131
  ```bash
133
132
  # Set up one or more supported agents
@@ -149,10 +148,9 @@ tvly init --skip-skills
149
148
 
150
149
  Skills are installed in `~/.agents/skills`, which Codex and Cursor load
151
150
  directly; Claude Code gets links in `~/.claude/skills`. If no supported agent
152
- is detected, setup still installs the shared skills.
153
- Rerunning `tvly init` updates existing skills to the latest published version
154
- (or, without Node.js, to the version pinned by your CLI release). You can also
155
- run `npx skills update` at any time.
151
+ is detected, setup skips the skills.
152
+ Rerunning `tvly init` updates existing skills to the latest published version.
153
+ You can also run `npx skills update` at any time.
156
154
 
157
155
  ### Try search and extract without signing in
158
156
 
@@ -426,7 +424,7 @@ tvly --status --json # structured status
426
424
  ### `tvly init`
427
425
 
428
426
  Run first-time setup, install or update the Tavily skills (through
429
- `npx skills` when Node.js is available), and verify the CLI with a live search.
427
+ `npx skills`, which requires Node.js), and verify the CLI with a live search.
430
428
 
431
429
  | Option | Description |
432
430
  |--------|-------------|
@@ -84,13 +84,12 @@ tvly search "latest AI trends"
84
84
  `tvly init` guides you through:
85
85
 
86
86
  1. **Authentication:** reuse an existing credential or sign in through browser OAuth.
87
- 2. **Agent setup:** detect Claude Code, Codex, and Cursor and install Tavily's eight core agent skills.
88
- 3. **Verification:** check the CLI and installed skills, then run a live search.
87
+ 2. **Agent setup:** detect Claude Code, Codex, and Cursor and install the Tavily agent skills.
88
+ 3. **Verification:** check the CLI, then run a live search.
89
89
 
90
- When Node.js is available, skills are installed with the
91
- [skills.sh CLI](https://skills.sh) (`npx skills add tavily-ai/skills`). Without
92
- Node.js, `tvly init` installs the skills pinned to your CLI release instead.
93
- Restart your agent after new skills are installed.
90
+ Skills are installed with the [skills.sh CLI](https://skills.sh)
91
+ (`npx skills add tavily-ai/skills`), so skill setup requires Node.js. Without
92
+ Node.js, use `--skip-skills`. Restart your agent after new skills are installed.
94
93
 
95
94
  ```bash
96
95
  # Set up one or more supported agents
@@ -112,10 +111,9 @@ tvly init --skip-skills
112
111
 
113
112
  Skills are installed in `~/.agents/skills`, which Codex and Cursor load
114
113
  directly; Claude Code gets links in `~/.claude/skills`. If no supported agent
115
- is detected, setup still installs the shared skills.
116
- Rerunning `tvly init` updates existing skills to the latest published version
117
- (or, without Node.js, to the version pinned by your CLI release). You can also
118
- run `npx skills update` at any time.
114
+ is detected, setup skips the skills.
115
+ Rerunning `tvly init` updates existing skills to the latest published version.
116
+ You can also run `npx skills update` at any time.
119
117
 
120
118
  ### Try search and extract without signing in
121
119
 
@@ -389,7 +387,7 @@ tvly --status --json # structured status
389
387
  ### `tvly init`
390
388
 
391
389
  Run first-time setup, install or update the Tavily skills (through
392
- `npx skills` when Node.js is available), and verify the CLI with a live search.
390
+ `npx skills`, which requires Node.js), and verify the CLI with a live search.
393
391
 
394
392
  | Option | Description |
395
393
  |--------|-------------|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "tavily-cli"
7
- version = "0.2.0"
7
+ version = "0.2.1"
8
8
  description = "CLI and agent tools for the Tavily API — search, extract, crawl, map, and research from the command line."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -12,14 +12,7 @@ import click
12
12
 
13
13
  from tavily_cli import __version__
14
14
  from tavily_cli.common import json_option
15
- from tavily_cli.init_skills import (
16
- SKILLS_REPO,
17
- SKILLS_SOURCE,
18
- agent_specs,
19
- detect_agents,
20
- install_agent_skills,
21
- verify_skills,
22
- )
15
+ from tavily_cli.init_skills import SKILLS_REPO, agent_specs, detect_agents, install_agent_skills
23
16
 
24
17
  _AGENT_CHOICES = tuple(agent_specs())
25
18
 
@@ -61,7 +54,7 @@ def init_command(
61
54
 
62
55
  selected_agents = _select_agents(agents, all_agents, assume_yes, skip_skills, json_output)
63
56
  result = _empty_result(selected_agents)
64
- result["skills"]["skipped"] = skip_skills
57
+ result["skills"]["skipped"] = skip_skills or not selected_agents
65
58
 
66
59
  try:
67
60
  auth = _ensure_auth(api_key=api_key, skip_auth=skip_auth, browser=browser, json_output=json_output)
@@ -72,22 +65,10 @@ def init_command(
72
65
  result["mode"] = "authenticated" if auth["authenticated"] else "keyless"
73
66
  result["verification"]["auth"] = auth["authenticated"]
74
67
 
75
- if not skip_skills:
68
+ if not result["skills"]["skipped"]:
76
69
  try:
77
70
  skills_result = install_agent_skills(selected_agents)
78
- result["skills"].update({
79
- "installer": skills_result.installer,
80
- "source": SKILLS_REPO if skills_result.installer == "npx" else SKILLS_SOURCE,
81
- "installed": skills_result.installed,
82
- "updated": skills_result.updated,
83
- "unchanged": skills_result.unchanged,
84
- "total": skills_result.total,
85
- "linked": skills_result.linked,
86
- "restart_required": skills_result.restart_required,
87
- })
88
- result["verification"]["skills"] = verify_skills(selected_agents)
89
- if not result["verification"]["skills"]:
90
- raise RuntimeError("Installed Tavily skills could not be verified.")
71
+ result["skills"]["restart_required"] = skills_result.restart_required
91
72
  except Exception as exc:
92
73
  _fail(result, "skills", str(exc), 1, json_output)
93
74
  return
@@ -195,21 +176,14 @@ def _empty_result(agents: tuple[str, ...]) -> dict[str, Any]:
195
176
  "mode": "unknown",
196
177
  "auth": {"authenticated": False, "method": "none"},
197
178
  "skills": {
198
- "installer": None,
199
- "source": SKILLS_SOURCE,
179
+ "source": SKILLS_REPO,
200
180
  "agents": list(agents),
201
- "installed": 0,
202
- "updated": 0,
203
- "unchanged": 0,
204
- "total": 0,
205
- "linked": 0,
206
181
  "restart_required": False,
207
182
  "skipped": False,
208
183
  },
209
184
  "verification": {
210
185
  "cli": False,
211
186
  "auth": False,
212
- "skills": None,
213
187
  "live_search": False,
214
188
  },
215
189
  }
@@ -251,11 +225,10 @@ def _print_result(result: dict[str, Any], *, json_output: bool) -> None:
251
225
  if skills["skipped"]:
252
226
  console.print(" [dim]• Skills skipped[/dim]")
253
227
  else:
254
- agents = ", ".join(skills["agents"]) or "shared agent directory"
255
- console.print(f" [#9BC0AE]✓[/#9BC0AE] {skills['total']} Tavily skills ready for {agents}")
228
+ console.print(f" [#9BC0AE]✓[/#9BC0AE] Tavily skills ready for {', '.join(skills['agents'])}")
256
229
  console.print(" [#9BC0AE]✓[/#9BC0AE] Live search verified")
257
230
 
258
- if skills["restart_required"] and skills["agents"]:
231
+ if skills["restart_required"]:
259
232
  console.print()
260
233
  console.print(f" [dim]Restart {', '.join(skills['agents'])} to load newly installed skills.[/dim]")
261
234
 
@@ -0,0 +1,111 @@
1
+ """Install Tavily's maintained agent skills with the skills.sh CLI (``npx skills``).
2
+
3
+ Installs track the latest published skills and are counted on skills.sh.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import os
10
+ import shutil
11
+ import subprocess
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+
15
+ SKILLS_REPO = "tavily-ai/skills"
16
+ # Exact version: npx runs whatever this resolves to with the user's permissions.
17
+ NPX_SKILLS_PACKAGE = "skills@1.7.4"
18
+
19
+ _NPX_TIMEOUT_SECONDS = 300
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class AgentSpec:
24
+ marker: Path
25
+ skills_dir: Path
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class SkillsInstallResult:
30
+ agents: tuple[str, ...]
31
+ restart_required: bool
32
+
33
+
34
+ def agent_specs(home: Path | None = None) -> dict[str, AgentSpec]:
35
+ """Return supported agent locations rooted at the current user's home."""
36
+ root = home or Path.home()
37
+ if home is None:
38
+ claude_root = Path(os.environ.get("CLAUDE_CONFIG_DIR", root / ".claude")).expanduser()
39
+ codex_root = Path(os.environ.get("CODEX_HOME", root / ".codex")).expanduser()
40
+ else:
41
+ claude_root = root / ".claude"
42
+ codex_root = root / ".codex"
43
+ return {
44
+ "claude-code": AgentSpec(claude_root, claude_root / "skills"),
45
+ "codex": AgentSpec(codex_root, codex_root / "skills"),
46
+ "cursor": AgentSpec(root / ".cursor", root / ".cursor" / "skills"),
47
+ }
48
+
49
+
50
+ def detect_agents(home: Path | None = None) -> tuple[str, ...]:
51
+ """Detect supported agents from their existing configuration directories."""
52
+ return tuple(name for name, spec in agent_specs(home).items() if spec.marker.is_dir())
53
+
54
+
55
+ def install_agent_skills(agents: tuple[str, ...]) -> SkillsInstallResult:
56
+ """Install every skill in the Tavily skills repo for the selected agents."""
57
+ npx = shutil.which("npx")
58
+ if not npx:
59
+ raise RuntimeError("Installing Tavily skills requires Node.js (npx). Install Node.js, or rerun with --skip-skills.")
60
+
61
+ # npx writes to the shared directory, or straight into an agent's own
62
+ # directory when that agent is the only target.
63
+ specs = agent_specs()
64
+ skill_dirs = (Path.home() / ".agents" / "skills", *(specs[name].skills_dir for name in agents))
65
+ before = _snapshot_skills(skill_dirs)
66
+
67
+ # Keep every argument free of quotes and spaces: on Windows npx is a .cmd
68
+ # shim, so the command line is re-parsed by cmd.exe.
69
+ command = [
70
+ npx, "--yes", NPX_SKILLS_PACKAGE, "add", SKILLS_REPO,
71
+ "--skill", "*", "--global", "--agent", *agents, "--yes",
72
+ ]
73
+ try:
74
+ completed = subprocess.run(
75
+ command,
76
+ stdin=subprocess.DEVNULL,
77
+ capture_output=True,
78
+ text=True,
79
+ timeout=_NPX_TIMEOUT_SECONDS,
80
+ check=False,
81
+ )
82
+ except subprocess.TimeoutExpired as exc:
83
+ raise RuntimeError("npx skills timed out while installing Tavily skills.") from exc
84
+ if completed.returncode != 0:
85
+ detail = (completed.stderr or completed.stdout).strip().splitlines()
86
+ raise RuntimeError(f"npx skills failed: {detail[-1] if detail else f'exit code {completed.returncode}'}")
87
+
88
+ return SkillsInstallResult(agents=agents, restart_required=_snapshot_skills(skill_dirs) != before)
89
+
90
+
91
+ def _snapshot_skills(skill_dirs: tuple[Path, ...]) -> dict[Path, str]:
92
+ # Key by path so a new agent link to an existing shared skill counts as a change.
93
+ return {
94
+ path: _directory_digest(path)
95
+ for skill_dir in skill_dirs
96
+ if skill_dir.is_dir()
97
+ for path in skill_dir.iterdir()
98
+ if path.is_dir()
99
+ }
100
+
101
+
102
+ def _directory_digest(path: Path) -> str:
103
+ digest = hashlib.sha256()
104
+ for file_path in sorted(item for item in path.rglob("*") if item.is_file()):
105
+ relative = file_path.relative_to(path).as_posix().encode("utf-8")
106
+ content = file_path.read_bytes()
107
+ digest.update(len(relative).to_bytes(4, "big"))
108
+ digest.update(relative)
109
+ digest.update(len(content).to_bytes(8, "big"))
110
+ digest.update(content)
111
+ return digest.hexdigest()
@@ -0,0 +1,176 @@
1
+ """Tests for one-shot CLI and agent skill setup."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import subprocess
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+ from click.testing import CliRunner
11
+
12
+ from tavily_cli import init_skills as init_skills_module
13
+ from tavily_cli.cli import cli
14
+ from tavily_cli.commands import init as init_module
15
+ from tavily_cli.init_skills import SkillsInstallResult, detect_agents, install_agent_skills
16
+
17
+ SKILLS = ("tavily-search", "tavily-research")
18
+
19
+
20
+ def test_detect_agents_only_returns_existing_markers(tmp_path: Path) -> None:
21
+ (tmp_path / ".codex").mkdir()
22
+ (tmp_path / ".config" / "opencode").mkdir(parents=True)
23
+
24
+ assert detect_agents(tmp_path) == ("codex",)
25
+
26
+
27
+ def test_detect_agents_honors_custom_agent_directories(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
28
+ default_home = tmp_path / "home"
29
+ codex_home = tmp_path / "custom-codex"
30
+ claude_home = tmp_path / "custom-claude"
31
+ for path in (default_home, codex_home, claude_home):
32
+ path.mkdir()
33
+ monkeypatch.setattr(Path, "home", lambda: default_home)
34
+ monkeypatch.setenv("CODEX_HOME", str(codex_home))
35
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))
36
+
37
+ assert detect_agents() == ("claude-code", "codex")
38
+
39
+
40
+ def _fake_npx_install(home: Path, calls: list[list[str]], *, returncode: int = 0, content: str = ""):
41
+ """Mimic the skills.sh CLI writing skills to the shared directory."""
42
+
43
+ def run(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
44
+ calls.append(command)
45
+ if returncode == 0:
46
+ for skill_name in SKILLS:
47
+ skill_dir = home / ".agents" / "skills" / skill_name
48
+ skill_dir.mkdir(parents=True, exist_ok=True)
49
+ (skill_dir / "SKILL.md").write_text(f"---\nname: {skill_name}\n---\n{content}")
50
+ return subprocess.CompletedProcess(command, returncode, "", "Error: repo not found\n")
51
+
52
+ return run
53
+
54
+
55
+ def test_agent_skills_install_runs_npx(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
56
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
57
+ monkeypatch.setattr(init_skills_module.shutil, "which", lambda name: "/usr/bin/npx")
58
+ calls: list[list[str]] = []
59
+ monkeypatch.setattr(init_skills_module.subprocess, "run", _fake_npx_install(tmp_path, calls))
60
+
61
+ agents = ("claude-code", "codex", "cursor")
62
+ first = install_agent_skills(agents)
63
+
64
+ command = calls[0]
65
+ assert command[:5] == ["/usr/bin/npx", "--yes", "skills@1.7.4", "add", "tavily-ai/skills"]
66
+ assert command[command.index("--agent") + 1 : command.index("--agent") + 4] == list(agents)
67
+ assert "--global" in command and command.count("--yes") == 2
68
+ assert all(" " not in arg and '"' not in arg for arg in command)
69
+ assert first.restart_required
70
+
71
+ second = install_agent_skills(agents)
72
+
73
+ assert not second.restart_required
74
+
75
+ monkeypatch.setattr(init_skills_module.subprocess, "run", _fake_npx_install(tmp_path, calls, content="new"))
76
+ third = install_agent_skills(agents)
77
+
78
+ assert third.restart_required
79
+
80
+
81
+ def test_agent_skills_install_counts_new_agent_links(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
82
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
83
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
84
+ monkeypatch.setattr(init_skills_module.shutil, "which", lambda name: "/usr/bin/npx")
85
+ calls: list[list[str]] = []
86
+ monkeypatch.setattr(init_skills_module.subprocess, "run", _fake_npx_install(tmp_path, calls))
87
+ install_agent_skills(("codex",))
88
+
89
+ def link_skills(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
90
+ for skill_name in SKILLS:
91
+ link = tmp_path / ".claude" / "skills" / skill_name
92
+ link.parent.mkdir(parents=True, exist_ok=True)
93
+ link.symlink_to(tmp_path / ".agents" / "skills" / skill_name, target_is_directory=True)
94
+ return subprocess.CompletedProcess(command, 0, "", "")
95
+
96
+ monkeypatch.setattr(init_skills_module.subprocess, "run", link_skills)
97
+
98
+ assert install_agent_skills(("claude-code", "codex")).restart_required
99
+
100
+
101
+ def test_agent_skills_install_requires_npx(monkeypatch: pytest.MonkeyPatch) -> None:
102
+ monkeypatch.setattr(init_skills_module.shutil, "which", lambda name: None)
103
+
104
+ with pytest.raises(RuntimeError, match="requires Node.js"):
105
+ install_agent_skills(("codex",))
106
+
107
+
108
+ def test_agent_skills_install_reports_npx_failure(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
109
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
110
+ monkeypatch.setattr(init_skills_module.shutil, "which", lambda name: "/usr/bin/npx")
111
+ calls: list[list[str]] = []
112
+ monkeypatch.setattr(init_skills_module.subprocess, "run", _fake_npx_install(tmp_path, calls, returncode=1))
113
+
114
+ with pytest.raises(RuntimeError, match="npx skills failed: Error: repo not found"):
115
+ install_agent_skills(("codex",))
116
+
117
+
118
+ def test_init_skips_skills_without_detected_agents(monkeypatch: pytest.MonkeyPatch) -> None:
119
+ monkeypatch.setattr(init_module, "detect_agents", lambda: ())
120
+ monkeypatch.setattr(init_module, "install_agent_skills", lambda agents: pytest.fail("skills installed"))
121
+ monkeypatch.setattr(init_module, "_verify_cli", lambda: True)
122
+ monkeypatch.setattr(init_module, "_verify_live_search", lambda: True)
123
+
124
+ result = CliRunner().invoke(cli, ["init", "--json"], env={"TAVILY_API_KEY": "tvly-test"})
125
+
126
+ assert result.exit_code == 0
127
+ assert json.loads(result.stdout)["skills"]["skipped"] is True
128
+
129
+
130
+ def test_init_json_reuses_environment_auth(monkeypatch: pytest.MonkeyPatch) -> None:
131
+ monkeypatch.setattr(init_module, "detect_agents", lambda: ("codex",))
132
+ monkeypatch.setattr(
133
+ init_module,
134
+ "install_agent_skills",
135
+ lambda agents: SkillsInstallResult(agents, True),
136
+ )
137
+ monkeypatch.setattr(init_module, "_verify_cli", lambda: True)
138
+ monkeypatch.setattr(init_module, "_verify_live_search", lambda: True)
139
+
140
+ result = CliRunner().invoke(cli, ["init", "--json"], env={"TAVILY_API_KEY": "tvly-test"})
141
+
142
+ assert result.exit_code == 0
143
+ output = json.loads(result.stdout)
144
+ assert output["ok"] is True
145
+ assert output["auth"] == {"authenticated": True, "method": "env"}
146
+ assert output["skills"]["agents"] == ["codex"]
147
+ assert output["skills"]["restart_required"] is True
148
+ assert output["skills"]["source"] == "tavily-ai/skills"
149
+ assert output["verification"]["live_search"] is True
150
+
151
+
152
+ def test_init_noninteractive_auth_failure_is_json(monkeypatch: pytest.MonkeyPatch) -> None:
153
+ from tavily_cli import config
154
+
155
+ monkeypatch.setattr(config, "get_api_key", lambda: None)
156
+ result = CliRunner().invoke(cli, ["init", "--skip-skills", "--json"])
157
+
158
+ assert result.exit_code == 3
159
+ output = json.loads(result.stdout)
160
+ assert output["ok"] is False
161
+ assert output["error"]["stage"] == "auth"
162
+ assert output["skills"]["skipped"] is True
163
+
164
+
165
+ def test_init_live_search_failure_exits_four(monkeypatch: pytest.MonkeyPatch) -> None:
166
+ from tavily_cli import config
167
+
168
+ monkeypatch.setattr(config, "get_api_key", lambda: None)
169
+ monkeypatch.setattr(init_module, "_verify_cli", lambda: True)
170
+ monkeypatch.setattr(init_module, "_verify_live_search", lambda: False)
171
+
172
+ result = CliRunner().invoke(cli, ["init", "--skip-auth", "--skip-skills", "--json"])
173
+
174
+ assert result.exit_code == 4
175
+ output = json.loads(result.stdout)
176
+ assert output["error"]["stage"] == "live_search"
@@ -1,390 +0,0 @@
1
- """Install Tavily's maintained agent skills.
2
-
3
- The skills.sh CLI (``npx skills``) is preferred when Node.js is available, so
4
- installs track the latest skills and are counted on skills.sh. The pinned,
5
- checksum-verified archive is the fallback for machines without Node.js.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import hashlib
11
- import io
12
- import os
13
- import shutil
14
- import subprocess
15
- import tarfile
16
- import tempfile
17
- from dataclasses import dataclass
18
- from pathlib import Path, PurePosixPath
19
- from uuid import uuid4
20
-
21
- import httpx
22
-
23
- SKILLS_REPO = "tavily-ai/skills"
24
- SKILLS_COMMIT = "778122e5f9c680f541eeceda5a5b36405eb7980c"
25
- SKILLS_ARCHIVE_SHA256 = "c6d426ef1bb364d3538967d9fe24be4a248ff3ce9b984439f948b6dcf27383f0"
26
- SKILLS_SOURCE = f"{SKILLS_REPO}@{SKILLS_COMMIT}"
27
- SKILLS_ARCHIVE_URL = f"https://codeload.github.com/{SKILLS_REPO}/tar.gz/{SKILLS_COMMIT}"
28
- # Exact version: npx runs whatever this resolves to with the user's permissions.
29
- NPX_SKILLS_PACKAGE = "skills@1.7.4"
30
- CORE_SKILLS = (
31
- "tavily-best-practices",
32
- "tavily-cli",
33
- "tavily-crawl",
34
- "tavily-dynamic-search",
35
- "tavily-extract",
36
- "tavily-map",
37
- "tavily-research",
38
- "tavily-search",
39
- )
40
-
41
- _MAX_ARCHIVE_BYTES = 25 * 1024 * 1024
42
- _MAX_FILE_BYTES = 5 * 1024 * 1024
43
- _NPX_TIMEOUT_SECONDS = 300
44
-
45
-
46
- @dataclass(frozen=True)
47
- class AgentSpec:
48
- marker: Path
49
- skills_dir: Path
50
- # Agents that load ``~/.agents/skills`` directly need no per-agent link.
51
- reads_shared_dir: bool = False
52
-
53
-
54
- @dataclass(frozen=True)
55
- class SkillsInstallResult:
56
- agents: tuple[str, ...]
57
- installed: int
58
- updated: int
59
- unchanged: int
60
- linked: int
61
- restart_required: bool
62
- installer: str = "archive"
63
-
64
- @property
65
- def total(self) -> int:
66
- return self.installed + self.updated + self.unchanged
67
-
68
-
69
- def agent_specs(home: Path | None = None) -> dict[str, AgentSpec]:
70
- """Return supported agent locations rooted at the current user's home."""
71
- root = home or Path.home()
72
- if home is None:
73
- claude_root = Path(os.environ.get("CLAUDE_CONFIG_DIR", root / ".claude")).expanduser()
74
- codex_root = Path(os.environ.get("CODEX_HOME", root / ".codex")).expanduser()
75
- else:
76
- claude_root = root / ".claude"
77
- codex_root = root / ".codex"
78
- return {
79
- "claude-code": AgentSpec(claude_root, claude_root / "skills"),
80
- "codex": AgentSpec(codex_root, codex_root / "skills", reads_shared_dir=True),
81
- "cursor": AgentSpec(root / ".cursor", root / ".cursor" / "skills", reads_shared_dir=True),
82
- }
83
-
84
-
85
- def _linked_skill_dirs(agents: tuple[str, ...], home: Path | None = None) -> tuple[Path, ...]:
86
- """Skill directories that need a link because the agent does not read ``~/.agents/skills``."""
87
- specs = agent_specs(home)
88
- return tuple(specs[name].skills_dir for name in agents if not specs[name].reads_shared_dir)
89
-
90
-
91
- def detect_agents(home: Path | None = None) -> tuple[str, ...]:
92
- """Detect supported agents from their existing configuration directories."""
93
- return tuple(name for name, spec in agent_specs(home).items() if spec.marker.is_dir())
94
-
95
-
96
- def download_skills_archive(*, client: httpx.Client | None = None) -> bytes:
97
- """Download the canonical skills archive with a conservative size limit."""
98
- http = client or httpx.Client(timeout=30.0, follow_redirects=True)
99
- close = client is None
100
- try:
101
- chunks: list[bytes] = []
102
- size = 0
103
- with http.stream("GET", SKILLS_ARCHIVE_URL) as response:
104
- response.raise_for_status()
105
- for chunk in response.iter_bytes():
106
- size += len(chunk)
107
- if size > _MAX_ARCHIVE_BYTES:
108
- raise ValueError("Tavily skills archive exceeds the 25 MB safety limit.")
109
- chunks.append(chunk)
110
- archive = b"".join(chunks)
111
- if hashlib.sha256(archive).hexdigest() != SKILLS_ARCHIVE_SHA256:
112
- raise ValueError("Downloaded Tavily skills archive failed integrity verification.")
113
- return archive
114
- finally:
115
- if close:
116
- http.close()
117
-
118
-
119
- def install_agent_skills(agents: tuple[str, ...]) -> SkillsInstallResult:
120
- """Install skills with ``npx skills`` when possible, else from the pinned archive."""
121
- npx = shutil.which("npx")
122
- if npx and agents:
123
- result = _install_with_npx(npx, agents)
124
- if result is not None:
125
- return result
126
- return install_skills(agents)
127
-
128
-
129
- def _install_with_npx(npx: str, agents: tuple[str, ...]) -> SkillsInstallResult | None:
130
- """Run the skills.sh CLI non-interactively; return None so the caller can fall back."""
131
- shared_root = Path.home() / ".agents" / "skills"
132
- link_dirs = _linked_skill_dirs(agents)
133
- before = _snapshot_skills(shared_root)
134
- existing_links = {d / name for d in link_dirs for name in CORE_SKILLS if (d / name).exists()}
135
-
136
- # Keep every argument free of quotes and spaces: on Windows npx is a .cmd
137
- # shim, so the command line is re-parsed by cmd.exe.
138
- command = [
139
- npx, "--yes", NPX_SKILLS_PACKAGE, "add", SKILLS_REPO,
140
- "--skill", "*", "--global", "--agent", *agents, "--yes",
141
- ]
142
- try:
143
- completed = subprocess.run(
144
- command,
145
- stdin=subprocess.DEVNULL,
146
- capture_output=True,
147
- text=True,
148
- timeout=_NPX_TIMEOUT_SECONDS,
149
- check=False,
150
- )
151
- except (OSError, subprocess.TimeoutExpired):
152
- return None
153
- if completed.returncode != 0 or not verify_skills(agents):
154
- return None
155
-
156
- after = _snapshot_skills(shared_root)
157
- installed = sum(1 for name in CORE_SKILLS if before[name] is None)
158
- updated = sum(1 for name in CORE_SKILLS if before[name] is not None and before[name] != after[name])
159
- linked = sum(1 for d in link_dirs for name in CORE_SKILLS if d / name not in existing_links)
160
- return SkillsInstallResult(
161
- agents=agents,
162
- installed=installed,
163
- updated=updated,
164
- unchanged=len(CORE_SKILLS) - installed - updated,
165
- linked=linked,
166
- restart_required=installed > 0 or updated > 0 or linked > 0,
167
- installer="npx",
168
- )
169
-
170
-
171
- def _snapshot_skills(shared_root: Path) -> dict[str, str | None]:
172
- return {
173
- name: _directory_digest(shared_root / name) if (shared_root / name).is_dir() else None
174
- for name in CORE_SKILLS
175
- }
176
-
177
-
178
- def install_skills(
179
- agents: tuple[str, ...],
180
- *,
181
- home: Path | None = None,
182
- archive: bytes | None = None,
183
- ) -> SkillsInstallResult:
184
- """Install the eight core skills from the pinned archive and expose them to selected agents.
185
-
186
- Archive scripts and references are copied as files but are never executed.
187
- Only the exact Tavily skill names in ``CORE_SKILLS`` are managed.
188
- """
189
- root = home or Path.home()
190
- specs = agent_specs(home)
191
- unsupported = sorted(set(agents) - set(specs))
192
- if unsupported:
193
- raise ValueError(f"Unsupported agent(s): {', '.join(unsupported)}")
194
-
195
- shared_root = root / ".agents" / "skills"
196
- shared_root.mkdir(parents=True, exist_ok=True)
197
-
198
- installed = 0
199
- updated = 0
200
- unchanged = 0
201
- linked = 0
202
- archive_data = archive if archive is not None else download_skills_archive()
203
-
204
- with tempfile.TemporaryDirectory(prefix="tavily-skills-") as temp_dir:
205
- extracted_root = Path(temp_dir)
206
- _extract_core_skills(archive_data, extracted_root)
207
- _preflight_install(shared_root, _linked_skill_dirs(agents, home))
208
-
209
- for skill_name in CORE_SKILLS:
210
- source = extracted_root / skill_name
211
- destination = shared_root / skill_name
212
- state = _replace_if_changed(source, destination)
213
- if state == "installed":
214
- installed += 1
215
- elif state == "updated":
216
- updated += 1
217
- else:
218
- unchanged += 1
219
-
220
- for skills_dir in _linked_skill_dirs(agents, home):
221
- skills_dir.mkdir(parents=True, exist_ok=True)
222
- for skill_name in CORE_SKILLS:
223
- if _expose_skill(shared_root / skill_name, skills_dir / skill_name):
224
- linked += 1
225
-
226
- changed = installed > 0 or updated > 0 or linked > 0
227
- return SkillsInstallResult(
228
- agents=agents,
229
- installed=installed,
230
- updated=updated,
231
- unchanged=unchanged,
232
- linked=linked,
233
- restart_required=changed,
234
- )
235
-
236
-
237
- def verify_skills(agents: tuple[str, ...], *, home: Path | None = None) -> bool:
238
- """Verify shared skill files and the links for agents that need them are present."""
239
- root = home or Path.home()
240
- specs = agent_specs(home)
241
- if any(name not in specs for name in agents):
242
- return False
243
- shared_root = root / ".agents" / "skills"
244
- skill_dirs = (shared_root, *_linked_skill_dirs(agents, home))
245
- return all((d / skill_name / "SKILL.md").is_file() for d in skill_dirs for skill_name in CORE_SKILLS)
246
-
247
-
248
- def _extract_core_skills(archive_data: bytes, destination: Path) -> None:
249
- """Extract only approved skill directories from an untrusted tar archive."""
250
- found: set[str] = set()
251
- total_file_bytes = 0
252
- try:
253
- archive = tarfile.open(fileobj=io.BytesIO(archive_data), mode="r:gz")
254
- except tarfile.TarError as exc:
255
- raise ValueError("Downloaded Tavily skills archive is invalid.") from exc
256
-
257
- with archive:
258
- for member in archive.getmembers():
259
- path = PurePosixPath(member.name)
260
- parts = path.parts
261
- if path.is_absolute() or ".." in parts or len(parts) < 4:
262
- continue
263
- if parts[1] != "skills" or parts[2] not in CORE_SKILLS:
264
- continue
265
-
266
- skill_name = parts[2]
267
- relative_parts = parts[3:]
268
- if not relative_parts:
269
- continue
270
- if any(part in ("", ".", "..") or "\\" in part or ":" in part for part in relative_parts):
271
- raise ValueError(f"Tavily skill {skill_name} contains an unsafe archive path.")
272
- target = destination / skill_name / Path(*relative_parts)
273
- if member.isdir():
274
- target.mkdir(parents=True, exist_ok=True)
275
- continue
276
- if not member.isfile():
277
- raise ValueError(f"Tavily skill {skill_name} contains an unsupported archive entry.")
278
- if member.size > _MAX_FILE_BYTES:
279
- raise ValueError(f"Tavily skill {skill_name} contains a file larger than 5 MB.")
280
- total_file_bytes += member.size
281
- if total_file_bytes > _MAX_ARCHIVE_BYTES:
282
- raise ValueError("Extracted Tavily skills exceed the 25 MB safety limit.")
283
-
284
- source = archive.extractfile(member)
285
- if source is None:
286
- raise ValueError(f"Could not read {member.name} from the Tavily skills archive.")
287
- target.parent.mkdir(parents=True, exist_ok=True)
288
- target.write_bytes(source.read())
289
- # Skill payloads are data consumed by agents, not trusted programs.
290
- # Never propagate executable bits supplied by the archive.
291
- target.chmod(0o644)
292
- found.add(skill_name)
293
-
294
- missing = [name for name in CORE_SKILLS if name not in found or not (destination / name / "SKILL.md").is_file()]
295
- if missing:
296
- raise ValueError(f"Tavily skills archive is missing: {', '.join(missing)}")
297
-
298
-
299
- def _directory_digest(path: Path) -> str:
300
- digest = hashlib.sha256()
301
- entries = sorted(path.rglob("*"))
302
- if any(item.is_symlink() for item in entries):
303
- raise ValueError(f"Cannot compare a skill containing links: {path}")
304
- for file_path in (item for item in entries if item.is_file()):
305
- relative = file_path.relative_to(path).as_posix().encode("utf-8")
306
- content = file_path.read_bytes()
307
- digest.update(len(relative).to_bytes(4, "big"))
308
- digest.update(relative)
309
- digest.update((file_path.stat().st_mode & 0o111).to_bytes(2, "big"))
310
- digest.update(len(content).to_bytes(8, "big"))
311
- digest.update(content)
312
- return digest.hexdigest()
313
-
314
-
315
- def _replace_if_changed(source: Path, destination: Path) -> str:
316
- existed = destination.exists() or destination.is_symlink()
317
- if destination.is_dir() and not destination.is_symlink():
318
- if _directory_digest(source) == _directory_digest(destination):
319
- return "unchanged"
320
- elif existed:
321
- raise ValueError(f"Cannot install Tavily skill over non-directory path: {destination}")
322
-
323
- token = uuid4().hex
324
- staging = destination.parent / f".{destination.name}.tavily-new-{token}"
325
- backup = destination.parent / f".{destination.name}.tavily-backup-{token}"
326
-
327
- shutil.copytree(source, staging)
328
- try:
329
- if existed:
330
- destination.replace(backup)
331
- staging.replace(destination)
332
- except Exception:
333
- if not destination.exists() and backup.exists():
334
- backup.replace(destination)
335
- raise
336
- else:
337
- if backup.exists() or backup.is_symlink():
338
- try:
339
- _remove_path(backup)
340
- except OSError:
341
- pass
342
- finally:
343
- if staging.exists() or staging.is_symlink():
344
- _remove_path(staging)
345
- return "updated" if existed else "installed"
346
-
347
-
348
- def _expose_skill(source: Path, destination: Path) -> bool:
349
- if destination.is_symlink():
350
- if destination.resolve(strict=False) == source.resolve():
351
- return False
352
- raise ValueError(f"Cannot replace existing skill link: {destination}")
353
- if destination.exists():
354
- if not destination.is_dir():
355
- raise ValueError(f"Cannot replace non-directory skill path: {destination}")
356
- return _replace_if_changed(source, destination) != "unchanged"
357
-
358
- relative_source = os.path.relpath(source, start=destination.parent)
359
- try:
360
- destination.symlink_to(relative_source, target_is_directory=True)
361
- except OSError:
362
- shutil.copytree(source, destination)
363
- return True
364
-
365
-
366
- def _preflight_install(shared_root: Path, link_dirs: tuple[Path, ...]) -> None:
367
- """Reject path conflicts before changing any installed skill."""
368
- for skill_name in CORE_SKILLS:
369
- destination = shared_root / skill_name
370
- if (destination.exists() or destination.is_symlink()) and (
371
- destination.is_symlink() or not destination.is_dir()
372
- ):
373
- raise ValueError(f"Cannot install Tavily skill over non-directory path: {destination}")
374
-
375
- for skills_dir in link_dirs:
376
- for skill_name in CORE_SKILLS:
377
- source = shared_root / skill_name
378
- destination = skills_dir / skill_name
379
- if destination.is_symlink():
380
- if destination.resolve(strict=False) != source.resolve(strict=False):
381
- raise ValueError(f"Cannot replace existing skill link: {destination}")
382
- elif destination.exists() and not destination.is_dir():
383
- raise ValueError(f"Cannot replace non-directory skill path: {destination}")
384
-
385
-
386
- def _remove_path(path: Path) -> None:
387
- if path.is_symlink() or path.is_file():
388
- path.unlink()
389
- elif path.is_dir():
390
- shutil.rmtree(path)
@@ -1,292 +0,0 @@
1
- """Tests for one-shot CLI and agent skill setup."""
2
-
3
- from __future__ import annotations
4
-
5
- import hashlib
6
- import io
7
- import json
8
- import subprocess
9
- import tarfile
10
- from pathlib import Path
11
-
12
- import httpx
13
- import pytest
14
- from click.testing import CliRunner
15
-
16
- from tavily_cli import init_skills as init_skills_module
17
- from tavily_cli.cli import cli
18
- from tavily_cli.commands import init as init_module
19
- from tavily_cli.init_skills import (
20
- CORE_SKILLS,
21
- SkillsInstallResult,
22
- detect_agents,
23
- download_skills_archive,
24
- install_agent_skills,
25
- install_skills,
26
- verify_skills,
27
- )
28
-
29
-
30
- def _skills_archive(*, changed_skill: str | None = None, symlink: bool = False) -> bytes:
31
- payload = io.BytesIO()
32
- with tarfile.open(fileobj=payload, mode="w:gz") as archive:
33
- for skill_name in CORE_SKILLS:
34
- content = f"---\nname: {skill_name}\n---\n"
35
- if skill_name == changed_skill:
36
- content += "updated\n"
37
- _add_file(archive, f"skills-main/skills/{skill_name}/SKILL.md", content.encode())
38
- _add_file(
39
- archive,
40
- "skills-main/skills/tavily-cli/scripts/check.sh",
41
- b"#!/bin/sh\nexit 99\n",
42
- mode=0o755,
43
- )
44
- if symlink:
45
- member = tarfile.TarInfo("skills-main/skills/tavily-cli/references/unsafe")
46
- member.type = tarfile.SYMTYPE
47
- member.linkname = "/etc/passwd"
48
- archive.addfile(member)
49
- return payload.getvalue()
50
-
51
-
52
- def _add_file(archive: tarfile.TarFile, name: str, content: bytes, *, mode: int = 0o644) -> None:
53
- member = tarfile.TarInfo(name)
54
- member.size = len(content)
55
- member.mode = mode
56
- archive.addfile(member, io.BytesIO(content))
57
-
58
-
59
- def test_download_skills_archive_verifies_checksum(monkeypatch: pytest.MonkeyPatch) -> None:
60
- archive = _skills_archive()
61
- monkeypatch.setattr(
62
- init_skills_module,
63
- "SKILLS_ARCHIVE_SHA256",
64
- hashlib.sha256(archive).hexdigest(),
65
- )
66
- transport = httpx.MockTransport(lambda request: httpx.Response(200, content=archive, request=request))
67
-
68
- with httpx.Client(transport=transport) as client:
69
- assert download_skills_archive(client=client) == archive
70
-
71
-
72
- def test_download_skills_archive_rejects_checksum_mismatch(monkeypatch: pytest.MonkeyPatch) -> None:
73
- monkeypatch.setattr(init_skills_module, "SKILLS_ARCHIVE_SHA256", "0" * 64)
74
- transport = httpx.MockTransport(lambda request: httpx.Response(200, content=b"tampered", request=request))
75
-
76
- with httpx.Client(transport=transport) as client, pytest.raises(ValueError, match="integrity verification"):
77
- download_skills_archive(client=client)
78
-
79
-
80
- def test_detect_agents_only_returns_existing_markers(tmp_path: Path) -> None:
81
- (tmp_path / ".codex").mkdir()
82
- (tmp_path / ".config" / "opencode").mkdir(parents=True)
83
-
84
- assert detect_agents(tmp_path) == ("codex",)
85
-
86
-
87
- def test_skill_install_honors_custom_agent_directories(
88
- tmp_path: Path,
89
- monkeypatch: pytest.MonkeyPatch,
90
- ) -> None:
91
- default_home = tmp_path / "home"
92
- codex_home = tmp_path / "custom-codex"
93
- claude_home = tmp_path / "custom-claude"
94
- default_home.mkdir()
95
- codex_home.mkdir()
96
- claude_home.mkdir()
97
- monkeypatch.setattr(Path, "home", lambda: default_home)
98
- monkeypatch.setenv("CODEX_HOME", str(codex_home))
99
- monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))
100
-
101
- assert detect_agents() == ("claude-code", "codex")
102
-
103
- install_skills(("claude-code", "codex"), archive=_skills_archive())
104
-
105
- assert verify_skills(("claude-code", "codex"))
106
- assert (claude_home / "skills" / "tavily-search" / "SKILL.md").is_file()
107
- assert (default_home / ".agents" / "skills" / "tavily-search" / "SKILL.md").is_file()
108
- assert not (codex_home / "skills").exists()
109
- assert not (default_home / ".claude").exists()
110
- assert not (default_home / ".codex").exists()
111
-
112
-
113
- def test_skill_install_is_complete_and_idempotent(tmp_path: Path) -> None:
114
- archive = _skills_archive()
115
-
116
- first = install_skills(("claude-code", "codex"), home=tmp_path, archive=archive)
117
-
118
- assert first.installed == len(CORE_SKILLS)
119
- assert first.updated == 0
120
- assert first.linked == len(CORE_SKILLS)
121
- assert first.restart_required
122
- assert verify_skills(("claude-code", "codex"), home=tmp_path)
123
- assert not (tmp_path / ".codex" / "skills").exists()
124
- script = tmp_path / ".agents" / "skills" / "tavily-cli" / "scripts" / "check.sh"
125
- assert script.read_text() == "#!/bin/sh\nexit 99\n"
126
- assert script.stat().st_mode & 0o111 == 0
127
-
128
- second = install_skills(("claude-code", "codex"), home=tmp_path, archive=archive)
129
-
130
- assert second.installed == 0
131
- assert second.updated == 0
132
- assert second.unchanged == len(CORE_SKILLS)
133
- assert second.linked == 0
134
- assert not second.restart_required
135
-
136
-
137
- def test_skill_install_without_agent_uses_shared_directory(tmp_path: Path) -> None:
138
- result = install_skills((), home=tmp_path, archive=_skills_archive())
139
-
140
- assert result.agents == ()
141
- assert result.installed == len(CORE_SKILLS)
142
- assert result.linked == 0
143
- assert verify_skills((), home=tmp_path)
144
-
145
-
146
- def test_skill_install_updates_only_changed_core_skill(tmp_path: Path) -> None:
147
- install_skills(("claude-code",), home=tmp_path, archive=_skills_archive())
148
-
149
- updated = install_skills(
150
- ("claude-code",),
151
- home=tmp_path,
152
- archive=_skills_archive(changed_skill="tavily-search"),
153
- )
154
-
155
- assert updated.updated == 1
156
- assert updated.unchanged == len(CORE_SKILLS) - 1
157
- assert "updated" in (tmp_path / ".agents" / "skills" / "tavily-search" / "SKILL.md").read_text()
158
-
159
-
160
- def test_skill_install_rejects_archive_links(tmp_path: Path) -> None:
161
- with pytest.raises(ValueError, match="unsupported archive entry"):
162
- install_skills((), home=tmp_path, archive=_skills_archive(symlink=True))
163
-
164
-
165
- def test_skill_install_checks_conflicts_before_writing(tmp_path: Path) -> None:
166
- conflict = tmp_path / ".agents" / "skills" / CORE_SKILLS[-1]
167
- conflict.parent.mkdir(parents=True)
168
- conflict.write_text("owned by the user")
169
-
170
- with pytest.raises(ValueError, match="non-directory path"):
171
- install_skills((), home=tmp_path, archive=_skills_archive())
172
-
173
- assert not (tmp_path / ".agents" / "skills" / CORE_SKILLS[0]).exists()
174
-
175
-
176
- def _fake_npx_install(home: Path, calls: list[list[str]], *, returncode: int = 0):
177
- """Mimic the skills.sh CLI layout: shared copies plus Claude Code links (Codex and Cursor read the shared dir)."""
178
-
179
- def run(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
180
- calls.append(command)
181
- if returncode == 0:
182
- shared = home / ".agents" / "skills"
183
- for skill_name in CORE_SKILLS:
184
- (shared / skill_name).mkdir(parents=True, exist_ok=True)
185
- (shared / skill_name / "SKILL.md").write_text(f"---\nname: {skill_name}\n---\n")
186
- link = home / ".claude" / "skills" / skill_name
187
- if not link.exists():
188
- link.parent.mkdir(parents=True, exist_ok=True)
189
- link.symlink_to(shared / skill_name, target_is_directory=True)
190
- return subprocess.CompletedProcess(command, returncode, "", "")
191
-
192
- return run
193
-
194
-
195
- def test_agent_skills_install_prefers_npx(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
196
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
197
- monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
198
- monkeypatch.delenv("CODEX_HOME", raising=False)
199
- monkeypatch.setattr(init_skills_module.shutil, "which", lambda name: "/usr/bin/npx")
200
- calls: list[list[str]] = []
201
- monkeypatch.setattr(init_skills_module.subprocess, "run", _fake_npx_install(tmp_path, calls))
202
- monkeypatch.setattr(init_skills_module, "install_skills", lambda agents: pytest.fail("archive fallback used"))
203
-
204
- agents = ("claude-code", "codex", "cursor")
205
- first = install_agent_skills(agents)
206
-
207
- command = calls[0]
208
- assert command[:5] == ["/usr/bin/npx", "--yes", "skills@1.7.4", "add", "tavily-ai/skills"]
209
- assert command[command.index("--agent") + 1 : command.index("--agent") + 4] == list(agents)
210
- assert "--global" in command and command.count("--yes") == 2
211
- assert all(" " not in arg and '"' not in arg for arg in command)
212
- assert first.installer == "npx"
213
- assert first.installed == len(CORE_SKILLS)
214
- assert first.linked == len(CORE_SKILLS)
215
- assert first.restart_required
216
- assert verify_skills(agents)
217
-
218
- second = install_agent_skills(agents)
219
-
220
- assert second.unchanged == len(CORE_SKILLS)
221
- assert second.linked == 0
222
- assert not second.restart_required
223
-
224
-
225
- def test_agent_skills_install_falls_back_without_npx(monkeypatch: pytest.MonkeyPatch) -> None:
226
- fallback = SkillsInstallResult(("codex",), 8, 0, 0, 8, True)
227
- monkeypatch.setattr(init_skills_module.shutil, "which", lambda name: None)
228
- monkeypatch.setattr(init_skills_module, "install_skills", lambda agents: fallback)
229
-
230
- assert install_agent_skills(("codex",)) is fallback
231
-
232
-
233
- def test_agent_skills_install_falls_back_when_npx_fails(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
234
- fallback = SkillsInstallResult(("codex",), 8, 0, 0, 8, True)
235
- monkeypatch.setattr(Path, "home", lambda: tmp_path)
236
- monkeypatch.setattr(init_skills_module.shutil, "which", lambda name: "/usr/bin/npx")
237
- calls: list[list[str]] = []
238
- monkeypatch.setattr(init_skills_module.subprocess, "run", _fake_npx_install(tmp_path, calls, returncode=1))
239
- monkeypatch.setattr(init_skills_module, "install_skills", lambda agents: fallback)
240
-
241
- assert install_agent_skills(("codex",)) is fallback
242
- assert len(calls) == 1
243
-
244
-
245
- def test_init_json_reuses_environment_auth(monkeypatch: pytest.MonkeyPatch) -> None:
246
- monkeypatch.setattr(init_module, "detect_agents", lambda: ("codex",))
247
- monkeypatch.setattr(
248
- init_module,
249
- "install_agent_skills",
250
- lambda agents: SkillsInstallResult(agents, 8, 0, 0, 8, True, installer="npx"),
251
- )
252
- monkeypatch.setattr(init_module, "verify_skills", lambda agents: True)
253
- monkeypatch.setattr(init_module, "_verify_cli", lambda: True)
254
- monkeypatch.setattr(init_module, "_verify_live_search", lambda: True)
255
-
256
- result = CliRunner().invoke(cli, ["init", "--json"], env={"TAVILY_API_KEY": "tvly-test"})
257
-
258
- assert result.exit_code == 0
259
- output = json.loads(result.stdout)
260
- assert output["ok"] is True
261
- assert output["auth"] == {"authenticated": True, "method": "env"}
262
- assert output["skills"]["agents"] == ["codex"]
263
- assert output["skills"]["installer"] == "npx"
264
- assert output["skills"]["source"] == "tavily-ai/skills"
265
- assert output["verification"]["live_search"] is True
266
-
267
-
268
- def test_init_noninteractive_auth_failure_is_json(monkeypatch: pytest.MonkeyPatch) -> None:
269
- from tavily_cli import config
270
-
271
- monkeypatch.setattr(config, "get_api_key", lambda: None)
272
- result = CliRunner().invoke(cli, ["init", "--skip-skills", "--json"])
273
-
274
- assert result.exit_code == 3
275
- output = json.loads(result.stdout)
276
- assert output["ok"] is False
277
- assert output["error"]["stage"] == "auth"
278
- assert output["skills"]["skipped"] is True
279
-
280
-
281
- def test_init_live_search_failure_exits_four(monkeypatch: pytest.MonkeyPatch) -> None:
282
- from tavily_cli import config
283
-
284
- monkeypatch.setattr(config, "get_api_key", lambda: None)
285
- monkeypatch.setattr(init_module, "_verify_cli", lambda: True)
286
- monkeypatch.setattr(init_module, "_verify_live_search", lambda: False)
287
-
288
- result = CliRunner().invoke(cli, ["init", "--skip-auth", "--skip-skills", "--json"])
289
-
290
- assert result.exit_code == 4
291
- output = json.loads(result.stdout)
292
- assert output["error"]["stage"] == "live_search"
File without changes
File without changes
File without changes
File without changes
File without changes