spaider-cli 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,14 @@
1
+ """SpAIder CLI — install wizard, agent management, Claude Code skill installer.
2
+
3
+ Public surface:
4
+
5
+ spaider init # one-shot first-time wizard
6
+ spaider doctor # self-check + repair
7
+ spaider agent ... # create / list / rotate-key / delete
8
+ spaider mcp install # write ~/.claude/.mcp.json + spaider.md skill
9
+
10
+ Implementation lives in ``spaider_cli.commands``; this module only re-exports
11
+ the entry-point app so ``[project.scripts]`` resolution stays simple.
12
+ """
13
+
14
+ __version__ = "0.1.0-dev"
@@ -0,0 +1,6 @@
1
+ """SpAIder CLI subcommand modules.
2
+
3
+ Each module here exposes either a ``run`` function (for top-level commands
4
+ like ``spaider init``) or a ``typer.Typer()`` named ``app`` (for nested
5
+ command groups like ``spaider agent ...``).
6
+ """
@@ -0,0 +1,178 @@
1
+ """``spaider agent ...`` — REST wrapper around SpAIder's /api/v1/agents.
2
+
3
+ Replaces ``scripts/dev/setup_mcp_dev_agent.sh`` and ``setup_bench_agent.sh``
4
+ with proper subcommands. The bash scripts now shell out to these.
5
+
6
+ Idempotent semantics on ``create``:
7
+
8
+ - If an agent with the requested name already exists, the command rotates its
9
+ key by default (matches the legacy bash-script behaviour). Pass
10
+ ``--no-rotate`` to fail loudly instead.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import typer
15
+ from rich.console import Console
16
+ from rich.table import Table
17
+
18
+ from spaider_cli.lib import api as api_client
19
+
20
+ app = typer.Typer(no_args_is_help=True)
21
+ console = Console()
22
+ err_console = Console(stderr=True)
23
+
24
+
25
+ @app.command("create")
26
+ def create(
27
+ name: str = typer.Argument(..., help="Agent name (e.g. dev-mycl, bench-acmeai)"),
28
+ description: str | None = typer.Option(
29
+ None, "--description", "-d", help="Optional description for the agent."
30
+ ),
31
+ tenant: str = typer.Option(
32
+ "default", "--tenant", help="Tenant ID for multi-tenant deployments."
33
+ ),
34
+ clearance: int = typer.Option(
35
+ 1,
36
+ "--clearance",
37
+ min=1,
38
+ max=5,
39
+ help="Diplomat Protocol clearance level (1=Public/Guest … 5=Admin).",
40
+ ),
41
+ no_rotate: bool = typer.Option(
42
+ False,
43
+ "--no-rotate",
44
+ help="If the agent already exists, fail instead of rotating its key.",
45
+ ),
46
+ ) -> None:
47
+ """Create an agent (idempotent: rotates the key if name already exists)."""
48
+ try:
49
+ existing = api_client.find_agent_by_name(name)
50
+ except api_client.SpaiderApiError as exc:
51
+ err_console.print(f"[red]✗[/] {exc}")
52
+ raise typer.Exit(code=1)
53
+
54
+ if existing is not None:
55
+ if no_rotate:
56
+ err_console.print(
57
+ f"[red]✗[/] agent '{name}' already exists (id={existing.id}); "
58
+ "pass without --no-rotate to rotate its key instead."
59
+ )
60
+ raise typer.Exit(code=1)
61
+ console.print(
62
+ f"[yellow]![/] agent '{name}' already exists (id={existing.id}); "
63
+ "rotating its API key…"
64
+ )
65
+ try:
66
+ new_key = api_client.rotate_key(existing.id)
67
+ except api_client.SpaiderApiError as exc:
68
+ err_console.print(f"[red]✗[/] {exc}")
69
+ raise typer.Exit(code=1)
70
+ _print_credentials(name=name, agent_id=existing.id, api_key=new_key)
71
+ return
72
+
73
+ try:
74
+ agent = api_client.create_agent(
75
+ name,
76
+ description=description,
77
+ tenant_id=tenant,
78
+ clearance_level=clearance,
79
+ )
80
+ except api_client.SpaiderApiError as exc:
81
+ err_console.print(f"[red]✗[/] {exc}")
82
+ raise typer.Exit(code=1)
83
+
84
+ if not agent.api_key:
85
+ err_console.print(
86
+ "[red]✗[/] create returned no api_key — backend may be misconfigured."
87
+ )
88
+ raise typer.Exit(code=1)
89
+ _print_credentials(name=agent.name, agent_id=agent.id, api_key=agent.api_key)
90
+
91
+
92
+ @app.command("list")
93
+ def list_agents() -> None:
94
+ """List every agent registered against this SpAIder instance."""
95
+ try:
96
+ agents = api_client.list_agents()
97
+ except api_client.SpaiderApiError as exc:
98
+ err_console.print(f"[red]✗[/] {exc}")
99
+ raise typer.Exit(code=1)
100
+
101
+ if not agents:
102
+ console.print("[yellow]No agents found.[/] Create one with: spaider agent create <name>")
103
+ return
104
+
105
+ table = Table(title="SpAIder agents", header_style="bold cyan")
106
+ table.add_column("Name", style="bold")
107
+ table.add_column("ID", overflow="fold")
108
+ table.add_column("Tenant", style="dim")
109
+ table.add_column("Clearance", justify="right")
110
+ for a in agents:
111
+ table.add_row(a.name, a.id, a.tenant_id, str(a.clearance_level))
112
+ console.print(table)
113
+
114
+
115
+ @app.command("rotate-key")
116
+ def rotate(
117
+ name: str = typer.Argument(..., help="Agent name whose key should be rotated."),
118
+ ) -> None:
119
+ """Rotate an agent's API key — shows the new value once."""
120
+ try:
121
+ existing = api_client.find_agent_by_name(name)
122
+ if not existing:
123
+ err_console.print(f"[red]✗[/] agent '{name}' not found.")
124
+ raise typer.Exit(code=1)
125
+ new_key = api_client.rotate_key(existing.id)
126
+ except api_client.SpaiderApiError as exc:
127
+ err_console.print(f"[red]✗[/] {exc}")
128
+ raise typer.Exit(code=1)
129
+ _print_credentials(name=name, agent_id=existing.id, api_key=new_key)
130
+
131
+
132
+ @app.command("delete")
133
+ def delete(
134
+ name: str = typer.Argument(..., help="Agent name to delete."),
135
+ yes: bool = typer.Option(
136
+ False, "--yes", "-y", help="Skip the confirmation prompt."
137
+ ),
138
+ ) -> None:
139
+ """Delete an agent and all its graph data (destructive — confirms by default)."""
140
+ try:
141
+ existing = api_client.find_agent_by_name(name)
142
+ except api_client.SpaiderApiError as exc:
143
+ err_console.print(f"[red]✗[/] {exc}")
144
+ raise typer.Exit(code=1)
145
+
146
+ if not existing:
147
+ err_console.print(f"[red]✗[/] agent '{name}' not found.")
148
+ raise typer.Exit(code=1)
149
+
150
+ if not yes:
151
+ confirmed = typer.confirm(
152
+ f"Delete agent '{name}' (id={existing.id}) and all its graph data?",
153
+ default=False,
154
+ )
155
+ if not confirmed:
156
+ console.print("[yellow]Aborted.[/]")
157
+ raise typer.Exit(code=0)
158
+
159
+ try:
160
+ api_client.delete_agent(existing.id)
161
+ except api_client.SpaiderApiError as exc:
162
+ err_console.print(f"[red]✗[/] {exc}")
163
+ raise typer.Exit(code=1)
164
+ console.print(f"[green]✓[/] deleted agent '{name}' (id={existing.id}).")
165
+
166
+
167
+ def _print_credentials(*, name: str, agent_id: str, api_key: str) -> None:
168
+ """Pretty-print the agent + key block so the user can copy it once."""
169
+ console.print()
170
+ console.print("[bold green]✓[/] agent ready")
171
+ console.print(f" name : [bold]{name}[/]")
172
+ console.print(f" id : [dim]{agent_id}[/]")
173
+ console.print(f" api key : [bold yellow]{api_key}[/]")
174
+ console.print()
175
+ console.print(
176
+ "[dim]The api key is shown once. Store it safely or rotate later with "
177
+ "[bold]spaider agent rotate-key " + name + "[/].[/]"
178
+ )
@@ -0,0 +1,231 @@
1
+ """``spaider doctor`` — read-only self-check.
2
+
3
+ Inspects everything ``spaider init`` set up, prints a status table, and exits
4
+ non-zero if any red items remain. The actual repair flow (offering one-click
5
+ fixes for each red item) is v0.2 — keeping doctor read-only in v0.1.0 means
6
+ running it is always safe to share with support.
7
+
8
+ Checks (in order, fail-fast for the ones that block later checks):
9
+
10
+ 1. ``docker`` CLI present.
11
+ 2. Docker daemon running.
12
+ 3. ``.env`` file present at the repo root.
13
+ 4. ``LLM_API_KEY`` set and accepted by OpenAI (1-token probe).
14
+ 5. Backend ``/health`` returns healthy.
15
+ 6. Stored embeddings all match ``EMBEDDING_DIMENSIONS`` (no silent vector-index
16
+ degradation from mixing providers/dimensions).
17
+ 7. ``~/.claude/.mcp.json`` has a SpAIder MCP entry.
18
+ 8. ``~/.claude/skills/spaider.md`` exists and references the four MCP tools.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+
26
+ import typer
27
+ from rich.console import Console
28
+ from rich.table import Table
29
+
30
+ from spaider_cli.lib import api as api_client
31
+ from spaider_cli.lib import docker as docker_lib
32
+ from spaider_cli.lib import llm as llm_lib
33
+
34
+ console = Console()
35
+
36
+
37
+ @dataclass
38
+ class CheckResult:
39
+ name: str
40
+ status: str # "ok" | "warn" | "fail"
41
+ detail: str # short hint shown alongside the status
42
+
43
+
44
+ def _ok(name: str, detail: str = "") -> CheckResult:
45
+ return CheckResult(name=name, status="ok", detail=detail)
46
+
47
+
48
+ def _warn(name: str, detail: str) -> CheckResult:
49
+ return CheckResult(name=name, status="warn", detail=detail)
50
+
51
+
52
+ def _fail(name: str, detail: str) -> CheckResult:
53
+ return CheckResult(name=name, status="fail", detail=detail)
54
+
55
+
56
+ # ---------------------------------------------------------------------------
57
+ # Individual checks
58
+ # ---------------------------------------------------------------------------
59
+
60
+
61
+ def check_docker() -> tuple[CheckResult, CheckResult]:
62
+ status = docker_lib.check_docker_available()
63
+ cli = (
64
+ _ok("docker CLI")
65
+ if status.cli_present
66
+ else _fail("docker CLI", "not on PATH. Install Docker Desktop.")
67
+ )
68
+ if not status.cli_present:
69
+ return cli, _fail("docker daemon", "skipped: docker CLI missing.")
70
+ daemon = (
71
+ _ok("docker daemon")
72
+ if status.daemon_running
73
+ else _fail("docker daemon", f"not running. {(status.error or '')[:80]}")
74
+ )
75
+ return cli, daemon
76
+
77
+
78
+ def check_env_file(repo: Path) -> CheckResult:
79
+ env_path = repo / ".env"
80
+ if not env_path.exists():
81
+ return _fail(
82
+ ".env file",
83
+ f"missing at {env_path}. Run `spaider init` or `cp .env.example .env`.",
84
+ )
85
+ return _ok(".env file", str(env_path))
86
+
87
+
88
+ def check_llm_key(repo: Path) -> CheckResult:
89
+ env_path = repo / ".env"
90
+ if not env_path.exists():
91
+ return _warn("LLM_API_KEY", "skipped: .env not present yet.")
92
+ from spaider_cli.lib import env as env_lib
93
+
94
+ parsed = env_lib.parse_env_text(env_path.read_text(encoding="utf-8"))
95
+ key = parsed.get("LLM_API_KEY", "").strip().strip('"').strip("'")
96
+ if not key or key == "sk-your-key-here":
97
+ return _fail(
98
+ "LLM_API_KEY",
99
+ "still set to the .env.example placeholder. Set a real OpenAI key.",
100
+ )
101
+ result = llm_lib.validate_openai_key(key)
102
+ if not result.ok:
103
+ return _fail("LLM_API_KEY", result.detail)
104
+ return _ok("LLM_API_KEY", "OpenAI accepts the key")
105
+
106
+
107
+ def check_backend_health() -> CheckResult:
108
+ if api_client.health():
109
+ return _ok("backend /health", "healthy on :8000")
110
+ return _fail(
111
+ "backend /health",
112
+ "not reachable. Run `make dev` or `docker compose up -d backend-api`.",
113
+ )
114
+
115
+
116
+ def check_embedding_dimensions() -> CheckResult:
117
+ """Flag a graph whose vectors don't match EMBEDDING_DIMENSIONS.
118
+
119
+ A mismatch (e.g. 768-dim Ollama data left behind after switching to a
120
+ 1536-dim OpenAI model) can't live in the vector index and silently degrades
121
+ semantic search — so it's a failure, not a warning.
122
+ """
123
+ report = api_client.embedding_health()
124
+ if report is None:
125
+ return _warn("embedding dimensions", "skipped: backend not reachable.")
126
+ if report.get("error"):
127
+ return _warn("embedding dimensions", f"could not check: {report['error']}")
128
+ expected = report.get("expected_dims")
129
+ present = report.get("present_dims") or []
130
+ if not present:
131
+ return _ok("embedding dimensions", f"no embeddings yet; will use {expected}-dim.")
132
+ if report.get("consistent"):
133
+ return _ok(
134
+ "embedding dimensions",
135
+ f"all {expected}-dim — matches EMBEDDING_DIMENSIONS.",
136
+ )
137
+ return _fail(
138
+ "embedding dimensions",
139
+ f"graph has {present}-dim vectors but EMBEDDING_DIMENSIONS={expected}; "
140
+ f"vector search degrades. Re-seed the agent(s) at {expected}-dim, or "
141
+ f"revert EMBEDDING_DIMENSIONS.",
142
+ )
143
+
144
+
145
+ def check_mcp_config(home: Path | None = None) -> CheckResult:
146
+ home = home or Path.home()
147
+ path = home / ".claude" / ".mcp.json"
148
+ if not path.exists():
149
+ return _warn(
150
+ "~/.claude/.mcp.json",
151
+ "no Claude Code MCP config yet. Run `spaider mcp install`.",
152
+ )
153
+ try:
154
+ data = json.loads(path.read_text(encoding="utf-8"))
155
+ except json.JSONDecodeError as exc:
156
+ return _fail("~/.claude/.mcp.json", f"malformed JSON: {exc}")
157
+ servers = (data.get("mcpServers") or {})
158
+ if "spaider" not in servers:
159
+ return _warn(
160
+ "~/.claude/.mcp.json",
161
+ "exists but has no SpAIder entry. Run `spaider mcp install`.",
162
+ )
163
+ return _ok("~/.claude/.mcp.json", "SpAIder entry present")
164
+
165
+
166
+ def check_skill_file(home: Path | None = None) -> CheckResult:
167
+ home = home or Path.home()
168
+ path = home / ".claude" / "skills" / "spaider.md"
169
+ if not path.exists():
170
+ return _warn(
171
+ "~/.claude/skills/spaider.md",
172
+ "skill not installed. Run `spaider mcp install`.",
173
+ )
174
+ body = path.read_text(encoding="utf-8")
175
+ missing_tools = [t for t in ("spaider.query", "spaider.feedback") if t not in body]
176
+ if missing_tools:
177
+ return _warn(
178
+ "~/.claude/skills/spaider.md",
179
+ f"present but missing references to {', '.join(missing_tools)} — re-install.",
180
+ )
181
+ return _ok("~/.claude/skills/spaider.md", "loaded by Claude Code at session start")
182
+
183
+
184
+ # ---------------------------------------------------------------------------
185
+ # Entry point
186
+ # ---------------------------------------------------------------------------
187
+
188
+
189
+ def run(
190
+ repo: Path = typer.Option(
191
+ Path.cwd(),
192
+ "--repo",
193
+ help="Path to the SpAIder checkout. Defaults to the current directory.",
194
+ ),
195
+ ) -> None:
196
+ """Run every check and print a status table."""
197
+ results: list[CheckResult] = []
198
+
199
+ docker_cli, docker_daemon = check_docker()
200
+ results.append(docker_cli)
201
+ results.append(docker_daemon)
202
+ results.append(check_env_file(repo))
203
+ results.append(check_llm_key(repo))
204
+ results.append(check_backend_health())
205
+ results.append(check_embedding_dimensions())
206
+ results.append(check_mcp_config())
207
+ results.append(check_skill_file())
208
+
209
+ table = Table(title="SpAIder doctor", header_style="bold cyan")
210
+ table.add_column("Check")
211
+ table.add_column("Status", justify="center")
212
+ table.add_column("Detail", overflow="fold")
213
+ icon = {"ok": "[green]✓[/]", "warn": "[yellow]⚠[/]", "fail": "[red]✗[/]"}
214
+ for r in results:
215
+ table.add_row(r.name, icon[r.status], r.detail)
216
+ console.print(table)
217
+
218
+ failures = [r for r in results if r.status == "fail"]
219
+ warnings = [r for r in results if r.status == "warn"]
220
+ if failures:
221
+ console.print(
222
+ f"\n[red]{len(failures)} failure(s)[/] — fix the rows above and re-run "
223
+ "[bold]spaider doctor[/]."
224
+ )
225
+ raise typer.Exit(code=1)
226
+ if warnings:
227
+ console.print(
228
+ f"\n[yellow]{len(warnings)} warning(s)[/] — non-blocking, but worth addressing."
229
+ )
230
+ raise typer.Exit(code=0)
231
+ console.print("\n[bold green]All clear.[/] SpAIder is ready.")