kitani-cli 0.2.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.
- kitani/__init__.py +5 -0
- kitani/cli.py +624 -0
- kitani/client.py +480 -0
- kitani/profile.py +69 -0
- kitani/py.typed +0 -0
- kitani/updates.py +122 -0
- kitani/wallet.py +192 -0
- kitani_cli-0.2.0.dist-info/METADATA +149 -0
- kitani_cli-0.2.0.dist-info/RECORD +11 -0
- kitani_cli-0.2.0.dist-info/WHEEL +4 -0
- kitani_cli-0.2.0.dist-info/entry_points.txt +2 -0
kitani/client.py
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
"""A pooled client for browser authorization, funding, and inference."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from collections.abc import Iterator, Mapping, Sequence
|
|
9
|
+
from contextlib import AbstractContextManager
|
|
10
|
+
from decimal import Decimal, InvalidOperation
|
|
11
|
+
from importlib.metadata import version
|
|
12
|
+
from typing import Any, Literal
|
|
13
|
+
from uuid import uuid4
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
JSON = dict[str, Any]
|
|
18
|
+
Method = Literal["paypal", "tao", "alpha"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class KitaniError(Exception):
|
|
22
|
+
"""An API or transport error, with HTTP status and optional retry delay."""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self, message: str, *, status: int = 0, retry_after: str | None = None
|
|
26
|
+
):
|
|
27
|
+
super().__init__(message)
|
|
28
|
+
self.status = status
|
|
29
|
+
self.retry_after = retry_after
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def usd_cents(amount: str | Decimal) -> int:
|
|
33
|
+
try:
|
|
34
|
+
value = Decimal(amount)
|
|
35
|
+
if not value.is_finite() or not Decimal(5) <= value <= Decimal(1000):
|
|
36
|
+
raise ValueError("Enter a USD amount between 5 and 1000.")
|
|
37
|
+
numerator, denominator = value.as_integer_ratio()
|
|
38
|
+
cents, remainder = divmod(numerator * 100, denominator)
|
|
39
|
+
if remainder:
|
|
40
|
+
raise ValueError("USD amounts support up to two decimal places.")
|
|
41
|
+
return int(cents)
|
|
42
|
+
except InvalidOperation as exc:
|
|
43
|
+
raise ValueError("Enter a decimal USD amount.") from exc
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def key_budget(value: str | Decimal) -> float:
|
|
47
|
+
try:
|
|
48
|
+
budget = Decimal(value)
|
|
49
|
+
if (
|
|
50
|
+
not budget.is_finite()
|
|
51
|
+
or not 0 <= budget <= 100000
|
|
52
|
+
or budget != budget.quantize(Decimal("0.01"))
|
|
53
|
+
):
|
|
54
|
+
raise ValueError(
|
|
55
|
+
"Use a USD budget between 0 and 100000, with at most two decimal places."
|
|
56
|
+
)
|
|
57
|
+
except InvalidOperation as exc:
|
|
58
|
+
raise ValueError("Enter a decimal USD budget.") from exc
|
|
59
|
+
return float(budget)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def segment(value: str) -> str:
|
|
63
|
+
if not re.fullmatch(r"[A-Za-z0-9_-]{1,200}", value):
|
|
64
|
+
raise ValueError("Invalid resource ID.")
|
|
65
|
+
return value
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Kitani(AbstractContextManager["Kitani"]):
|
|
69
|
+
"""Use as a context manager. A caller-supplied HTTP client remains caller-owned."""
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
*,
|
|
74
|
+
fingerprint: str | None = None,
|
|
75
|
+
api_key: str | None = None,
|
|
76
|
+
client: httpx.Client | None = None,
|
|
77
|
+
):
|
|
78
|
+
self.fingerprint = fingerprint or os.getenv("KITANI_FINGERPRINT")
|
|
79
|
+
self.api_key = api_key or os.getenv("KITANI_API_KEY")
|
|
80
|
+
self._http = (
|
|
81
|
+
client
|
|
82
|
+
if client is not None
|
|
83
|
+
else httpx.Client(
|
|
84
|
+
base_url="https://api.kitani.ai/v1/",
|
|
85
|
+
timeout=httpx.Timeout(90, connect=10),
|
|
86
|
+
headers={"User-Agent": f"kitani-python/{version('kitani-cli')}"},
|
|
87
|
+
follow_redirects=False,
|
|
88
|
+
)
|
|
89
|
+
)
|
|
90
|
+
self._owns_client = client is None
|
|
91
|
+
|
|
92
|
+
def close(self) -> None:
|
|
93
|
+
if self._owns_client:
|
|
94
|
+
self._http.close()
|
|
95
|
+
|
|
96
|
+
def __exit__(self, *exc: object) -> None:
|
|
97
|
+
self.close()
|
|
98
|
+
|
|
99
|
+
def _headers(self, credential: str | None) -> dict[str, str]:
|
|
100
|
+
if credential is None:
|
|
101
|
+
return {}
|
|
102
|
+
secret = self.api_key if credential == "api_key" else self.fingerprint
|
|
103
|
+
if not secret:
|
|
104
|
+
raise KitaniError(
|
|
105
|
+
f"A {credential.replace('_', ' ')} is required.", status=401
|
|
106
|
+
)
|
|
107
|
+
return {"Authorization": f"Bearer {secret}"}
|
|
108
|
+
|
|
109
|
+
@staticmethod
|
|
110
|
+
def _check(r: httpx.Response) -> None:
|
|
111
|
+
if r.is_success:
|
|
112
|
+
return
|
|
113
|
+
try:
|
|
114
|
+
data = r.json()
|
|
115
|
+
error = data.get("error", data) if isinstance(data, dict) else {}
|
|
116
|
+
message = error.get("message") if isinstance(error, dict) else str(error)
|
|
117
|
+
except ValueError:
|
|
118
|
+
message = None
|
|
119
|
+
raise KitaniError(
|
|
120
|
+
message or f"Kitani returned HTTP {r.status_code}.",
|
|
121
|
+
status=r.status_code,
|
|
122
|
+
retry_after=r.headers.get("Retry-After"),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def _request(
|
|
126
|
+
self,
|
|
127
|
+
verb: str,
|
|
128
|
+
path: str,
|
|
129
|
+
*,
|
|
130
|
+
credential: str | None = None,
|
|
131
|
+
body: JSON | None = None,
|
|
132
|
+
params: Mapping[str, str | int | None] | None = None,
|
|
133
|
+
) -> JSON:
|
|
134
|
+
try:
|
|
135
|
+
r = self._http.request(
|
|
136
|
+
verb,
|
|
137
|
+
path,
|
|
138
|
+
headers=self._headers(credential),
|
|
139
|
+
json=body,
|
|
140
|
+
params={k: v for k, v in (params or {}).items() if v is not None},
|
|
141
|
+
)
|
|
142
|
+
self._check(r)
|
|
143
|
+
if r.status_code == 204:
|
|
144
|
+
return {}
|
|
145
|
+
result = r.json()
|
|
146
|
+
if not isinstance(result, dict):
|
|
147
|
+
raise KitaniError("Kitani returned an invalid JSON response.")
|
|
148
|
+
return result
|
|
149
|
+
except httpx.HTTPError as exc:
|
|
150
|
+
raise KitaniError(
|
|
151
|
+
"Connection failed. Check the operation status before retrying a write."
|
|
152
|
+
) from exc
|
|
153
|
+
except ValueError as exc:
|
|
154
|
+
raise KitaniError("Kitani returned an invalid JSON response.") from exc
|
|
155
|
+
|
|
156
|
+
def start_signup(self, name: str | None = None) -> JSON:
|
|
157
|
+
"""Return a public verification URL and a private device polling credential."""
|
|
158
|
+
return self._request(
|
|
159
|
+
"POST", "cli/device/start", body={"name": name} if name else {}
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
def poll_signup(self, device_code: str) -> JSON:
|
|
163
|
+
"""Poll once at the advertised interval. Approved responses contain a secret."""
|
|
164
|
+
return self._request(
|
|
165
|
+
"POST", "cli/device/token", body={"device_code": device_code}
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def account(self) -> JSON:
|
|
169
|
+
return self._request("GET", "cli/account", credential="fingerprint")
|
|
170
|
+
|
|
171
|
+
def revoke_fingerprint(self) -> JSON:
|
|
172
|
+
return self._request("DELETE", "cli/credential", credential="fingerprint")
|
|
173
|
+
|
|
174
|
+
def create_key(self, name: str, *, budget_usd: str | Decimal | None = None) -> JSON:
|
|
175
|
+
"""Create an inference key. The response contains the secret once."""
|
|
176
|
+
body: JSON = {"name": name}
|
|
177
|
+
if budget_usd is not None:
|
|
178
|
+
body["usage_limit_usd"] = key_budget(budget_usd)
|
|
179
|
+
return self._request("POST", "cli/keys", credential="fingerprint", body=body)
|
|
180
|
+
|
|
181
|
+
def set_key_budget(self, key_id: str, budget_usd: str | Decimal | None) -> JSON:
|
|
182
|
+
"""Update the lifetime ceiling of a CLI-issued key. None removes its ceiling."""
|
|
183
|
+
return self._request(
|
|
184
|
+
"PATCH",
|
|
185
|
+
f"cli/keys/{segment(key_id)}/usage-limit",
|
|
186
|
+
credential="fingerprint",
|
|
187
|
+
body={
|
|
188
|
+
"usage_limit_usd": None
|
|
189
|
+
if budget_usd is None
|
|
190
|
+
else key_budget(budget_usd)
|
|
191
|
+
},
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
def rotate_key(self, key_id: str, current_fingerprint: str) -> JSON:
|
|
195
|
+
"""Replace a CLI-issued key's secret, preserving its ledger and budget."""
|
|
196
|
+
return self._request(
|
|
197
|
+
"POST",
|
|
198
|
+
f"cli/keys/{segment(key_id)}/rotate",
|
|
199
|
+
credential="fingerprint",
|
|
200
|
+
body={"fingerprint": current_fingerprint},
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
def revoke_key(self, key_id: str) -> JSON:
|
|
204
|
+
"""Revoke a CLI-created inference key belonging to the current account."""
|
|
205
|
+
return self._request(
|
|
206
|
+
"DELETE", f"cli/keys/{segment(key_id)}", credential="fingerprint"
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
def keys(self) -> JSON:
|
|
210
|
+
"""Return account key metadata, including spend and limits, without secrets."""
|
|
211
|
+
return self._request("GET", "cli/keys", credential="fingerprint")
|
|
212
|
+
|
|
213
|
+
def usage(
|
|
214
|
+
self, *, since: str = "30d", group_by: Literal["model", "key"] = "model"
|
|
215
|
+
) -> JSON:
|
|
216
|
+
return self._request(
|
|
217
|
+
"GET",
|
|
218
|
+
"cli/usage",
|
|
219
|
+
credential="fingerprint",
|
|
220
|
+
params={"since": since, "group_by": group_by},
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
def requests(
|
|
224
|
+
self,
|
|
225
|
+
*,
|
|
226
|
+
limit: int = 10,
|
|
227
|
+
since: str | None = None,
|
|
228
|
+
model: str | None = None,
|
|
229
|
+
key_id: str | None = None,
|
|
230
|
+
cursor: str | None = None,
|
|
231
|
+
) -> JSON:
|
|
232
|
+
return self._request(
|
|
233
|
+
"GET",
|
|
234
|
+
"cli/requests",
|
|
235
|
+
credential="fingerprint",
|
|
236
|
+
params={
|
|
237
|
+
"limit": limit,
|
|
238
|
+
"since": since,
|
|
239
|
+
"model": model,
|
|
240
|
+
"key_id": key_id,
|
|
241
|
+
"cursor": cursor,
|
|
242
|
+
},
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
def payment_history(self, *, limit: int = 20, cursor: str | None = None) -> JSON:
|
|
246
|
+
"""Page through dashboard and CLI payments, newest first."""
|
|
247
|
+
return self._request(
|
|
248
|
+
"GET",
|
|
249
|
+
"cli/payments",
|
|
250
|
+
credential="fingerprint",
|
|
251
|
+
params={"limit": limit, "cursor": cursor},
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
def terminals(self) -> JSON:
|
|
255
|
+
return self._request("GET", "cli/terminals", credential="fingerprint")
|
|
256
|
+
|
|
257
|
+
def revoke_terminal(self, terminal_id: str) -> JSON:
|
|
258
|
+
return self._request(
|
|
259
|
+
"DELETE", f"cli/terminals/{segment(terminal_id)}", credential="fingerprint"
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
def recovery_email(self) -> JSON:
|
|
263
|
+
return self._request("GET", "cli/recovery/email", credential="fingerprint")
|
|
264
|
+
|
|
265
|
+
def add_recovery_email(self, email: str) -> JSON:
|
|
266
|
+
"""Send a verification code. Persist challenge_token privately until verified."""
|
|
267
|
+
return self._request(
|
|
268
|
+
"POST",
|
|
269
|
+
"cli/recovery/email/start",
|
|
270
|
+
credential="fingerprint",
|
|
271
|
+
body={"email": email},
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
def verify_recovery_email(self, challenge_token: str, code: str) -> JSON:
|
|
275
|
+
return self._request(
|
|
276
|
+
"POST",
|
|
277
|
+
"cli/recovery/email/verify",
|
|
278
|
+
credential="fingerprint",
|
|
279
|
+
body={"challenge_token": challenge_token, "code": code},
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
def models(self) -> JSON:
|
|
283
|
+
return self._request("GET", "models")
|
|
284
|
+
|
|
285
|
+
def model(self, model_id: str) -> JSON:
|
|
286
|
+
"""Retrieve one model’s published capabilities, limits, and serving details."""
|
|
287
|
+
if not re.fullmatch(
|
|
288
|
+
r"[A-Za-z0-9_-][A-Za-z0-9_.-]*/[A-Za-z0-9_-][A-Za-z0-9_.-]*", model_id
|
|
289
|
+
):
|
|
290
|
+
raise ValueError("Use the complete publisher/model ID from kitani models.")
|
|
291
|
+
return self._request("GET", f"models/{model_id}")
|
|
292
|
+
|
|
293
|
+
def performance(self) -> JSON:
|
|
294
|
+
"""Last-day model latency and throughput for qualified network samples."""
|
|
295
|
+
return self._request("GET", "network/performance")
|
|
296
|
+
|
|
297
|
+
def pricing(
|
|
298
|
+
self,
|
|
299
|
+
model_id: str | None = None,
|
|
300
|
+
*,
|
|
301
|
+
online_only: bool = False,
|
|
302
|
+
capability: str | None = None,
|
|
303
|
+
min_context: int | None = None,
|
|
304
|
+
sort: Literal["input-price"] | None = None,
|
|
305
|
+
) -> JSON:
|
|
306
|
+
"""Get the website’s pricing snapshot. A null miner count means unavailable."""
|
|
307
|
+
# Use the public website's snapshot without copying API credentials or cookies
|
|
308
|
+
# to a second origin, including defaults supplied on an injected HTTP client.
|
|
309
|
+
request = httpx.Request(
|
|
310
|
+
"GET",
|
|
311
|
+
"https://kitani.ai/api/pricing",
|
|
312
|
+
headers={"Accept": "application/json"},
|
|
313
|
+
)
|
|
314
|
+
try:
|
|
315
|
+
response = self._http.send(request, auth=None, follow_redirects=False)
|
|
316
|
+
self._check(response)
|
|
317
|
+
snapshot = response.json()
|
|
318
|
+
except (httpx.HTTPError, ValueError) as exc:
|
|
319
|
+
raise KitaniError("Could not read the Kitani pricing snapshot.") from exc
|
|
320
|
+
if (
|
|
321
|
+
not isinstance(snapshot, dict)
|
|
322
|
+
or snapshot.get("catalogAvailable") is not True
|
|
323
|
+
):
|
|
324
|
+
raise KitaniError(
|
|
325
|
+
"The model pricing catalog is temporarily unavailable.", status=503
|
|
326
|
+
)
|
|
327
|
+
rows = snapshot.get("rows")
|
|
328
|
+
if not isinstance(rows, list) or not all(
|
|
329
|
+
isinstance(row, dict) and isinstance(row.get("id"), str) for row in rows
|
|
330
|
+
):
|
|
331
|
+
raise KitaniError("Kitani returned an invalid pricing catalog.")
|
|
332
|
+
if model_id is not None:
|
|
333
|
+
rows = [row for row in rows if row["id"] == model_id]
|
|
334
|
+
if not rows:
|
|
335
|
+
raise KitaniError(f"Unknown catalog model: {model_id}", status=404)
|
|
336
|
+
if online_only:
|
|
337
|
+
if snapshot.get("totalMiners") is None:
|
|
338
|
+
raise KitaniError(
|
|
339
|
+
"Online miner counts are temporarily unavailable.", status=503
|
|
340
|
+
)
|
|
341
|
+
rows = [row for row in rows if (row.get("miners") or 0) > 0]
|
|
342
|
+
if min_context is not None:
|
|
343
|
+
if min_context < 1:
|
|
344
|
+
raise ValueError("Minimum context must be a positive token count.")
|
|
345
|
+
rows = [row for row in rows if (row.get("context") or 0) >= min_context]
|
|
346
|
+
if capability:
|
|
347
|
+
# Older website snapshots omit capabilities. Join the public catalog by ID
|
|
348
|
+
# once, rather than treating a missing field as proof of absent support.
|
|
349
|
+
old_models = {}
|
|
350
|
+
if any("capabilities" not in r for r in rows):
|
|
351
|
+
old_models = {m["id"]: m for m in self.models()["data"]}
|
|
352
|
+
wanted = capability.strip().casefold()
|
|
353
|
+
|
|
354
|
+
def supports(row):
|
|
355
|
+
meta = (
|
|
356
|
+
old_models.get(row["id"], {}) if "capabilities" not in row else row
|
|
357
|
+
)
|
|
358
|
+
caps = {value.casefold() for value in (meta.get("capabilities") or [])}
|
|
359
|
+
if wanted == "tools":
|
|
360
|
+
return (
|
|
361
|
+
row.get("tools") is True
|
|
362
|
+
or bool(
|
|
363
|
+
caps
|
|
364
|
+
& {
|
|
365
|
+
"tools",
|
|
366
|
+
"tool use",
|
|
367
|
+
"tool calling",
|
|
368
|
+
"tool_use",
|
|
369
|
+
"tool_calls",
|
|
370
|
+
"tool_calling",
|
|
371
|
+
"function calling",
|
|
372
|
+
"function_calling",
|
|
373
|
+
}
|
|
374
|
+
)
|
|
375
|
+
or "tools" in (meta.get("supported_parameters") or [])
|
|
376
|
+
)
|
|
377
|
+
return wanted in caps
|
|
378
|
+
|
|
379
|
+
rows = [row for row in rows if supports(row)]
|
|
380
|
+
if sort is not None:
|
|
381
|
+
if sort != "input-price":
|
|
382
|
+
raise ValueError("Unknown pricing sort.")
|
|
383
|
+
rows = sorted(
|
|
384
|
+
rows,
|
|
385
|
+
key=lambda row: (
|
|
386
|
+
row.get("input") is None,
|
|
387
|
+
row.get("input") or 0,
|
|
388
|
+
row["id"],
|
|
389
|
+
),
|
|
390
|
+
)
|
|
391
|
+
return {**snapshot, "rows": rows}
|
|
392
|
+
|
|
393
|
+
def chat(
|
|
394
|
+
self, model: str, messages: Sequence[Mapping[str, Any]], **options: Any
|
|
395
|
+
) -> JSON:
|
|
396
|
+
if options.get("stream"):
|
|
397
|
+
raise ValueError("Use stream_chat() for streaming responses.")
|
|
398
|
+
return self._request(
|
|
399
|
+
"POST",
|
|
400
|
+
"chat/completions",
|
|
401
|
+
credential="api_key",
|
|
402
|
+
body={**options, "model": model, "messages": list(messages)},
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
def stream_chat(
|
|
406
|
+
self, model: str, messages: Sequence[Mapping[str, Any]], **options: Any
|
|
407
|
+
) -> Iterator[JSON]:
|
|
408
|
+
"""Yield OpenAI-compatible SSE chunks, including usage and tool-call deltas."""
|
|
409
|
+
body = {**options, "model": model, "messages": list(messages), "stream": True}
|
|
410
|
+
try:
|
|
411
|
+
with self._http.stream(
|
|
412
|
+
"POST", "chat/completions", json=body, headers=self._headers("api_key")
|
|
413
|
+
) as r:
|
|
414
|
+
if not r.is_success:
|
|
415
|
+
r.read()
|
|
416
|
+
self._check(r)
|
|
417
|
+
data: list[str] = []
|
|
418
|
+
for line in r.iter_lines():
|
|
419
|
+
if line.startswith("data:"):
|
|
420
|
+
data.append(line[5:].lstrip(" "))
|
|
421
|
+
elif not line and data:
|
|
422
|
+
event = "\n".join(data)
|
|
423
|
+
data.clear()
|
|
424
|
+
if event == "[DONE]":
|
|
425
|
+
return
|
|
426
|
+
chunk = json.loads(event)
|
|
427
|
+
if not isinstance(chunk, dict) or "error" in chunk:
|
|
428
|
+
raise KitaniError(
|
|
429
|
+
"Kitani reported an error during streaming."
|
|
430
|
+
)
|
|
431
|
+
yield chunk
|
|
432
|
+
raise KitaniError("Stream ended before the completion marker.")
|
|
433
|
+
except (httpx.HTTPError, ValueError) as exc:
|
|
434
|
+
raise KitaniError("The inference stream was interrupted.") from exc
|
|
435
|
+
|
|
436
|
+
@staticmethod
|
|
437
|
+
def new_idempotency_key() -> str:
|
|
438
|
+
return str(uuid4())
|
|
439
|
+
|
|
440
|
+
def payment_link(
|
|
441
|
+
self, usd: str | Decimal, method: Method, *, idempotency_key: str
|
|
442
|
+
) -> JSON:
|
|
443
|
+
"""Reuse the same key, amount and method for retries of one top-up."""
|
|
444
|
+
if method not in ("paypal", "tao", "alpha"):
|
|
445
|
+
raise ValueError("Choose paypal, tao, or alpha.")
|
|
446
|
+
return self._request(
|
|
447
|
+
"POST",
|
|
448
|
+
"cli/payments",
|
|
449
|
+
credential="fingerprint",
|
|
450
|
+
body={
|
|
451
|
+
"amount_cents": usd_cents(usd),
|
|
452
|
+
"method": method,
|
|
453
|
+
"idempotency_key": idempotency_key,
|
|
454
|
+
},
|
|
455
|
+
)
|
|
456
|
+
|
|
457
|
+
def payment(self, payment_id: str) -> JSON:
|
|
458
|
+
return self._request(
|
|
459
|
+
"GET", f"cli/payments/{segment(payment_id)}", credential="fingerprint"
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
def quote(self, payment_id: str, sender: str, *, hotkey: str | None = None) -> JSON:
|
|
463
|
+
"""Request a sender-bound Finney quote. For alpha, identify the staked hotkey."""
|
|
464
|
+
body = {"sender": sender}
|
|
465
|
+
if hotkey:
|
|
466
|
+
body["hotkey"] = hotkey
|
|
467
|
+
return self._request(
|
|
468
|
+
"POST",
|
|
469
|
+
f"cli/payments/{segment(payment_id)}/quote",
|
|
470
|
+
credential="fingerprint",
|
|
471
|
+
body=body,
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
def submit(self, payment_id: str, quote_id: str, signature: str) -> JSON:
|
|
475
|
+
return self._request(
|
|
476
|
+
"POST",
|
|
477
|
+
f"cli/payments/{segment(payment_id)}/submit",
|
|
478
|
+
credential="fingerprint",
|
|
479
|
+
body={"quote_id": quote_id, "signature": signature},
|
|
480
|
+
)
|
kitani/profile.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Local CLI profile. Secrets are never included in the normal command output."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sqlite3
|
|
8
|
+
from contextlib import closing
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Profile:
|
|
14
|
+
def __init__(self, directory: Path | None = None):
|
|
15
|
+
directory = (
|
|
16
|
+
directory
|
|
17
|
+
or Path(
|
|
18
|
+
os.environ.get("KITANI_CONFIG_DIR", "~/.config/kitani")
|
|
19
|
+
).expanduser()
|
|
20
|
+
)
|
|
21
|
+
self.path = directory / "profile.sqlite3"
|
|
22
|
+
if self.path.exists():
|
|
23
|
+
self._prepare()
|
|
24
|
+
|
|
25
|
+
def _prepare(self) -> None:
|
|
26
|
+
directory = self.path.parent
|
|
27
|
+
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
28
|
+
if os.name == "posix" and (
|
|
29
|
+
directory.stat().st_mode & 0o022 or directory.stat().st_uid != os.geteuid()
|
|
30
|
+
):
|
|
31
|
+
raise ValueError(
|
|
32
|
+
"Use a Kitani profile directory owned by you and writable only by you."
|
|
33
|
+
)
|
|
34
|
+
if directory.is_symlink() or self.path.is_symlink():
|
|
35
|
+
raise ValueError("Kitani requires a private profile directory and file.")
|
|
36
|
+
# The mode applies at creation, before SQLite ever writes a credential.
|
|
37
|
+
fd = os.open(
|
|
38
|
+
self.path, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600
|
|
39
|
+
)
|
|
40
|
+
try:
|
|
41
|
+
if os.name == "posix" and os.fstat(fd).st_mode & 0o077:
|
|
42
|
+
raise ValueError("Restrict your Kitani profile file to mode 0600.")
|
|
43
|
+
finally:
|
|
44
|
+
os.close(fd)
|
|
45
|
+
with closing(sqlite3.connect(self.path)) as db:
|
|
46
|
+
db.execute(
|
|
47
|
+
"CREATE TABLE IF NOT EXISTS profile (name TEXT PRIMARY KEY, value TEXT NOT NULL)"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
def get(self, name: str, default: Any = None) -> Any:
|
|
51
|
+
if not self.path.exists():
|
|
52
|
+
return default
|
|
53
|
+
with closing(sqlite3.connect(self.path)) as db:
|
|
54
|
+
row = db.execute(
|
|
55
|
+
"SELECT value FROM profile WHERE name = ?", (name,)
|
|
56
|
+
).fetchone()
|
|
57
|
+
return json.loads(row[0]) if row else default
|
|
58
|
+
|
|
59
|
+
def update(self, **values: Any) -> None:
|
|
60
|
+
self._prepare()
|
|
61
|
+
with closing(sqlite3.connect(self.path)) as db, db:
|
|
62
|
+
for name, value in values.items():
|
|
63
|
+
if value is None:
|
|
64
|
+
db.execute("DELETE FROM profile WHERE name = ?", (name,))
|
|
65
|
+
else:
|
|
66
|
+
db.execute(
|
|
67
|
+
"INSERT OR REPLACE INTO profile VALUES (?, ?)",
|
|
68
|
+
(name, json.dumps(value)),
|
|
69
|
+
)
|
kitani/py.typed
ADDED
|
File without changes
|
kitani/updates.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Best-effort release notices for interactive CLI sessions."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import platform
|
|
6
|
+
import shlex
|
|
7
|
+
import sqlite3
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
from importlib.metadata import version
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
from packaging.specifiers import InvalidSpecifier, SpecifierSet
|
|
16
|
+
from packaging.utils import parse_sdist_filename, parse_wheel_filename
|
|
17
|
+
from packaging.version import Version
|
|
18
|
+
|
|
19
|
+
from .profile import Profile
|
|
20
|
+
|
|
21
|
+
INDEX = "https://pypi.org/simple/kitani-cli/"
|
|
22
|
+
CHECK_INTERVAL = 24 * 60 * 60
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def latest_release(files: list) -> Version | None:
|
|
26
|
+
python_version = platform.python_version()
|
|
27
|
+
latest = None
|
|
28
|
+
for file in files:
|
|
29
|
+
if not isinstance(file, dict) or file.get("yanked", False) is not False:
|
|
30
|
+
continue
|
|
31
|
+
filename = file.get("filename")
|
|
32
|
+
if not isinstance(filename, str):
|
|
33
|
+
continue
|
|
34
|
+
try:
|
|
35
|
+
if not SpecifierSet(file.get("requires-python") or "").contains(
|
|
36
|
+
python_version
|
|
37
|
+
):
|
|
38
|
+
continue
|
|
39
|
+
if filename.endswith(".whl"):
|
|
40
|
+
name, release, _, _ = parse_wheel_filename(filename)
|
|
41
|
+
else:
|
|
42
|
+
name, release = parse_sdist_filename(filename)
|
|
43
|
+
except (ValueError, InvalidSpecifier, TypeError):
|
|
44
|
+
continue
|
|
45
|
+
if (
|
|
46
|
+
name == "kitani-cli"
|
|
47
|
+
and not release.is_prerelease
|
|
48
|
+
and (latest is None or release > latest)
|
|
49
|
+
):
|
|
50
|
+
latest = release
|
|
51
|
+
return latest
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def upgrade_command() -> str:
|
|
55
|
+
pipx_metadata = Path(sys.prefix) / "pipx_metadata.json"
|
|
56
|
+
if pipx_metadata.is_file():
|
|
57
|
+
main_package = json.loads(pipx_metadata.read_text(encoding="utf-8"))[
|
|
58
|
+
"main_package"
|
|
59
|
+
]
|
|
60
|
+
spec = main_package.get("package_or_url", "kitani-cli")
|
|
61
|
+
if spec in ("kitani-cli", "kitani-cli[wallet]"):
|
|
62
|
+
return "pipx upgrade kitani-cli"
|
|
63
|
+
# pipx upgrade reuses its original source (including a Git URL or version pin).
|
|
64
|
+
wallet = "wallet" in (main_package.get("extras") or []) or "[wallet]" in spec
|
|
65
|
+
args = [
|
|
66
|
+
"pipx",
|
|
67
|
+
"install",
|
|
68
|
+
"--force",
|
|
69
|
+
"kitani-cli[wallet]" if wallet else "kitani-cli",
|
|
70
|
+
]
|
|
71
|
+
else:
|
|
72
|
+
args = [sys.executable, "-m", "pip", "install", "--upgrade", "kitani-cli"]
|
|
73
|
+
return subprocess.list2cmdline(args) if os.name == "nt" else shlex.join(args)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def notify_if_outdated(profile: Profile) -> None:
|
|
77
|
+
if (
|
|
78
|
+
not (sys.stdout.isatty() and sys.stderr.isatty())
|
|
79
|
+
or os.getenv("KITANI_NO_UPDATE_CHECK")
|
|
80
|
+
or os.getenv("CI")
|
|
81
|
+
):
|
|
82
|
+
return
|
|
83
|
+
try:
|
|
84
|
+
now = time.time()
|
|
85
|
+
cache = profile.get("pypi_update")
|
|
86
|
+
if (
|
|
87
|
+
isinstance(cache, dict)
|
|
88
|
+
and 0 <= now - cache.get("checked_at", 0) < CHECK_INTERVAL
|
|
89
|
+
):
|
|
90
|
+
latest = Version(cache["version"]) if cache.get("version") else None
|
|
91
|
+
else:
|
|
92
|
+
# Keep this client independent of the authenticated Kitani API client.
|
|
93
|
+
latest = None
|
|
94
|
+
try:
|
|
95
|
+
response = httpx.get(
|
|
96
|
+
INDEX,
|
|
97
|
+
headers={"Accept": "application/vnd.pypi.simple.v1+json"},
|
|
98
|
+
timeout=1.0,
|
|
99
|
+
)
|
|
100
|
+
response.raise_for_status()
|
|
101
|
+
metadata = response.json()
|
|
102
|
+
if isinstance(metadata, dict) and isinstance(
|
|
103
|
+
metadata.get("files"), list
|
|
104
|
+
):
|
|
105
|
+
latest = latest_release(metadata["files"])
|
|
106
|
+
except (httpx.HTTPError, ValueError):
|
|
107
|
+
pass
|
|
108
|
+
profile.update(
|
|
109
|
+
pypi_update={
|
|
110
|
+
"checked_at": now,
|
|
111
|
+
"version": str(latest) if latest else None,
|
|
112
|
+
}
|
|
113
|
+
)
|
|
114
|
+
installed = version("kitani-cli")
|
|
115
|
+
if latest and latest > Version(installed):
|
|
116
|
+
print(
|
|
117
|
+
f"Kitani CLI {latest} is available (installed {installed}). Upgrade with: {upgrade_command()}",
|
|
118
|
+
file=sys.stderr,
|
|
119
|
+
)
|
|
120
|
+
except (OSError, sqlite3.Error, KeyError, ValueError, TypeError):
|
|
121
|
+
# Update metadata is optional even if the cache is corrupt or read-only.
|
|
122
|
+
return
|