spaider-cli 0.1.2__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 (45) hide show
  1. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/PKG-INFO +1 -1
  2. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/pyproject.toml +2 -2
  3. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/commands/doctor.py +38 -9
  4. spaider_cli-0.2.1/src/spaider_cli/commands/governance.py +133 -0
  5. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/commands/init.py +21 -8
  6. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/commands/mcp.py +30 -0
  7. spaider_cli-0.2.1/src/spaider_cli/commands/memory.py +95 -0
  8. spaider_cli-0.2.1/src/spaider_cli/commands/ops.py +61 -0
  9. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/lib/api.py +35 -8
  10. spaider_cli-0.2.1/src/spaider_cli/lib/client.py +61 -0
  11. spaider_cli-0.2.1/src/spaider_cli/lib/clients.py +97 -0
  12. spaider_cli-0.2.1/src/spaider_cli/lib/config.py +51 -0
  13. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/lib/docker.py +15 -10
  14. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/lib/env.py +1 -1
  15. spaider_cli-0.2.1/src/spaider_cli/lib/stack.py +43 -0
  16. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/main.py +11 -0
  17. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/skills/claude_code.md +14 -1
  18. spaider_cli-0.2.1/src/spaider_cli/stack/.env.example +209 -0
  19. spaider_cli-0.2.1/src/spaider_cli/stack/clickhouse/system-logs.xml +35 -0
  20. spaider_cli-0.2.1/src/spaider_cli/stack/docker-compose.yml +328 -0
  21. spaider_cli-0.2.1/src/spaider_cli/stack/gateway/kong.yml +46 -0
  22. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli.egg-info/PKG-INFO +1 -1
  23. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli.egg-info/SOURCES.txt +13 -0
  24. spaider_cli-0.2.1/tests/test_commands.py +272 -0
  25. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/tests/test_doctor.py +26 -18
  26. spaider_cli-0.2.1/tests/test_doctor_health.py +46 -0
  27. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/tests/test_env.py +4 -4
  28. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/tests/test_init.py +4 -4
  29. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/LICENSE +0 -0
  30. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/README.md +0 -0
  31. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/setup.cfg +0 -0
  32. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/__init__.py +0 -0
  33. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/commands/__init__.py +0 -0
  34. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/commands/agent.py +0 -0
  35. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/lib/__init__.py +0 -0
  36. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/lib/llm.py +0 -0
  37. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/lib/mcp.py +0 -0
  38. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli/skills/__init__.py +0 -0
  39. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli.egg-info/dependency_links.txt +0 -0
  40. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli.egg-info/entry_points.txt +0 -0
  41. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli.egg-info/requires.txt +0 -0
  42. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/src/spaider_cli.egg-info/top_level.txt +0 -0
  43. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/tests/test_agent.py +0 -0
  44. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/tests/test_mcp.py +0 -0
  45. {spaider_cli-0.1.2 → spaider_cli-0.2.1}/tests/test_smoke.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spaider-cli
3
- Version: 0.1.2
3
+ Version: 0.2.1
4
4
  Summary: SpAIder install wizard, agent management, and Claude Code skill installer
5
5
  Author: SpAIder Studio
6
6
  License-Expression: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "spaider-cli"
7
- version = "0.1.2"
7
+ version = "0.2.1"
8
8
  description = "SpAIder install wizard, agent management, and Claude Code skill installer"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -50,7 +50,7 @@ spaider = "spaider_cli.main:app"
50
50
  where = ["src"]
51
51
 
52
52
  [tool.setuptools.package-data]
53
- "spaider_cli" = ["skills/*.md"]
53
+ "spaider_cli" = ["skills/*.md", "stack/docker-compose.yml", "stack/.env.example", "stack/gateway/*", "stack/clickhouse/*"]
54
54
 
55
55
  [tool.ruff]
56
56
  line-length = 120
@@ -15,7 +15,8 @@ Checks (in order, fail-fast for the ones that block later checks):
15
15
  6. Stored embeddings all match ``EMBEDDING_DIMENSIONS`` (no silent vector-index
16
16
  degradation from mixing providers/dimensions).
