kyvvu-cli 1.0.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.
kyvvu_cli/client.py ADDED
@@ -0,0 +1,237 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Kyvvu B.V.
3
+
4
+ """Thin httpx wrapper with auth header injection and error handling."""
5
+ from __future__ import annotations
6
+
7
+ from contextlib import contextmanager
8
+ from typing import Any, Dict, Iterator, Optional, Tuple
9
+
10
+ import httpx
11
+ import typer
12
+
13
+ from kyvvu_cli.config import get_api_url, get_cli_auth
14
+
15
+
16
+ def _handle_http_error(
17
+ resp: httpx.Response, context: str = "", *, auth_type: str = "jwt",
18
+ ) -> None:
19
+ """Print a clear error message for HTTP failures and exit."""
20
+ if resp.status_code == 401:
21
+ if auth_type == "api_key":
22
+ typer.echo(
23
+ "API key rejected. Check that KV_API_KEY is set to a valid key.",
24
+ err=True,
25
+ )
26
+ else:
27
+ typer.echo("Your session has expired. Run `kyvvu auth` to continue.", err=True)
28
+ raise typer.Exit(1)
29
+ if resp.status_code == 429:
30
+ retry = resp.headers.get("Retry-After", "a few minutes")
31
+ typer.echo(f"Too many attempts. Try again in {retry}.", err=True)
32
+ raise typer.Exit(1)
33
+ if resp.status_code == 403:
34
+ typer.echo(
35
+ "You don't have permission for this action. "
36
+ "Your account may be pending verification — try `kyvvu whoami`.",
37
+ err=True,
38
+ )
39
+ raise typer.Exit(1)
40
+ if resp.status_code == 422:
41
+ detail, code = _error_detail(resp)
42
+ typer.echo(f"Validation error{_code_suffix(code)}: {detail}", err=True)
43
+ raise typer.Exit(1)
44
+ if resp.status_code >= 400:
45
+ detail, code = _error_detail(resp)
46
+ typer.echo(f"Error ({resp.status_code}{' ' + code if code else ''}): {detail}", err=True)
47
+ raise typer.Exit(1)
48
+
49
+
50
+ # A non-JSON error body (a proxy's HTML page, say) is cut to this many
51
+ # characters so the message stays one readable line.
52
+ _MAX_RAW_ERROR_CHARS = 300
53
+
54
+
55
+ def _code_suffix(code: Optional[str]) -> str:
56
+ return f" ({code})" if code else ""
57
+
58
+
59
+ def _format_detail(detail: Any) -> str:
60
+ """Render an API ``detail`` as one line.
61
+
62
+ ``detail`` is a string for the platform's own errors, and a list of
63
+ ``{"loc", "msg"}`` objects for a request FastAPI refused on validation.
64
+ """
65
+ if isinstance(detail, str):
66
+ return detail
67
+ if isinstance(detail, list):
68
+ parts = []
69
+ for item in detail:
70
+ if isinstance(item, dict) and "msg" in item:
71
+ loc = ".".join(str(x) for x in item.get("loc", []) if x != "body")
72
+ parts.append(f"{loc}: {item['msg']}" if loc else str(item["msg"]))
73
+ else:
74
+ parts.append(str(item))
75
+ return "; ".join(parts)
76
+ return str(detail)
77
+
78
+
79
+ def _error_detail(resp: httpx.Response) -> Tuple[str, Optional[str]]:
80
+ """Return ``(detail, code)`` from an API error response.
81
+
82
+ The platform answers every error as ``{"detail": ..., "code"?: ...}``
83
+ (#769). The person at the terminal needs those two, not the JSON body
84
+ they arrived in. A body that is not that shape is shown raw, on one line.
85
+ """
86
+ try:
87
+ body = resp.json()
88
+ except Exception:
89
+ body = None
90
+ if isinstance(body, dict) and "detail" in body:
91
+ code = body.get("code")
92
+ return _format_detail(body["detail"]), str(code) if code else None
93
+ raw = " ".join(resp.text.split()) or resp.reason_phrase or "no response body"
94
+ if len(raw) > _MAX_RAW_ERROR_CHARS:
95
+ raw = raw[:_MAX_RAW_ERROR_CHARS] + "..."
96
+ return raw, None
97
+
98
+
99
+ def _make_client(api_url: Optional[str] = None, timeout: float = 15.0) -> httpx.Client:
100
+ """Create an httpx client pointed at the API."""
101
+ base = api_url or get_api_url()
102
+ return httpx.Client(base_url=base, timeout=timeout)
103
+
104
+
105
+ @contextmanager
106
+ def _client_ctx(
107
+ client: Optional[httpx.Client], api_url: Optional[str] = None
108
+ ) -> Iterator[httpx.Client]:
109
+ """Yield *client* if provided (caller owns it), else a fresh one-shot client.
110
+
111
+ Lets callers reuse a single connection across a fan-out of requests while
112
+ keeping the single-call path unchanged (a fresh client per call).
113
+ """
114
+ if client is not None:
115
+ yield client
116
+ else:
117
+ with _make_client(api_url) as owned:
118
+ yield owned
119
+
120
+
121
+ def api_post(
122
+ path: str,
123
+ json: Optional[Dict[str, Any]] = None,
124
+ *,
125
+ jwt: Optional[str] = None,
126
+ api_key: Optional[str] = None,
127
+ api_url: Optional[str] = None,
128
+ client: Optional[httpx.Client] = None,
129
+ ) -> Dict[str, Any]:
130
+ """POST to the Kyvvu API with auth. Returns parsed JSON.
131
+
132
+ Pass *client* to reuse a single connection across multiple calls.
133
+ """
134
+ headers: Dict[str, str] = {"Content-Type": "application/json"}
135
+ if jwt:
136
+ headers["Authorization"] = f"Bearer {jwt}"
137
+ elif api_key:
138
+ headers["Authorization"] = f"Bearer {api_key}"
139
+
140
+ try:
141
+ with _client_ctx(client, api_url) as c:
142
+ resp = c.post(path, json=json, headers=headers)
143
+ except httpx.TimeoutException:
144
+ url = api_url or get_api_url()
145
+ typer.echo(
146
+ f"Error: Could not reach the Kyvvu platform at {url} (timed out).\n"
147
+ "Check your network connection and KV_API_URL.",
148
+ err=True,
149
+ )
150
+ raise typer.Exit(1)
151
+ except httpx.ConnectError:
152
+ url = api_url or get_api_url()
153
+ typer.echo(f"Could not reach {url}. Check your network connection or --api-url.", err=True)
154
+ raise typer.Exit(1)
155
+
156
+ _handle_http_error(resp, path, auth_type="api_key" if api_key else "jwt")
157
+ return resp.json() # type: ignore[no-any-return]
158
+
159
+
160
+ def api_get(
161
+ path: str,
162
+ params: Optional[Dict[str, Any]] = None,
163
+ *,
164
+ jwt: Optional[str] = None,
165
+ api_key: Optional[str] = None,
166
+ api_url: Optional[str] = None,
167
+ client: Optional[httpx.Client] = None,
168
+ ) -> Any:
169
+ """GET from the Kyvvu API with auth. Returns parsed JSON.
170
+
171
+ Pass *client* to reuse a single connection across multiple calls.
172
+ """
173
+ headers: Dict[str, str] = {}
174
+ if jwt:
175
+ headers["Authorization"] = f"Bearer {jwt}"
176
+ elif api_key:
177
+ headers["Authorization"] = f"Bearer {api_key}"
178
+
179
+ try:
180
+ with _client_ctx(client, api_url) as c:
181
+ resp = c.get(path, params=params, headers=headers)
182
+ except httpx.TimeoutException:
183
+ url = api_url or get_api_url()
184
+ typer.echo(
185
+ f"Error: Could not reach the Kyvvu platform at {url} (timed out).\n"
186
+ "Check your network connection and KV_API_URL.",
187
+ err=True,
188
+ )
189
+ raise typer.Exit(1)
190
+ except httpx.ConnectError:
191
+ url = api_url or get_api_url()
192
+ typer.echo(f"Could not reach {url}. Check your network connection or --api-url.", err=True)
193
+ raise typer.Exit(1)
194
+
195
+ _handle_http_error(resp, path, auth_type="api_key" if api_key else "jwt")
196
+ return resp.json()
197
+
198
+ def api_delete(
199
+ path: str,
200
+ *,
201
+ jwt: Optional[str] = None,
202
+ api_key: Optional[str] = None,
203
+ api_url: Optional[str] = None,
204
+ client: Optional[httpx.Client] = None,
205
+ ) -> None:
206
+ """DELETE to the Kyvvu API with auth.
207
+
208
+ Pass *client* to reuse a single connection across multiple calls.
209
+ """
210
+ headers: Dict[str, str] = {}
211
+ if jwt:
212
+ headers["Authorization"] = f"Bearer {jwt}"
213
+ elif api_key:
214
+ headers["Authorization"] = f"Bearer {api_key}"
215
+
216
+ try:
217
+ with _client_ctx(client, api_url) as c:
218
+ resp = c.delete(path, headers=headers)
219
+ except httpx.TimeoutException:
220
+ url = api_url or get_api_url()
221
+ typer.echo(f"Error: Could not reach {url} (timed out).", err=True)
222
+ raise typer.Exit(1)
223
+ except httpx.ConnectError:
224
+ url = api_url or get_api_url()
225
+ typer.echo(f"Could not reach {url}.", err=True)
226
+ raise typer.Exit(1)
227
+
228
+ _handle_http_error(resp, path, auth_type="api_key" if api_key else "jwt")
229
+
230
+
231
+ def require_cli_pat() -> str:
232
+ """Return the stored CLI PAT or exit with a prompt to run `kyvvu auth`."""
233
+ api_key = get_cli_auth().get("api_key")
234
+ if not api_key:
235
+ typer.echo("Run `kyvvu auth` to continue.", err=True)
236
+ raise typer.Exit(1)
237
+ return str(api_key)
kyvvu_cli/config.py ADDED
@@ -0,0 +1,71 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2026 Kyvvu B.V.
3
+
4
+ """TOML config storage at ~/.kyvvu/config.toml.
5
+
6
+ Handles reading and writing. File mode 0600.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import tomllib
12
+ from pathlib import Path
13
+ from typing import Any, Dict
14
+
15
+ import tomli_w
16
+
17
+ _CONFIG_DIR = Path.home() / ".kyvvu"
18
+ _CONFIG_FILE = _CONFIG_DIR / "config.toml"
19
+
20
+
21
+ def _ensure_dir() -> None:
22
+ _CONFIG_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
23
+
24
+
25
+ def load_config(path: Path | None = None) -> Dict[str, Any]:
26
+ """Load config from ~/.kyvvu/config.toml. Returns empty dict if missing."""
27
+ config_file = path or _CONFIG_FILE
28
+ if not config_file.exists():
29
+ return {}
30
+ return tomllib.loads(config_file.read_text(encoding="utf-8"))
31
+
32
+
33
+ def save_config(data: Dict[str, Any]) -> None:
34
+ """Write config to ~/.kyvvu/config.toml with mode 0600."""
35
+ _ensure_dir()
36
+ _CONFIG_FILE.write_bytes(tomli_w.dumps(data).encode("utf-8"))
37
+ os.chmod(_CONFIG_FILE, 0o600)
38
+
39
+
40
+ def get_cli_auth(path: Path | None = None) -> Dict[str, Any]:
41
+ """Return the [cli] section or empty dict."""
42
+ result: Dict[str, Any] = load_config(path).get("cli", {})
43
+ return result
44
+
45
+
46
+ def save_cli_auth(api_key: str, api_url: str) -> None:
47
+ """Update [cli] section, preserving other sections."""
48
+ cfg = load_config()
49
+ cfg["cli"] = {
50
+ "api_key": api_key,
51
+ "api_url": api_url,
52
+ }
53
+ save_config(cfg)
54
+
55
+
56
+ def clear_cli_auth() -> None:
57
+ """Remove [cli] section, keep everything else."""
58
+ cfg = load_config()
59
+ cfg.pop("cli", None)
60
+ save_config(cfg)
61
+
62
+
63
+ def get_api_url() -> str:
64
+ """Resolve the API URL: env var > cli config > default."""
65
+ env = os.environ.get("KV_API_URL")
66
+ if env:
67
+ return env.rstrip("/")
68
+ cli_auth = get_cli_auth()
69
+ if cli_auth.get("api_url"):
70
+ return str(cli_auth["api_url"]).rstrip("/")
71
+ return "https://platform.kyvvu.com"