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 ADDED
@@ -0,0 +1,5 @@
1
+ """Kitani's Python client for inference, browser authorization and funding."""
2
+
3
+ from .client import Kitani, KitaniError
4
+
5
+ __all__ = ["Kitani", "KitaniError"]
kitani/cli.py ADDED
@@ -0,0 +1,624 @@
1
+ """Agent-first terminal entry point. Prompts and progress go to stderr."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import getpass
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import shutil
11
+ import sqlite3
12
+ import sys
13
+ import time
14
+ import webbrowser
15
+ from decimal import Decimal
16
+ from importlib.metadata import version
17
+ from pathlib import Path
18
+ from urllib.parse import urlsplit
19
+
20
+ from .client import Kitani, KitaniError
21
+ from .profile import Profile
22
+ from .updates import notify_if_outdated
23
+
24
+
25
+ def parser() -> argparse.ArgumentParser:
26
+ flags = argparse.ArgumentParser(add_help=False)
27
+ flags.add_argument(
28
+ "--json",
29
+ action="store_true",
30
+ default=argparse.SUPPRESS,
31
+ help="machine-readable output and errors",
32
+ )
33
+
34
+ def group(p):
35
+ return p.add_subparsers(dest="action" if p is root else "sub", required=True)
36
+
37
+ def cmd(parent, name, help):
38
+ return parent.add_parser(name, help=help, description=help, parents=[flags])
39
+
40
+ root = argparse.ArgumentParser(
41
+ prog="kitani",
42
+ description="Kitani inference and prepaid billing.",
43
+ parents=[flags],
44
+ )
45
+ root.add_argument(
46
+ "--version", action="version", version="%(prog)s " + version("kitani-cli")
47
+ )
48
+ actions = group(root)
49
+ signup = cmd(actions, "signup", "Authorize this CLI through the Kitani browser.")
50
+ signup.add_argument(
51
+ "--no-browser", action="store_true", help="return a URL for a human"
52
+ )
53
+ signup.add_argument(
54
+ "--resume", action="store_true", help="wait for the existing approval"
55
+ )
56
+ signup.add_argument("--name", help="label this terminal for later revocation")
57
+ doctor = cmd(
58
+ actions, "doctor", "Check executable, profile, credentials and active account."
59
+ )
60
+ doctor.add_argument(
61
+ "--offline", action="store_true", help="skip the account lookup"
62
+ )
63
+ usage = cmd(
64
+ actions, "usage", "Summarize token usage, spend and measured request times."
65
+ )
66
+ usage.add_argument("--since", default="30d")
67
+ usage.add_argument("--by", choices=["model", "key"], default="model")
68
+ requests = cmd(actions, "requests", "List recent account requests.")
69
+ requests.add_argument("--last", type=int, default=10)
70
+ requests.add_argument("--since")
71
+ requests.add_argument("--model")
72
+ requests.add_argument("--key", help="key record ID")
73
+ requests.add_argument("--cursor")
74
+ recovery = group(
75
+ cmd(actions, "recovery", "Manage recovery for an email-free account.")
76
+ )
77
+ cmd(recovery, "status", "Read verified recovery status.")
78
+ cmd(recovery, "add", "Email a verification code.").add_argument("email")
79
+ cmd(recovery, "verify", "Verify the code from your inbox.").add_argument(
80
+ "--stdin", action="store_true"
81
+ )
82
+ terminals = group(cmd(actions, "terminals", "Manage authorized terminals."))
83
+ cmd(terminals, "list", "List authorized terminal credentials.")
84
+ cmd(terminals, "revoke", "Remove a terminal’s access.").add_argument("id")
85
+ login = cmd(actions, "login", "Import an existing account fingerprint.")
86
+ login.add_argument(
87
+ "--stdin", action="store_true", help="read the secret from stdin"
88
+ )
89
+ cmd(actions, "logout", "Clear the saved local credentials.")
90
+ cmd(actions, "whoami", "Show the active account and available USD balance.")
91
+ cmd(actions, "balance", "Read the prepaid account balance.")
92
+ models = cmd(
93
+ actions, "models", "List model IDs or inspect one model’s capabilities."
94
+ )
95
+ models.add_argument("model_id", nargs="?", help="full publisher/model ID")
96
+ pricing = cmd(
97
+ actions,
98
+ "pricing",
99
+ "See model prices, context windows, and online miner counts.",
100
+ )
101
+ pricing.add_argument("model_id", nargs="?", help="optionally show a single model")
102
+ pricing.add_argument(
103
+ "--online", action="store_true", help="only models reporting online miners"
104
+ )
105
+ pricing.add_argument("--capability", help="e.g. tools or reasoning")
106
+ pricing.add_argument("--min-context", type=int, help="minimum context in tokens")
107
+ pricing.add_argument("--sort", choices=["input-price"])
108
+ keys = group(cmd(actions, "keys", "Manage this CLI’s credentials."))
109
+ cmd(keys, "list", "List key metadata, spend and budgets.")
110
+ new = cmd(keys, "create", "Create and save an inference key.")
111
+ new.add_argument("--name", required=True)
112
+ new.add_argument("--budget-usd", help="lifetime spend ceiling in USD")
113
+ budget = cmd(keys, "budget", "Update the lifetime budget of a CLI-issued key.")
114
+ budget.add_argument("id")
115
+ cap = budget.add_mutually_exclusive_group(required=True)
116
+ cap.add_argument("--usd")
117
+ cap.add_argument("--unlimited", action="store_true", help="remove the key's budget")
118
+ rotate = cmd(
119
+ keys,
120
+ "rotate",
121
+ "Replace a CLI key and save the replacement as the active inference key.",
122
+ )
123
+ rotate.add_argument("id")
124
+ rotate.add_argument(
125
+ "--current-fingerprint",
126
+ required=True,
127
+ help="the key record's short fingerprint from keys list",
128
+ )
129
+ revoke = cmd(keys, "revoke", "Revoke a CLI-created inference key by ID.")
130
+ revoke.add_argument("id")
131
+ export = cmd(
132
+ keys, "export", "Write a saved credential to stdout for backup or integration."
133
+ )
134
+ export.add_argument("kind", choices=["api-key", "fingerprint"])
135
+ chat = cmd(actions, "chat", "Send an inference request.")
136
+ chat.add_argument("--model")
137
+ chat.add_argument(
138
+ "--request-file", help="OpenAI-compatible JSON request file, or - for stdin"
139
+ )
140
+ chat.add_argument("prompt", nargs="?", help="or pipe the prompt on stdin")
141
+ chat.add_argument(
142
+ "--stream", action="store_true", help="stream text, or JSON lines with --json"
143
+ )
144
+ fund = group(cmd(actions, "fund", "Create, quote, and track prepaid top-ups."))
145
+ link = cmd(fund, "link", "Create a payer link bound to this account.")
146
+ link.add_argument("--usd", required=True)
147
+ link.add_argument("--via", choices=["paypal", "tao", "sn132"], required=True)
148
+ link.add_argument("--idempotency-key", help="reuse on retries of this top-up")
149
+ status = cmd(fund, "status", "Check a payment or wait for settlement.")
150
+ which_payment = status.add_mutually_exclusive_group(required=True)
151
+ which_payment.add_argument("id", nargs="?")
152
+ which_payment.add_argument("--last", action="store_true")
153
+ history = cmd(fund, "history", "List dashboard and terminal payments.")
154
+ history.add_argument("--last", type=int, default=20)
155
+ history.add_argument("--cursor")
156
+ status.add_argument("--wait", action="store_true")
157
+ status.add_argument(
158
+ "--timeout", type=int, default=180, help="maximum wait in seconds"
159
+ )
160
+ quote = cmd(fund, "quote", "Show the exact TAO or SN132 amount for a payment.")
161
+ quote.add_argument("id")
162
+ quote.add_argument("--sender", required=True, help="public coldkey address")
163
+ quote.add_argument("--hotkey", help="public staking hotkey for SN132")
164
+ pay = cmd(
165
+ fund, "pay", "Review and sign an existing crypto top-up with a local wallet."
166
+ )
167
+ pay.add_argument("id")
168
+ pay.add_argument("--wallet", required=True, help="local Bittensor wallet name")
169
+ pay.add_argument("--hotkey", help="public staking hotkey for SN132")
170
+ pay.add_argument(
171
+ "--max-units",
172
+ type=int,
173
+ help="maximum asset amount in base units for unattended signing",
174
+ )
175
+ pay.add_argument(
176
+ "--max-fee-rao",
177
+ type=int,
178
+ help="maximum estimated fee in RAO for unattended signing",
179
+ )
180
+ pay.add_argument(
181
+ "--yes",
182
+ action="store_true",
183
+ help="use explicit amount and fee limits instead of prompting",
184
+ )
185
+ return root
186
+
187
+
188
+ def print_pricing(snapshot: dict):
189
+ fields = ("id", "input", "output", "cache", "perImage", "context", "miners")
190
+ headers = ("Model", "Input", "Output", "Cached", "Per image", "Context", "Miners")
191
+ if any(row.get("p50_latency_ms") is not None for row in snapshot["rows"]):
192
+ fields += ("p50_latency_ms", "completion_tokens_per_elapsed_second")
193
+ headers += ("p50 ms", "Output tok/s")
194
+ rows = [
195
+ [str(row[key]) if row.get(key) is not None else "—" for key in fields]
196
+ for row in snapshot["rows"]
197
+ ]
198
+ table = [headers, *rows]
199
+ widths = [max(map(len, column)) for column in zip(*table)]
200
+ miners = snapshot.get("totalMiners")
201
+ print("USD per million tokens · image rates per image")
202
+ print(
203
+ f"Online miners across the network: {miners if miners is not None else 'unavailable'}"
204
+ )
205
+ for name, *values in table:
206
+ print(
207
+ " ".join(
208
+ [
209
+ name.ljust(widths[0]),
210
+ *(value.rjust(width) for value, width in zip(values, widths[1:])),
211
+ ]
212
+ )
213
+ )
214
+ if not rows:
215
+ print("No matching models.")
216
+
217
+
218
+ def output(obj, machine: bool):
219
+ """Keep JSON stable for scripts and put useful fields first in a terminal."""
220
+ if not machine and isinstance(obj, dict):
221
+ if "catalogAvailable" in obj and "rows" in obj:
222
+ print_pricing(obj)
223
+ return
224
+ if "payment_url" in obj:
225
+ dollars = Decimal(obj["amount_cents"]).scaleb(-2)
226
+ print(
227
+ f"Kitani top-up USD {dollars:.2f} {obj['method']} {obj['status']}"
228
+ )
229
+ print(obj["payment_url"])
230
+ print(f"Track with: kitani fund status {obj['id']} --wait")
231
+ return
232
+ if "verification_url" in obj:
233
+ print(
234
+ f"Open {obj['verification_url']} and confirm code {obj['user_code']}."
235
+ )
236
+ print(f"Return to this terminal and run: {obj['next']}")
237
+ return
238
+ if "balance_usd" in obj:
239
+ print(f"{obj['name']} {obj['id']}")
240
+ print(
241
+ f"Available credit USD {obj['balance_usd']:,.6f}".rstrip("0").rstrip(
242
+ "."
243
+ )
244
+ )
245
+ return
246
+ if obj.get("object") == "list" and isinstance(obj.get("data"), list):
247
+ for model in obj["data"]:
248
+ print(model["id"])
249
+ return
250
+ if isinstance(obj, str) and not machine:
251
+ print(obj)
252
+ else:
253
+ print(json.dumps(obj, ensure_ascii=False, indent=None if machine else 2))
254
+
255
+
256
+ def signup(args, client, profile):
257
+ if client.fingerprint:
258
+ raise ValueError(
259
+ "This CLI already has a fingerprint. Use whoami, or a separate KITANI_CONFIG_DIR."
260
+ )
261
+ grant = profile.get("pending")
262
+ if not grant or grant["deadline"] <= time.time():
263
+ if args.resume:
264
+ raise ValueError("No unexpired approval. Start kitani signup again.")
265
+ grant = client.start_signup(args.name) if args.name else client.start_signup()
266
+ grant["deadline"] = time.time() + grant["expires_in"]
267
+ profile.update(pending=grant)
268
+ url = grant["verification_uri_complete"]
269
+ parsed = urlsplit(url)
270
+ if (
271
+ parsed.scheme != "https"
272
+ or parsed.netloc != "kitani.ai"
273
+ or parsed.path != "/cli/authorize"
274
+ ):
275
+ raise KitaniError("Kitani returned an unexpected verification URL.")
276
+ public = {
277
+ "status": "pending",
278
+ "verification_url": url,
279
+ "user_code": grant["user_code"],
280
+ "expires_in": max(0, int(grant["deadline"] - time.time())),
281
+ "next": "kitani signup --resume --json",
282
+ }
283
+ if not args.resume:
284
+ if args.no_browser or not sys.stdin.isatty():
285
+ return public
286
+ print(f"Open {url} and confirm code {grant['user_code']}.", file=sys.stderr)
287
+ webbrowser.open(url)
288
+ delay = max(1, grant["interval"])
289
+ while time.time() < grant["deadline"]:
290
+ time.sleep(min(delay, max(0, grant["deadline"] - time.time())))
291
+ if time.time() >= grant["deadline"]:
292
+ break
293
+ try:
294
+ result = client.poll_signup(grant["device_code"])
295
+ except KitaniError as exc:
296
+ if exc.status != 429:
297
+ raise
298
+ delay = max(delay, int(exc.retry_after or 5))
299
+ continue
300
+ if result.get("status") == "approved":
301
+ profile.update(
302
+ fingerprint=result["fingerprint"], api_key=None, pending=None
303
+ )
304
+ return {
305
+ "status": "approved",
306
+ "account_id": result["account_id"],
307
+ "recovery_hint": "For an email-free account, run kitani recovery add EMAIL before funding.",
308
+ "next": "kitani keys create --name agent",
309
+ }
310
+ if result.get("status") != "pending":
311
+ raise KitaniError("Unexpected device authorization response.")
312
+ raise KitaniError(
313
+ "Browser approval expired. Start kitani signup again.", status=410
314
+ )
315
+
316
+
317
+ def execute(args, client, profile):
318
+ if args.action == "signup":
319
+ return signup(args, client, profile)
320
+ if args.action == "login":
321
+ if os.getenv("KITANI_FINGERPRINT"):
322
+ raise ValueError(
323
+ "Unset KITANI_FINGERPRINT before importing a local profile."
324
+ )
325
+ secret = (
326
+ sys.stdin.readline().strip()
327
+ if args.stdin
328
+ else getpass.getpass("Kitani fingerprint: ")
329
+ )
330
+ if not secret:
331
+ raise ValueError("A fingerprint is required.")
332
+ client.fingerprint = secret
333
+ account = client.account()
334
+ profile.update(
335
+ fingerprint=secret, api_key=None, pending=None, recovery_pending=None
336
+ )
337
+ return account
338
+ if args.action == "logout":
339
+ profile.update(
340
+ fingerprint=None,
341
+ api_key=None,
342
+ key_owner=None,
343
+ key_id=None,
344
+ pending=None,
345
+ recovery_pending=None,
346
+ )
347
+ return {"local_profile": "cleared"}
348
+ if args.action in ("whoami", "balance"):
349
+ return client.account()
350
+ if args.action == "doctor":
351
+ report = {
352
+ "version": version("kitani-cli"),
353
+ "python": sys.executable,
354
+ "invoked": str(Path(sys.argv[0]).resolve()),
355
+ "kitani_on_path": shutil.which("kitani"),
356
+ "profile": str(profile.path),
357
+ "fingerprint_source": "environment"
358
+ if os.getenv("KITANI_FINGERPRINT")
359
+ else "profile"
360
+ if client.fingerprint
361
+ else None,
362
+ "api_key_source": "environment"
363
+ if os.getenv("KITANI_API_KEY")
364
+ else "profile"
365
+ if client.api_key
366
+ else None,
367
+ "account_checked": False,
368
+ }
369
+ if client.fingerprint and not args.offline:
370
+ try:
371
+ account = client.account()
372
+ except KitaniError as exc:
373
+ report.update(
374
+ account_checked=True,
375
+ account_error={"http_status": exc.status, "message": str(exc)},
376
+ )
377
+ else:
378
+ report.update(
379
+ account_checked=True,
380
+ account_id=account["id"],
381
+ account_name=account.get("name"),
382
+ )
383
+ return report
384
+ if args.action == "usage":
385
+ return client.usage(since=args.since, group_by=args.by)
386
+ if args.action == "requests":
387
+ return client.requests(
388
+ limit=args.last,
389
+ since=args.since,
390
+ model=args.model,
391
+ key_id=args.key,
392
+ cursor=args.cursor,
393
+ )
394
+ if args.action == "terminals":
395
+ if args.sub == "list":
396
+ return client.terminals()
397
+ client.revoke_terminal(args.id)
398
+ return {"id": args.id, "revoked": True}
399
+ if args.action == "recovery":
400
+ if args.sub == "status":
401
+ return client.recovery_email()
402
+ if not client.fingerprint:
403
+ raise KitaniError("A fingerprint is required.", status=401)
404
+ owner = hashlib.sha256(client.fingerprint.encode()).hexdigest()
405
+ if args.sub == "add":
406
+ grant = client.add_recovery_email(args.email)
407
+ profile.update(
408
+ recovery_pending={
409
+ "owner": owner,
410
+ "token": grant["challenge_token"],
411
+ "expires": time.time() + grant["expires_in"],
412
+ }
413
+ )
414
+ return {"next": "kitani recovery verify", "expires_in": grant["expires_in"]}
415
+ pending = profile.get("recovery_pending")
416
+ if (
417
+ not pending
418
+ or pending["owner"] != owner
419
+ or pending["expires"] <= time.time()
420
+ ):
421
+ raise ValueError(
422
+ "Run kitani recovery add EMAIL with this fingerprint first."
423
+ )
424
+ code = (
425
+ sys.stdin.readline().strip()
426
+ if args.stdin
427
+ else getpass.getpass("Email verification code: ").strip()
428
+ )
429
+ result = client.verify_recovery_email(pending["token"], code)
430
+ profile.update(recovery_pending=None)
431
+ return result
432
+ if args.action == "models":
433
+ return client.model(args.model_id) if args.model_id else client.models()
434
+ if args.action == "pricing":
435
+ return client.pricing(
436
+ args.model_id,
437
+ online_only=args.online,
438
+ capability=args.capability,
439
+ min_context=args.min_context,
440
+ sort=args.sort,
441
+ )
442
+ if args.action == "keys":
443
+ return manage_keys(args, client, profile)
444
+ if args.action == "chat":
445
+ return chat(args, client)
446
+ return fund(args, client)
447
+
448
+
449
+ def manage_keys(args, client, profile):
450
+ if args.sub == "budget":
451
+ return client.set_key_budget(args.id, args.usd)
452
+ if args.sub == "list":
453
+ return client.keys()
454
+ if args.sub == "revoke":
455
+ client.revoke_key(args.id)
456
+ if profile.get("key_id") == args.id:
457
+ profile.update(api_key=None, key_id=None, key_owner=None)
458
+ return {"id": args.id, "status": "revoked"}
459
+ if args.sub == "export":
460
+ value = client.api_key if args.kind == "api-key" else client.fingerprint
461
+ if not value:
462
+ raise ValueError("No matching credential.")
463
+ return value
464
+ if args.sub == "rotate":
465
+ result = client.rotate_key(args.id, args.current_fingerprint)
466
+ else:
467
+ result = (
468
+ client.create_key(args.name, budget_usd=args.budget_usd)
469
+ if args.budget_usd is not None
470
+ else client.create_key(args.name)
471
+ )
472
+ profile.update(
473
+ api_key=result["api_key"],
474
+ key_id=result["api_key_record"]["id"],
475
+ key_owner=hashlib.sha256(client.fingerprint.encode()).hexdigest(),
476
+ )
477
+ return {"saved": True, "key": result["api_key_record"]}
478
+
479
+
480
+ def chat(args, client):
481
+ options = {}
482
+ structured = args.request_file is not None
483
+ if structured:
484
+ if args.prompt is not None:
485
+ raise ValueError("Choose either a prompt or --request-file.")
486
+ raw = (
487
+ sys.stdin.read()
488
+ if args.request_file == "-"
489
+ else Path(args.request_file).read_text(encoding="utf-8")
490
+ )
491
+ options = json.loads(raw)
492
+ if not isinstance(options, dict):
493
+ raise ValueError("The request must be a JSON object.")
494
+ model = options.pop("model", args.model)
495
+ if args.model is not None and args.model != model:
496
+ raise ValueError("The request file and --model specify different models.")
497
+ messages = options.pop("messages", None)
498
+ if (
499
+ not isinstance(messages, list)
500
+ or not messages
501
+ or not all(isinstance(item, dict) for item in messages)
502
+ ):
503
+ raise ValueError(
504
+ "The request must include a nonempty messages array of objects."
505
+ )
506
+ stream = options.pop("stream", False)
507
+ if not isinstance(stream, bool):
508
+ raise ValueError("stream must be a boolean.")
509
+ else:
510
+ prompt = args.prompt
511
+ if prompt is None and not sys.stdin.isatty():
512
+ prompt = sys.stdin.read()
513
+ if not prompt:
514
+ raise ValueError("Supply a prompt or pipe it on stdin.")
515
+ messages = [{"role": "user", "content": prompt}]
516
+ model = args.model
517
+ stream = False
518
+ if not isinstance(model, str) or not model.strip():
519
+ raise ValueError("Specify a model in the request or with --model.")
520
+ if args.stream or stream:
521
+ for chunk in client.stream_chat(model, messages, **options):
522
+ if args.json or structured:
523
+ print(json.dumps(chunk, ensure_ascii=False), flush=True)
524
+ else:
525
+ for choice in chunk.get("choices", []):
526
+ print(
527
+ choice.get("delta", {}).get("content") or "", end="", flush=True
528
+ )
529
+ if not (args.json or structured):
530
+ print()
531
+ return None
532
+ result = client.chat(model, messages, **options)
533
+ return (
534
+ result
535
+ if args.json or structured
536
+ else result["choices"][0]["message"]["content"]
537
+ )
538
+
539
+
540
+ def fund(args, client):
541
+ if args.sub == "history":
542
+ return client.payment_history(limit=args.last, cursor=args.cursor)
543
+ if args.sub == "link":
544
+ print(
545
+ "Using an email-free account? Set up recovery with kitani recovery add EMAIL before funding.",
546
+ file=sys.stderr,
547
+ )
548
+ key = args.idempotency_key or client.new_idempotency_key()
549
+ print(f"Top-up request key: {key}", file=sys.stderr)
550
+ method = "alpha" if args.via == "sn132" else args.via
551
+ return {
552
+ **client.payment_link(args.usd, method, idempotency_key=key),
553
+ "idempotency_key": key,
554
+ }
555
+ if args.sub == "quote":
556
+ return client.quote(args.id, args.sender, hotkey=args.hotkey)
557
+ if args.sub == "pay":
558
+ from .wallet import pay
559
+
560
+ return pay(client, args)
561
+ payment_id = args.id
562
+ if args.last:
563
+ items = client.payment_history(limit=1)["items"]
564
+ if not items:
565
+ return {"status": "no_payments"}
566
+ payment_id = items[0]["id"]
567
+ deadline = time.monotonic() + args.timeout
568
+ while True:
569
+ result = client.payment(payment_id)
570
+ if (
571
+ result["status"]
572
+ in {"paid", "failed", "expired", "refunded", "partially_refunded"}
573
+ or not args.wait
574
+ ):
575
+ return result
576
+ remaining = deadline - time.monotonic()
577
+ if remaining <= 0:
578
+ raise KitaniError(
579
+ f"Payment {payment_id} is {result['status']}. Resume with fund status {payment_id}.",
580
+ status=408,
581
+ )
582
+ time.sleep(min(5, remaining))
583
+
584
+
585
+ def error_exit_code(status: int | None) -> int:
586
+ return {401: 3, 403: 3, 402: 4, 429: 5, 408: 6}.get(status, 1)
587
+
588
+
589
+ def main(argv=None) -> int:
590
+ args = parser().parse_args(argv)
591
+ args.json = getattr(args, "json", False)
592
+ try:
593
+ profile = Profile()
594
+ fp = os.environ.get("KITANI_FINGERPRINT") or profile.get("fingerprint")
595
+ key = os.environ.get("KITANI_API_KEY") or (
596
+ profile.get("api_key")
597
+ if fp
598
+ and profile.get("key_owner") == hashlib.sha256(fp.encode()).hexdigest()
599
+ else None
600
+ )
601
+ with Kitani(fingerprint=fp, api_key=key) as client:
602
+ result = execute(args, client, profile)
603
+ if result is not None:
604
+ output(result, args.json)
605
+ if not (args.json or getattr(args, "offline", False)):
606
+ notify_if_outdated(profile)
607
+ if args.action == "doctor" and result.get("account_error"):
608
+ return error_exit_code(result["account_error"]["http_status"])
609
+ return 0
610
+ except (KitaniError, ValueError, OSError, sqlite3.Error) as exc:
611
+ status = getattr(exc, "status", None)
612
+ err = {
613
+ "error": str(exc),
614
+ "http_status": status,
615
+ "retry_after": getattr(exc, "retry_after", None),
616
+ }
617
+ print(json.dumps(err) if args.json else str(exc), file=sys.stderr)
618
+ return error_exit_code(status)
619
+ except KeyboardInterrupt:
620
+ return 130
621
+
622
+
623
+ if __name__ == "__main__":
624
+ raise SystemExit(main())