17
17
  7. ``~/.claude/.mcp.json`` has a SpAIder MCP entry.
18
- 8. ``~/.claude/skills/spaider.md`` exists and references the four MCP tools.
18
+ 8. ``~/.claude/skills/spaider.md`` exists and describes the current MCP tools.
19
+ 9. The saved API key is accepted by the server.
19
20
  """
20
21
  from __future__ import annotations
21
22
 
@@ -23,13 +24,16 @@ import json
23
24
  from dataclasses import dataclass
24
25
  from pathlib import Path
25
26
 
27
+ import httpx
26
28
  import typer
27
29
  from rich.console import Console
28
30
  from rich.table import Table
29
31
 
30
32
  from spaider_cli.lib import api as api_client
33
+ from spaider_cli.lib import config as config_lib
31
34
  from spaider_cli.lib import docker as docker_lib
32
35
  from spaider_cli.lib import llm as llm_lib
36
+ from spaider_cli.lib.client import headers as client_headers
33
37
 
34
38
  console = Console()
35
39
 
@@ -105,12 +109,34 @@ def check_llm_key(repo: Path) -> CheckResult:
105
109
 
106
110
 
107
111
  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
- )
112
+ report = api_client.health_report()
113
+ if report is None:
114
+ return _fail(
115
+ "backend /health",
116
+ "not reachable. Run `make dev` or `docker compose up -d backend-api`.",
117
+ )
118
+ # "disabled" means switched off on purpose (the Lite profile). Only a
119
+ # service that is switched on and does not answer is a problem.
120
+ broken = sorted(name for name, state in report.get("services", {}).items() if state == "unavailable")
121
+ if report.get("healthy") is False:
122
+ return _fail("backend /health", "not healthy: " + (", ".join(broken) or "see /health"))
123
+ if broken:
124
+ return _warn("backend /health", "answers, but not available: " + ", ".join(broken))
125
+ return _ok("backend /health", "healthy on :8000")
126
+
127
+
128
+ def check_login() -> CheckResult:
129
+ """Auth is always on since 0.5, so a working key is part of a working install."""
130
+ if not config_lib.api_key():
131
+ return _warn("API key", "not logged in. Run `spaider login`.")
132
+ try:
133
+ response = httpx.get(f"{config_lib.api_base()}/auth/whoami", headers=client_headers(), timeout=5)
134
+ except httpx.HTTPError as exc:
135
+ return _warn("API key", f"could not check it: {type(exc).__name__}")
136
+ if response.status_code != 200:
137
+ return _fail("API key", "rejected by the server. Run `spaider login` with a current key.")
138
+ who = response.json()
139
+ return _ok("API key", f"{who.get('name') or who.get('id')} ({who.get('org_role')})")
114
140
 
115
141
 
116
142
  def check_embedding_dimensions() -> CheckResult:
@@ -172,11 +198,13 @@ def check_skill_file(home: Path | None = None) -> CheckResult:
172
198
  "skill not installed. Run `spaider mcp install`.",
173
199
  )
174
200
  body = path.read_text(encoding="utf-8")
175
- missing_tools = [t for t in ("spaider.query", "spaider.feedback") if t not in body]
201
+ missing_tools = [
202
+ t for t in ("spaider.query", "spaider.feedback", "spaider.recall", "spaider.remember") if t not in body
203
+ ]
176
204
  if missing_tools:
177
205
  return _warn(
178
206
  "~/.claude/skills/spaider.md",
179
- f"present but missing references to {', '.join(missing_tools)} — re-install.",
207
+ f"out of date (no {', '.join(missing_tools)}). Run `spaider mcp skill`.",
180
208
  )
181
209
  return _ok("~/.claude/skills/spaider.md", "loaded by Claude Code at session start")
182
210
 
@@ -223,6 +251,7 @@ def run(
223
251
  results.append(check_env_file(repo))
224
252
  results.append(check_llm_key(repo))
225
253
  results.append(check_backend_health())
254
+ results.append(check_login())
226
255
  results.append(check_embedding_dimensions())
227
256
  results.append(check_mcp_config())
228
257
  results.append(check_skill_file())
@@ -0,0 +1,133 @@
1
+ """Federation grants, Knowledge PRs and fine-tuning."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ import typer
9
+ from rich.console import Console
10
+
11
+ from spaider_cli.lib import client
12
+
13
+ console = Console()
14
+ grant = typer.Typer(help="Share one knowledge base with another.", no_args_is_help=True)
15
+ kpr = typer.Typer(help="Propose merging knowledge between KBs.", no_args_is_help=True)
16
+ finetune = typer.Typer(help="Train a model on a KB's data with an external provider.", no_args_is_help=True)
17
+
18
+
19
+ def _show(value) -> None:
20
+ console.print_json(json.dumps(value))
21
+
22
+
23
+ @grant.command("request")
24
+ def grant_request(
25
+ source: str = typer.Argument(..., help="KB being read."),
26
+ target: str = typer.Argument(..., help="KB that will read it."),
27
+ node_type: Optional[list[str]] = typer.Option(None, "--node-type"),
28
+ relation: Optional[list[str]] = typer.Option(None, "--relation"),
29
+ max_clearance: int = typer.Option(1, "--max-clearance"),
30
+ expires_at: Optional[str] = typer.Option(None, "--expires-at", help="ISO 8601."),
31
+ ) -> None:
32
+ body = {
33
+ "source_kb": source, "target_kb": target, "node_types": node_type or None,
34
+ "relation_types": relation or None, "max_clearance": max_clearance, "expires_at": expires_at,
35
+ }
36
+ _show(client.request("POST", "/federation/grants", json=body))
37
+
38
+
39
+ @grant.command("list")
40
+ def grant_list() -> None:
41
+ _show(client.request("GET", "/federation/grants"))
42
+
43
+
44
+ @grant.command("approve")
45
+ def grant_approve(grant_id: str) -> None:
46
+ _show(client.request("POST", f"/federation/grants/{grant_id}/approve", json={}))
47
+
48
+
49
+ @grant.command("deny")
50
+ def grant_deny(grant_id: str) -> None:
51
+ _show(client.request("POST", f"/federation/grants/{grant_id}/deny"))
52
+
53
+
54
+ @grant.command("revoke")
55
+ def grant_revoke(grant_id: str) -> None:
56
+ _show(client.request("DELETE", f"/federation/grants/{grant_id}"))
57
+
58
+
59
+ @kpr.command("create")
60
+ def kpr_create(
61
+ source: str,
62
+ target: str,
63
+ node_ids: list[str] = typer.Argument(...),
64
+ title: str = typer.Option(..., "--title"),
65
+ ) -> None:
66
+ body = {"source_kb": source, "target_kb": target, "node_ids": node_ids, "title": title}
67
+ _show(client.request("POST", "/federation/kpr", json=body))
68
+
69
+
70
+ @kpr.command("list")
71
+ def kpr_list(target: str) -> None:
72
+ _show(client.request("GET", "/federation/kpr", params={"target_kb": target}))
73
+
74
+
75
+ @kpr.command("show")
76
+ def kpr_show(kpr_id: str) -> None:
77
+ _show(client.request("GET", f"/federation/kpr/{kpr_id}"))
78
+
79
+
80
+ @kpr.command("approve")
81
+ def kpr_approve(kpr_id: str) -> None:
82
+ _show(client.request("POST", f"/federation/kpr/{kpr_id}/approve"))
83
+
84
+
85
+ @kpr.command("reject")
86
+ def kpr_reject(kpr_id: str) -> None:
87
+ _show(client.request("POST", f"/federation/kpr/{kpr_id}/reject"))
88
+
89
+
90
+ @kpr.command("revert")
91
+ def kpr_revert(kpr_id: str) -> None:
92
+ _show(client.request("POST", f"/federation/kpr/{kpr_id}/revert"))
93
+
94
+
95
+ @finetune.command("create")
96
+ def finetune_create(
97
+ agent: str,
98
+ provider: str = typer.Option(..., "--provider", help="openai, together or tinker."),
99
+ base_model: str = typer.Option(..., "--base-model"),
100
+ data_clearance: int = typer.Option(1, "--data-clearance"),
101
+ ) -> None:
102
+ """Submit a job. Training data is sent to the provider."""
103
+ body = {"agent_id": agent, "provider": provider, "base_model": base_model, "data_clearance": data_clearance}
104
+ _show(client.request("POST", "/finetune/jobs", json=body, timeout=600))
105
+
106
+
107
+ @finetune.command("list")
108
+ def finetune_list(agent: str) -> None:
109
+ _show(client.request("GET", "/finetune/jobs", params={"agent_id": agent}))
110
+
111
+
112
+ @finetune.command("status")
113
+ def finetune_status(version_id: str) -> None:
114
+ _show(client.request("GET", f"/finetune/jobs/{version_id}"))
115
+
116
+
117
+ @finetune.command("evaluate")
118
+ def finetune_evaluate(
119
+ version_id: str,
120
+ items: Path = typer.Argument(..., exists=True, help='JSON list of {"question", "expected"}.'),
121
+ ) -> None:
122
+ body = {"items": json.loads(items.read_text(encoding="utf-8"))}
123
+ _show(client.request("POST", f"/finetune/jobs/{version_id}/evaluate", json=body, timeout=3600))
124
+
125
+
126
+ @finetune.command("promote")
127
+ def finetune_promote(version_id: str) -> None:
128
+ _show(client.request("POST", f"/finetune/jobs/{version_id}/promote"))
129
+
130
+
131
+ @finetune.command("rollback")
132
+ def finetune_rollback(agent: str) -> None:
133
+ _show(client.request("POST", "/finetune/rollback", params={"agent_id": agent}))
@@ -12,7 +12,7 @@ Order of operations:
12
12
  Neo4j password).
