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/wallet.py ADDED
@@ -0,0 +1,192 @@
1
+ """Optional local wallet integration. Import chain libraries only for terminal payments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import sys
7
+ from contextlib import contextmanager
8
+ from decimal import Decimal
9
+ from functools import partial
10
+
11
+ from .client import KitaniError
12
+
13
+ GENESIS = "0x2f0555cc76fc2840a25a6ea3b9637146806f1f44b090c175ffde2a7e5ab36c03"
14
+ TREASURY = "5CSEvx7KDfj47iSkwQoNVaT1WWkfw3uDmJgmNZZsAMQaJpgs"
15
+ RPC = "https://entrypoint-finney.opentensor.ai"
16
+
17
+
18
+ @contextmanager
19
+ def finney():
20
+ from substrateinterface import SubstrateInterface
21
+
22
+ # HTTPS avoids downloading the complete runtime metadata in a single WS frame.
23
+ chain = SubstrateInterface(url=RPC, ss58_format=42, auto_discover=False)
24
+ session = chain.transport.session
25
+ session.request = partial(session.request, timeout=(10, 60))
26
+ try:
27
+ yield chain
28
+ finally:
29
+ session.close()
30
+ chain.close()
31
+
32
+
33
+ def verified_payment(
34
+ chain, quote: dict, sender: str, asset: str, hotkey: str | None
35
+ ) -> tuple[bytes, int]:
36
+ """Independently encode the two permitted calls using Finney runtime metadata."""
37
+ from substrateinterface import Keypair
38
+
39
+ p = quote["payload"]
40
+ if (
41
+ quote["receiver"] != TREASURY
42
+ or quote["genesis"] != GENESIS
43
+ or quote["netuid"] != 132
44
+ or p["genesisHash"] != GENESIS
45
+ or chain.get_block_hash(0) != GENESIS
46
+ or p["address"] != sender
47
+ or quote["sender"] != sender
48
+ or quote["asset"] != asset
49
+ or not re.fullmatch(r"deposit_bt_[A-Za-z0-9_-]{1,64}", quote["id"])
50
+ or not 0 < int(quote["units"]) < 2**63
51
+ or p["version"] != 4
52
+ or int(p["tip"], 16) != 0
53
+ ):
54
+ raise ValueError(
55
+ "The quote does not match this wallet, asset, network, or Kitani recipient."
56
+ )
57
+ block = int(p["blockNumber"], 16)
58
+ block_hash = chain.get_block_hash(block)
59
+ if block_hash != p["blockHash"]:
60
+ raise ValueError("Quote block differs from Finney.")
61
+ memo = chain.compose_call(
62
+ "System",
63
+ "remark_with_event",
64
+ {"remark": "0x" + quote["id"].encode().hex()},
65
+ block_hash,
66
+ )
67
+ if asset == "tao":
68
+ transfer = chain.compose_call(
69
+ "Balances",
70
+ "transfer_keep_alive",
71
+ {"dest": TREASURY, "value": int(quote["units"])},
72
+ block_hash,
73
+ )
74
+ elif asset == "alpha" and hotkey and quote["hotkey"] == hotkey:
75
+ transfer = chain.compose_call(
76
+ "SubtensorModule",
77
+ "transfer_stake",
78
+ {
79
+ "destination_coldkey": TREASURY,
80
+ "hotkey": hotkey,
81
+ "origin_netuid": 132,
82
+ "destination_netuid": 132,
83
+ "alpha_amount": int(quote["units"]),
84
+ },
85
+ block_hash,
86
+ )
87
+ else:
88
+ raise ValueError(
89
+ "SN132 payments require the hotkey holding the sender’s stake."
90
+ )
91
+ batch = chain.compose_call(
92
+ "Utility", "batch_all", {"calls": [memo, transfer]}, block_hash
93
+ )
94
+ if str(batch.data) != p["method"]:
95
+ raise ValueError("Quoted calls differ from the expected Kitani deposit.")
96
+ # The service uses a 32-block mortal transaction and zero tip. Never sign an
97
+ # opaque blob supplied by the service. Refuse new runtime layouts on mismatch.
98
+ expected = bytes(
99
+ chain.generate_signature_payload(
100
+ batch,
101
+ era={"period": 32, "current": block},
102
+ nonce=int(p["nonce"], 16),
103
+ tip=0,
104
+ ).data
105
+ )
106
+ if "0x" + expected.hex() != quote["signing_bytes"]:
107
+ raise ValueError(
108
+ "Signing bytes do not match the locally reconstructed payment."
109
+ )
110
+ # A zero-filled signature is sufficient for the read-only payment_queryInfo RPC.
111
+ # Estimate the same call, nonce and mortality that the wallet will sign.
112
+ unsigned = chain.create_signed_extrinsic(
113
+ call=batch,
114
+ keypair=Keypair(ss58_address=sender),
115
+ nonce=int(p["nonce"], 16),
116
+ era={"period": 32, "current": block},
117
+ tip=0,
118
+ signature=bytes(64),
119
+ )
120
+ info = chain.rpc_request("payment_queryInfo", [str(unsigned.data), block_hash])[
121
+ "result"
122
+ ]
123
+ fee = int(info["partialFee"])
124
+ if fee < 0:
125
+ raise ValueError("Finney returned an invalid fee estimate.")
126
+ return expected, fee
127
+
128
+
129
+ def pay(client, args):
130
+ try:
131
+ from bittensor_wallet import Wallet
132
+ except ImportError as exc:
133
+ raise ValueError(
134
+ "Terminal signing requires the optional kitani-cli[wallet] dependencies."
135
+ ) from exc
136
+ if args.yes and (args.max_units is None or args.max_fee_rao is None):
137
+ raise ValueError("Unattended signing requires --max-units and --max-fee-rao.")
138
+ if not args.yes and not sys.stdin.isatty():
139
+ raise ValueError(
140
+ "Use an interactive terminal or specify --yes and both spending limits."
141
+ )
142
+ payment = client.payment(args.id)
143
+ if payment["status"] not in ("pending", "quoted"):
144
+ return payment
145
+ asset = payment["method"]
146
+ if asset not in ("tao", "alpha") or (asset == "alpha" and not args.hotkey):
147
+ raise ValueError(
148
+ "Choose a TAO payment or supply --hotkey for an SN132 payment."
149
+ )
150
+ try:
151
+ wallet = Wallet(name=args.wallet)
152
+ sender = wallet.coldkeypub.ss58_address
153
+ quote = client.quote(args.id, sender, hotkey=args.hotkey)
154
+ if quote["cents"] != payment["amount_cents"]:
155
+ raise ValueError("Quote USD value differs from the payment.")
156
+ units, fee = int(quote["units"]), int(quote["fee"])
157
+ if (
158
+ fee < 0
159
+ or (args.max_units is not None and units > args.max_units)
160
+ or (args.max_fee_rao is not None and fee > args.max_fee_rao)
161
+ ):
162
+ raise ValueError("The quote exceeds your amount or fee limit.")
163
+ with finney() as chain:
164
+ payload, network_fee = verified_payment(
165
+ chain, quote, sender, asset, args.hotkey
166
+ )
167
+ fee = max(fee, network_fee)
168
+ if args.max_fee_rao is not None and fee > args.max_fee_rao:
169
+ raise ValueError(
170
+ "The independently estimated network fee exceeds your fee limit."
171
+ )
172
+ symbol = "TAO" if asset == "tao" else "SN132 ⴵ"
173
+ print(
174
+ f"Pay {Decimal(units).scaleb(-9):f} {symbol} for USD {Decimal(quote['cents']).scaleb(-2):.2f}"
175
+ f"\nFrom {sender}\nTo {TREASURY}\nEstimated fee {Decimal(fee).scaleb(-9):f} TAO",
176
+ file=sys.stderr,
177
+ )
178
+ if not args.yes:
179
+ print("Sign this payment? [y/N] ", end="", file=sys.stderr, flush=True)
180
+ if input().strip().lower() not in {"y", "yes"}:
181
+ return {"id": args.id, "status": "unsigned"}
182
+ signer = wallet.coldkey
183
+ if signer.ss58_address != sender or signer.crypto_type not in (0, 1):
184
+ raise ValueError("Select a matching ed25519 or sr25519 coldkey.")
185
+ signature = "0x" + (bytes([signer.crypto_type]) + signer.sign(payload)).hex()
186
+ except (ValueError, KitaniError):
187
+ raise
188
+ except Exception as exc:
189
+ raise KitaniError(
190
+ "Could not prepare or sign the payment. Check your local wallet and Finney connection."
191
+ ) from exc
192
+ return {"id": args.id, **client.submit(args.id, quote["id"], signature)}
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.5
2
+ Name: kitani-cli
3
+ Version: 0.2.0
4
+ Summary: Python SDK and agent-first CLI for Kitani inference and prepaid billing
5
+ Project-URL: Repository, https://github.com/kitani-inc/kitani-cli
6
+ Project-URL: Documentation, https://kitani.ai/agents
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: httpx<1,>=0.27
9
+ Requires-Dist: packaging>=24
10
+ Provides-Extra: test
11
+ Requires-Dist: pytest<10,>=8; extra == 'test'
12
+ Provides-Extra: wallet
13
+ Requires-Dist: bittensor-wallet<5,>=4; extra == 'wallet'
14
+ Requires-Dist: substrate-interface<2,>=1.7; extra == 'wallet'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # Kitani CLI and Python SDK
18
+
19
+ Authorize a Kitani account, fund its prepaid balance, and run inference from a terminal. Commands work interactively or emit JSON for agent runners. The Python client reuses HTTP connections and streams model output without buffering the entire response.
20
+
21
+ [Agents](https://kitani.ai/agents) · [Agent skill](https://github.com/kitani-inc/kitani-cli/blob/main/skills/kitani/SKILL.md) · [API documentation](https://kitani.ai/docs/agents)
22
+
23
+ ## Install
24
+
25
+ Requires Python 3.10 or later. Install the released CLI from PyPI with pipx:
26
+
27
+ ```sh
28
+ pipx install kitani-cli
29
+ kitani --version
30
+ ```
31
+
32
+ For the Python SDK, run `python -m pip install kitani-cli` in your virtual environment. For local wallet signing, install `'kitani-cli[wallet]'`. To install the development version from source, run `pipx install 'git+https://github.com/kitani-inc/kitani-cli.git'` or `pipx install .` from a clone.
33
+
34
+ Interactive commands check PyPI at most once per day per profile and print the upgrade command to stderr when a newer stable release supports your Python version. For a standard pipx install, run `pipx upgrade kitani-cli`. JSON output, redirected streams, CI, and `doctor --offline` skip the check. Set `KITANI_NO_UPDATE_CHECK=1` to disable it.
35
+
36
+ ## First inference request
37
+
38
+ 1. Run `kitani signup`. Confirm the displayed code on kitani.ai, choose a new fingerprint-only account or sign into an existing account, and complete Turnstile. For SSH or CI, run `kitani signup --no-browser --json`, give the verification URL and code to the person approving, then run `kitani signup --resume` in the original profile. Approval expires after ten minutes.
39
+ 2. Run `kitani whoami` and `kitani keys create --name agent`. The CLI saves the inference key. Preserve the fingerprint for an email-less account in a password manager. Use `kitani keys export fingerprint` in a private terminal or pipe its output into your secret store.
40
+ 3. Run `kitani fund link --via paypal --usd 10 --json`. Share the returned `payment_url` with the payer. Check the credit with `kitani fund status PAYMENT_ID --wait`.
41
+ 4. Run `kitani models --json`, then `kitani chat --model MODEL_ID "Hello from Kitani"` with an available model ID. Add `--stream` for incremental text or `--stream --json` for newline-delimited JSON.
42
+
43
+ ## Model catalog and pricing
44
+
45
+ ```sh
46
+ kitani models # list model IDs
47
+ kitani models qwen/qwen3.8-27b-uncensored --json
48
+ kitani pricing --online # rates and reported online miners
49
+ kitani pricing qwen/qwen3.8-27b-uncensored --json
50
+ ```
51
+
52
+ Pricing comes from the same public snapshot as the website. Input, output and cached prices are USD per million tokens. Image rates are USD per image. The network total counts unique online miners; a miner may serve several models. Missing coverage is shown as unavailable. In Python, use `api.model(model_id)` for detailed capabilities and `api.pricing(model_id, online_only=False)` for pricing and miner counts. Omit the ID for the full pricing table.
53
+
54
+ ## Python
55
+
56
+ Supply `KITANI_API_KEY` for inference and `KITANI_FINGERPRINT` for account or billing operations. The SDK reads environment variables or constructor arguments. The CLI profile is private to the CLI.
57
+
58
+ ```python
59
+ from kitani import Kitani
60
+
61
+ with Kitani() as api:
62
+ catalog = api.models()
63
+ model_id = catalog["data"][0]["id"] # Choose an available model for your request.
64
+ for chunk in api.stream_chat(model_id, [{"role": "user", "content": "Hello"}]):
65
+ for choice in chunk.get("choices", []):
66
+ print(choice["delta"].get("content") or "", end="", flush=True)
67
+ ```
68
+
69
+ For headless signup, call `start_signup()`, share only `verification_uri_complete` and `user_code`, then call `poll_signup(device_code)` at the returned interval. Store the approved fingerprint as a secret. Use `create_key(name)` to mint an inference credential and `revoke_key(id)` to retire a CLI-issued key.
70
+
71
+ ```python
72
+ from kitani import Kitani
73
+
74
+ with Kitani() as api:
75
+ request_key = api.new_idempotency_key()
76
+ # Persist request_key with your top-up record before sending the request.
77
+ checkout = api.payment_link("10.00", "paypal", idempotency_key=request_key)
78
+ print(checkout["payment_url"])
79
+ print(api.payment(checkout["id"])["status"])
80
+ ```
81
+
82
+ ## Crypto checkout
83
+
84
+ Use `--via tao` or `--via sn132` with `fund link` for Kitani-hosted wallet checkout. The payer connects their extension on the checkout page. To quote and sign in a terminal:
85
+
86
+ ```sh
87
+ kitani fund link --usd 10 --via tao --json
88
+ kitani fund quote PAYMENT_ID --sender PUBLIC_COLDKEY --json
89
+ kitani fund pay PAYMENT_ID --wallet WALLET_NAME
90
+ kitani fund status PAYMENT_ID --wait
91
+ ```
92
+
93
+ For SN132 ⴵ, supply `--hotkey STAKING_HOTKEY_ADDRESS` to both quote and pay. Use the same sending coldkey for that link. The quote includes the sender-specific invoice, exact amount, estimated TAO fee, recipient, and block expiry. A plain transfer to the recipient lacks the invoice and may never credit the account. See the [agent skill](https://github.com/kitani-inc/kitani-cli/blob/main/skills/kitani/SKILL.md) for limits, unattended signing and interrupted payments.
94
+
95
+ ## Credentials and output
96
+
97
+ | Credential | Purpose |
98
+ | --- | --- |
99
+ | Fingerprint | Account and payment management, minting and revoking CLI inference keys |
100
+ | Inference key | Authenticated inference against prepaid credit |
101
+ | Verification URL and user code | Share with the person authorizing this terminal |
102
+ | Payment URL | Share with a payer for one account, amount and payment method |
103
+
104
+ The CLI stores a plaintext SQLite profile in `~/.config/kitani` with owner-only file permissions on POSIX systems. Use `KITANI_CONFIG_DIR` to isolate runners, and secret injection on shared machines. Environment credentials take precedence. A saved inference key is bound to its profile fingerprint. Use `kitani login --stdin` to import a fingerprint from a pipe. `kitani logout` clears the local profile. Back up a fingerprint-only account before discarding its last credential.
105
+
106
+ Add `--json` to any command. Results go to stdout, diagnostics to stderr. Exit codes are 0 for completion, 1 for other failures, 2 for invalid syntax, 3 for authentication or permission failures, 4 for insufficient credit, 5 for rate limiting, 6 for a wait timeout, and 130 for interruption. A successful status query can report a failed payment. Inspect the status field before treating the invoice as paid.
107
+
108
+ ## Development
109
+
110
+ ```sh
111
+ python -m pip install -e '.[test]'
112
+ python -m pytest
113
+ ```
114
+
115
+ The canonical agent instructions are in `skills/kitani/SKILL.md`. The website serves a copy at `/agents/skill.md`. Update the mirror when changing the workflow.
116
+
117
+ ## Run and monitor an agent
118
+
119
+ | Task | Terminal |
120
+ | --- | --- |
121
+ | Find online models with tool calling | `kitani pricing --online --capability tools --min-context 128000 --sort input-price` |
122
+ | Create a budgeted key and inspect spend | `kitani keys create --name worker --budget-usd 5.00`, then `kitani keys list` |
123
+ | Rotate a CLI-issued secret, keeping its budget and usage history | `kitani keys rotate KEY_ID --current-fingerprint SHORT_FINGERPRINT` (from `keys list`) |
124
+ | Change an existing CLI key’s lifetime ceiling | `kitani keys budget KEY_ID --usd 10.00` (or explicitly pass `--unlimited`) |
125
+ | Read seven days of spend | `kitani usage --since 7d --by model --json` or `--by key` |
126
+ | Investigate individual requests | `kitani requests --last 10 --key KEY_ID --since 24h --json` |
127
+ | Track deposits across the dashboard and CLI | `kitani fund history --json` and `kitani fund status --last --wait` |
128
+ | Check which executable and credentials are active | `python -m kitani.cli doctor --json` in the SDK environment |
129
+ | Name and manage authorized devices | `kitani signup --name build-runner`, `kitani terminals list`, `kitani terminals revoke ID` |
130
+
131
+ Pass a complete chat payload with `kitani chat --request-file request.json --json`. Use `--request-file -` to read JSON from stdin. Include the model ID, messages and any model-supported options such as tools, tool choice or response format. A streaming request produces newline-delimited chunk objects, including tool-call deltas. The Python equivalents are `api.chat(model, messages, **options)` and `api.stream_chat(model, messages, **options)`.
132
+
133
+ For an email-free account, run `kitani recovery add EMAIL` and then `kitani recovery verify` while you still have the fingerprint. If you lose access, open Kitani’s [account recovery page](https://kitani.ai/cli/recover), complete Turnstile and verify the emailed code, then authorize your new terminal against that account. Check other terminals from dashboard settings or with `kitani terminals list`.
134
+
135
+ ## Release to PyPI
136
+
137
+ 1. Sign in to [PyPI Publishing](https://pypi.org/manage/account/publishing/) and add a pending **GitHub** publisher using these exact values.
138
+
139
+ | Field | Value |
140
+ | --- | --- |
141
+ | PyPI project name | `kitani-cli` |
142
+ | GitHub owner | `kitani-inc` |
143
+ | Repository | `kitani-cli` |
144
+ | Workflow filename | `release.yml` |
145
+ | Environment | `pypi` |
146
+
147
+ 2. Push the release commit on `main`. In [GitHub Releases](https://github.com/kitani-inc/kitani-cli/releases/new), create the tag matching the version in `pyproject.toml` (currently `v0.2.0`), target that commit, and select **Publish release**. The workflow runs when a release is published.
148
+ 3. Check the [publishing workflow](https://github.com/kitani-inc/kitani-cli/actions/workflows/release.yml). It runs tests, builds the wheel and source distribution, verifies the tag against the wheel metadata, and publishes with GitHub’s short-lived identity. After it succeeds, verify the version on [PyPI](https://pypi.org/project/kitani-cli/) and try `pipx run --no-cache --spec kitani-cli kitani --version`.
149
+ 4. For later releases, increment the version in `pyproject.toml`, push the commit, and publish the matching GitHub release. The verified publisher carries over. The README in the tagged commit supplies the PyPI description for that release.
@@ -0,0 +1,11 @@
1
+ kitani/__init__.py,sha256=LeCkMnhY4pAoFaxKlovm3_TTkLETg3gePOPL7io2r4M,157
2
+ kitani/cli.py,sha256=0rcm6Y4XW_4b90xGlyWArW3BqnX6I1QW1uREuqOC6Bc,24158
3
+ kitani/client.py,sha256=ItNnfSwkdJmHidNj1WulV5xq8The3q7D_Cg1oOu1c-k,18005
4
+ kitani/profile.py,sha256=dTjERkguqqlYXeaVR0KGg6Kzcx7aUZ_t0kaA6DI36Yo,2576
5
+ kitani/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ kitani/updates.py,sha256=_NRa4DeCyMMxGSmY_UDuTDCPRYIg5RZkaXoSykjRJWU,4236
7
+ kitani/wallet.py,sha256=5dSa3ztdpj4kIQwjPApog0-45lXeezYoFEvOImcyOBA,7402
8
+ kitani_cli-0.2.0.dist-info/METADATA,sha256=HZctrAD5Ia1V4ARXQKjl0go3Ngs9xBv61lMula3mr38,10598
9
+ kitani_cli-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ kitani_cli-0.2.0.dist-info/entry_points.txt,sha256=DHNbl0k0nrqWwpwscuJR2Az5jCquVQJXFK7WdYQoQdQ,43
11
+ kitani_cli-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ kitani = kitani.cli:main