13
13
  4. Merge the values into the ``.env`` file (creating from ``.env.example`` if
14
14
  needed, preserving any user-set keys, backing up any prior version).
15
- 5. ``docker compose up -d backend-api``; wait for ``/health`` to go healthy.
15
+ 5. Build and start the stack with ``docker compose up``; wait for ``/health``.
16
16
  6. Provision a dev agent named ``dev-${USER}`` (or rotate it if it already
17
17
  exists).
18
18
  7. Install the MCP server entry + skill file into ``~/.claude/`` (skip with
@@ -29,6 +29,7 @@ from rich.panel import Panel
29
29
  from rich.prompt import Prompt
30
30
 
31
31
  from spaider_cli.lib import api as api_client
32
+ from spaider_cli.lib import config as config_lib
32
33
  from spaider_cli.lib import docker as docker_lib
33
34
  from spaider_cli.lib import env as env_lib
34
35
  from spaider_cli.lib import llm as llm_lib
@@ -112,7 +113,7 @@ def run(
112
113
  # Re-run safety: NEVER regenerate a secret that already exists in .env.
113
114
  # The running Neo4j container is created with whatever NEO4J_PASSWORD was in
114
115
  # .env at first boot; rewriting it on a re-run would lock the backend out of
115
- # its own database (and silently invalidate JWTs / connector ciphertext).
116
+ # its own database (and make connector ciphertext unreadable).
116
117
  # So generate only the secrets that are missing/empty, and preserve the rest.
117
118
  console.print("\n[bold][3/6] Generating secrets[/]")
118
119
  env_path = repo / ".env"
@@ -126,19 +127,19 @@ def run(
126
127
  current = existing.get(key, "").strip()
127
128
  return (current, True) if current else (generator(), False)
128
129
 
129
- jwt, jwt_kept = _keep_or_generate("JWT_SECRET", env_lib.generate_jwt_secret)
130
+ bootstrap_token, bootstrap_kept = _keep_or_generate("SPAIDER_BOOTSTRAP_TOKEN", env_lib.generate_bootstrap_token)
130
131
  connector_key, ck_kept = _keep_or_generate("CONNECTOR_SECRET_KEY", env_lib.generate_connector_key)
131
132
  neo4j_pw, neo_kept = _keep_or_generate("NEO4J_PASSWORD", env_lib.generate_neo4j_password)
132
- if jwt_kept or ck_kept or neo_kept:
133
+ if bootstrap_kept or ck_kept or neo_kept:
133
134
  console.print(" [green]✓[/] Reused existing secrets where present (re-run safe)")
134
135
  else:
135
- console.print(" [green]✓[/] JWT signing secret, connector encryption key, Neo4j password")
136
+ console.print(" [green]✓[/] Bootstrap token, connector encryption key, Neo4j password")
136
137
 
137
138
  # 4. .env
138
139
  console.print("\n[bold][4/6] Writing .env[/]")
139
140
  overrides = {
140
141
  **provider_overrides,
141
- "JWT_SECRET": jwt,
142
+ "SPAIDER_BOOTSTRAP_TOKEN": bootstrap_token,
142
143
  "CONNECTOR_SECRET_KEY": connector_key,
143
144
  "NEO4J_PASSWORD": neo4j_pw,
144
145
  }
@@ -159,7 +160,10 @@ def run(
159
160
  if skip_docker:
160
161
  console.print("\n[bold][5/6] Stack startup[/] [dim](skipped via --skip-docker)[/]")
161
162
  else:
162
- console.print("\n[bold][5/6] Starting Docker stack[/]")
163
+ console.print(
164
+ "\n[bold][5/6] Building and starting the stack[/] "
165
+ "[dim](the first build takes several minutes)[/]"
166
+ )
163
167
  compose = docker_lib.compose_up(repo)
164
168
  if not compose.ok:
165
169
  err_console.print(
@@ -167,7 +171,7 @@ def run(
167
171
  f" {compose.stderr.strip()[:400]}"
168
172
  )
169
173
  raise typer.Exit(code=1)
170
- console.print(" Containers starting…")
174
+ console.print(" Containers started")
171
175
  if not docker_lib.wait_for_backend():
172
176
  err_console.print(
173
177
  " [red]✗[/] backend-api did not become healthy within 120s. "
@@ -176,6 +180,14 @@ def run(
176
180
  raise typer.Exit(code=1)
177
181
  console.print(" [green]✓[/] backend-api healthy on :8000")
178
182
 
183
+ if not skip_docker and not config_lib.api_key():
184
+ try:
185
+ owner = api_client.bootstrap(bootstrap_token, "SpAIder", _default_agent_name())
186
+ config_lib.save(api_key=owner["api_key"])
187
+ console.print(" [green]✓[/] Owner key saved to your SpAIder config")
188
+ except api_client.SpaiderApiError as exc:
189
+ err_console.print(f" [yellow]![/] Could not create the owner: {exc}. Run [bold]spaider login[/].")
190
+
179
191
  # 6. Agent + MCP
180
192
  resolved_agent = agent_name or _default_agent_name()
181
193
  console.print(f"\n[bold][6/6] Provisioning agent '{resolved_agent}'[/]")
@@ -192,6 +204,7 @@ def run(
192
204
  err_console.print(f" [red]✗[/] agent provisioning failed: {exc}")
193
205
  raise typer.Exit(code=1)
194
206
  console.print(f" [green]✓[/] agent ready (id={agent_id})")
207
+ config_lib.save(agent_id=agent_id)
195
208
 
196
209
  if skip_mcp:
197
210
  console.print("\n[dim]Skipping MCP install (--skip-mcp).[/]")
@@ -21,6 +21,8 @@ import typer
21
21
  from rich.console import Console
22
22
 
23
23
  from spaider_cli.lib import api as api_client
24
+ from spaider_cli.lib import client as http_client
25
+ from spaider_cli.lib import clients as clients_lib
24
26
  from spaider_cli.lib import mcp as mcp_lib
25
27
 
26
28
  app = typer.Typer(no_args_is_help=True)
@@ -123,6 +125,34 @@ def install(
123
125
  # ---------------------------------------------------------------------------
124
126
 
125
127
 
128
+ @app.command("skill")
129
+ def skill() -> None:
130
+ """Refresh the Claude Code skill file. Keys and MCP entries are not touched."""
131
+ path = mcp_lib.claude_code_paths().skill_file
132
+ path.parent.mkdir(parents=True, exist_ok=True)
133
+ mcp_lib.backup_if_exists(path)
134
+ mcp_lib.atomic_write_text(path, mcp_lib.read_packaged_skill())
135
+ console.print(f"[green]✓[/] {path}")
136
+
137
+
138
+ @app.command("add")
139
+ def add(
140
+ client: str = typer.Argument(..., help=f"One of: {', '.join(clients_lib.SUPPORTED)}."),
141
+ agent: str | None = typer.Option(None, "--agent", help="Knowledge base id."),
142
+ url: str = typer.Option(DEFAULT_MCP_URL, "--url"),
143
+ ) -> None:
144
+ """Connect one client, with its own key that can be revoked separately."""
145
+ if client not in clients_lib.SUPPORTED:
146
+ console.print(f"[red]✗[/] Unknown client. Choose from: {', '.join(clients_lib.SUPPORTED)}")
147
+ raise typer.Exit(code=1)
148
+ kb = http_client.agent_or_exit(agent)
149
+ account = http_client.request(
150
+ "POST", f"/agents/{kb}/service-accounts", json={"name": f"mcp-{client}", "role": "contributor"}
151
+ )
152
+ path = clients_lib.install(client, url, account["api_key"])
153
+ console.print(f"[green]✓[/] {client} connected ({path})")
154
+
155
+
126
156
  def _default_agent_name() -> str:
127
157
  """Return ``dev-${USER}`` (falling back to ``dev-user`` on no $USER)."""
128
158
  import os
@@ -0,0 +1,95 @@
1
+ """Working with what a knowledge base remembers."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ import httpx
9
+ import typer
10
+ from rich.console import Console
11
+
12
+ from spaider_cli.lib import client, config
13
+
14
+ console = Console()
15
+ _AGENT = typer.Option(None, "--agent", "-a", help="Knowledge base id. Defaults to the logged-in one.")
16
+
17
+
18
+ def ingest(
19
+ text: Optional[str] = typer.Argument(None, help="Text to ingest."),
20
+ file: Optional[Path] = typer.Option(None, "--file", "-f", exists=True, dir_okay=False),
21
+ source: Optional[str] = typer.Option(None, "--source"),
22
+ agent: Optional[str] = _AGENT,
23
+ ) -> None:
24
+ """Extract knowledge from text into the graph."""
25
+ content = file.read_text(encoding="utf-8") if file else text
26
+ if not content:
27
+ console.print("[red]✗[/] Give some text or --file.")
28
+ raise typer.Exit(code=1)
29
+ body = {"text": content, "agent_id": client.agent_or_exit(agent), "source": source}
30
+ result = client.request("POST", "/ingest/sync", json=body)
31
+ console.print(
32
+ f"[green]✓[/] Nodes {result['nodes_created']} created, {result['nodes_merged']} merged; "
33
+ f"edges {result['edges_created']}"
34
+ )
35
+
36
+
37
+ def recall(
38
+ text: str = typer.Argument(..., help="What to look for."),
39
+ limit: int = typer.Option(10, "--limit", "-n"),
40
+ federated: bool = typer.Option(False, "--federated", help="Also search KBs shared with this one."),
41
+ agent: Optional[str] = _AGENT,
42
+ ) -> None:
43
+ """Search memory directly, with no LLM call."""
44
+ body = {"agent_id": client.agent_or_exit(agent), "query": text, "limit": limit, "federated": federated}
45
+ results = client.request("POST", "/recall", json=body)["results"]
46
+ if not results:
47
+ console.print("[dim]Nothing found.[/]")
48
+ for item in results:
49
+ console.print(f"[cyan]{item['type']:7}[/] {item['text']}", highlight=False)
50
+
51
+
52
+ def query(
53
+ question: str = typer.Argument(...),
54
+ agent: Optional[str] = _AGENT,
55
+ ) -> None:
56
+ """Ask a question and get a cited answer."""
57
+ result = client.request("POST", "/query", json={"question": question, "agent_id": client.agent_or_exit(agent)})
58
+ console.print(result["answer"], highlight=False)
59
+ for item in result.get("citations", []):
60
+ console.print(f"[dim][{item['ref']}] {item['label']}[/]", highlight=False)
61
+ if result.get("query_id"):
62
+ console.print(f"[dim]query_id: {result['query_id']}[/]")
63
+
64
+
65
+ def sleep(
66
+ agent: Optional[str] = _AGENT,
67
+ report: bool = typer.Option(False, "--report", help="Show the last report instead of running."),
68
+ ) -> None:
69
+ """Run the consolidation cycle now."""
70
+ kb = client.agent_or_exit(agent)
71
+ if report:
72
+ result = client.request("GET", f"/agents/{kb}/sleep/report")
73
+ else:
74
+ result = client.request("POST", f"/agents/{kb}/sleep", timeout=3600)
75
+ console.print_json(json.dumps(result))
76
+
77
+
78
+ def export(
79
+ output: Path = typer.Argument(..., help="File to write."),
80
+ embeddings: bool = typer.Option(False, "--embeddings"),
81
+ agent: Optional[str] = _AGENT,
82
+ ) -> None:
83
+ """Save a KB as NDJSON."""
84
+ kb = client.agent_or_exit(agent)
85
+ url = f"{config.api_base()}/agents/{kb}/export"
86
+ with httpx.stream(
87
+ "GET", url, params={"include_embeddings": embeddings}, headers=client.headers(), timeout=None
88
+ ) as response:
89
+ if response.status_code >= 400:
90
+ console.print(f"[red]✗[/] Export failed: {response.status_code}")
91
+ raise typer.Exit(code=1)
92
+ with output.open("wb") as handle:
93
+ for chunk in response.iter_bytes():
94
+ handle.write(chunk)
95
+ console.print(f"[green]✓[/] Wrote {output}")
@@ -0,0 +1,61 @@
1
+ """Stack lifecycle and login."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ from typing import Optional
6
+
7
+ import typer
8
+ from rich.console import Console
9
+
10
+ from spaider_cli.lib import client, config, stack
11
+
12
+ console = Console()
13
+ _PROFILE = typer.Option("lite", "--profile", help="lite (Neo4j and API) or full.")
14
+ _DIRECTORY = typer.Option(None, "--dir", help="Directory holding docker-compose.yml.")
15
+
16
+
17
+ def up(profile: str = _PROFILE, directory: Optional[Path] = _DIRECTORY) -> None:
18
+ """Start the stack."""
19
+ root = stack.locate(directory)
20
+ result = stack.compose(root, "up", "-d", "--wait", profile=profile)
21
+ if result.returncode:
22
+ raise typer.Exit(code=result.returncode)
23
+ console.print(f"[green]✓[/] Stack up ({profile}) from {root}")
24
+
25
+
26
+ def down(profile: str = _PROFILE, directory: Optional[Path] = _DIRECTORY) -> None:
27
+ """Stop the stack. Data volumes are kept."""
28
+ result = stack.compose(stack.locate(directory), "down", profile=profile)
29
+ raise typer.Exit(code=result.returncode)
30
+
31
+
32
+ def status() -> None:
33
+ """Show whether the API answers and who you are logged in as."""
34
+ base = config.api_base()
35
+ if not client.healthy():
36
+ console.print(f"[red]✗[/] No API at {base}")
37
+ raise typer.Exit(code=1)
38
+ console.print(f"[green]✓[/] API healthy at {base}")
39
+ if not config.api_key():
40
+ console.print("[yellow]![/] Not logged in. Run [bold]spaider login[/].")
41
+ return
42
+ who = client.request("GET", "/auth/whoami")
43
+ console.print(f"[green]✓[/] {who.get('name') or who.get('id')} ({who.get('org_role')})")
44
+
45
+
46
+ def logs(service: Optional[str] = typer.Argument(None), directory: Optional[Path] = _DIRECTORY) -> None:
47
+ """Follow container logs."""
48
+ arguments = ["logs", "-f", "--tail", "100"] + ([service] if service else [])
49
+ raise typer.Exit(code=stack.compose(stack.locate(directory), *arguments).returncode)
50
+
51
+
52
+ def login(
53
+ api_key: Optional[str] = typer.Option(None, "--api-key", help="Omit to be prompted without echo."),
54
+ url: str = typer.Option(config.DEFAULT_API_BASE, "--url"),
55
+ agent: Optional[str] = typer.Option(None, "--agent", help="Default knowledge base for commands."),
56
+ ) -> None:
57
+ """Save and verify an API key."""
58
+ key = api_key or typer.prompt("API key", hide_input=True)
59
+ who = client.request("GET", "/auth/whoami", base=url.rstrip("/"), key=key)
60
+ path = config.save(api_base=url.rstrip("/"), api_key=key, agent_id=agent or who.get("default_kb"))
61
+ console.print(f"[green]✓[/] Logged in as {who.get('name') or who.get('id')}. Saved to {path}")
@@ -3,25 +3,24 @@
3
3
  Thin wrapper over httpx that exposes only the endpoints the CLI needs. All
4
4
  calls target ``${SPAIDER_API_BASE:-http://localhost:8000/api/v1}`` by default.
5
5
 
6
- The local dev API does not require authentication for /agents endpoints; the
7
- client therefore makes unauthenticated calls. If the user is targeting a
8
- deployment behind Kong with auth enforced (production / managed Cloud), a
9
- future ``--api-key`` flag on the CLI will be plumbed through here.
6
+ Every call carries the key from ``spaider login`` or SPAIDER_API_KEY.
10
7
  """
11
8
  from __future__ import annotations
12
9
 
13
- import os
14
10
  from dataclasses import dataclass
15
11
  from typing import Any
16
12
 
17
13
  import httpx
18
14
 
15
+ from spaider_cli.lib import config
16
+ from spaider_cli.lib.client import headers as client_headers
17
+
19
18
  DEFAULT_API_BASE = "http://localhost:8000/api/v1"
20
19
 
21
20
 
22
21
  def api_base() -> str:
23
- """Resolve the API base URL from the environment, with a localhost default."""
24
- return os.environ.get("SPAIDER_API_BASE", DEFAULT_API_BASE).rstrip("/")
22
+ """The API base URL from the environment or saved login."""
23
+ return config.api_base()
25
24
 
26
25
 
27
26
  class SpaiderApiError(RuntimeError):
@@ -51,7 +50,25 @@ class Agent:
51
50
 
52
51
 
53
52
  def _client(timeout: float = 10.0) -> httpx.Client:
54
- return httpx.Client(base_url=api_base(), timeout=timeout)
53
+ return httpx.Client(base_url=api_base(), timeout=timeout, headers=client_headers())
54
+
55
+
56
+ def bootstrap(token: str, org_name: str, owner_name: str) -> dict[str, Any]:
57
+ """Create the first organization and owner. Works once per install."""
58
+ try:
59
+ with httpx.Client(base_url=api_base(), timeout=30.0) as client:
60
+ response = client.post(
61
+ "/auth/bootstrap",
62
+ json={"org_name": org_name, "owner_name": owner_name},
63
+ headers={"X-Bootstrap-Token": token},
64
+ )
65
+ except httpx.HTTPError as exc:
66
+ raise SpaiderApiError(f"bootstrap failed: {exc}") from exc
67
+ if response.status_code == 409:
68
+ raise SpaiderApiError("already-bootstrapped")
69
+ if response.status_code >= 400:
70
+ raise SpaiderApiError(f"bootstrap failed: {response.status_code}")
71
+ return response.json()
55
72
 
56
73
 
57
74
  def health() -> bool:
@@ -68,6 +85,16 @@ def health() -> bool:
68
85
  return False
69
86
 
70
87
 
88
+ def health_report() -> dict | None:
89
+ """The full /health body, or None when the API does not answer."""
90
+ try:
91
+ with httpx.Client(timeout=2.0) as c:
92
+ resp = c.get(f"{api_base().rsplit('/api', 1)[0]}/health")
93
+ return resp.json() if resp.status_code == 200 else None
94
+ except Exception:
95
+ return None
96
+
97
+
71
98
  def embedding_health() -> dict | None:
72
99
  """GET /health/embedding — embedding-dimension consistency report.
73
100