zcode-cli-usage 0.1.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.
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Read Z.ai Coding Plan quotas using an existing API key."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import shlex
|
|
9
|
+
import signal
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
import time
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.request
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from importlib.metadata import version
|
|
17
|
+
|
|
18
|
+
API_URL = "https://api.z.ai/api/monitor/usage/quota/limit"
|
|
19
|
+
INTERVAL = 300
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def config_path():
|
|
23
|
+
return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "zcode-cli-usage/config.json"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def cache_path():
|
|
27
|
+
return Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "zcode-cli-usage/usage.json"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def read_json(path):
|
|
31
|
+
try:
|
|
32
|
+
data = json.loads(path.read_text())
|
|
33
|
+
return data if isinstance(data, dict) else None
|
|
34
|
+
except (OSError, ValueError):
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def atomic_json(path, data):
|
|
39
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
fd, name = tempfile.mkstemp(prefix=".usage-", dir=path.parent)
|
|
41
|
+
try:
|
|
42
|
+
with os.fdopen(fd, "w") as stream:
|
|
43
|
+
json.dump(data, stream, indent=2)
|
|
44
|
+
stream.write("\n")
|
|
45
|
+
os.replace(name, path)
|
|
46
|
+
finally:
|
|
47
|
+
Path(name).unlink(missing_ok=True)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def get_api_key(env_file=None):
|
|
51
|
+
key = os.environ.get("ZAI_API_KEY", "").strip()
|
|
52
|
+
if key:
|
|
53
|
+
return key
|
|
54
|
+
source = env_file or os.environ.get("ZCODE_USAGE_ENV_FILE") or (read_json(config_path()) or {}).get("env_file")
|
|
55
|
+
if source:
|
|
56
|
+
try:
|
|
57
|
+
for line in Path(source).expanduser().read_text().splitlines():
|
|
58
|
+
name, sep, value = line.strip().removeprefix("export ").partition("=")
|
|
59
|
+
if sep and name.strip() == "ZAI_API_KEY":
|
|
60
|
+
parts = shlex.split(value, comments=True)
|
|
61
|
+
if len(parts) == 1 and parts[0].strip():
|
|
62
|
+
return parts[0].strip()
|
|
63
|
+
raise ValueError("Invalid ZAI_API_KEY assignment")
|
|
64
|
+
except (OSError, ValueError):
|
|
65
|
+
raise RuntimeError("Could not read ZAI_API_KEY from the configured env file") from None
|
|
66
|
+
raise RuntimeError("Set ZAI_API_KEY or configure an env file with zcode-cli-usage configure --env-file PATH")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def number(value):
|
|
70
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0:
|
|
71
|
+
raise ValueError("Invalid quota response: expected a nonnegative finite number")
|
|
72
|
+
return value
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def normalize(payload):
|
|
76
|
+
if not isinstance(payload, dict) or payload.get("code") != 200 or payload.get("success") is not True:
|
|
77
|
+
raise ValueError("Usage API reported an unsuccessful response")
|
|
78
|
+
data = payload.get("data")
|
|
79
|
+
if not isinstance(data, dict) or not isinstance(data.get("limits"), list) or not data["limits"]:
|
|
80
|
+
raise ValueError("Invalid quota response: missing limits")
|
|
81
|
+
limits = []
|
|
82
|
+
for item in data["limits"]:
|
|
83
|
+
if not isinstance(item, dict) or not isinstance(item.get("type"), str):
|
|
84
|
+
raise ValueError("Invalid quota response: missing quota type")
|
|
85
|
+
unit = number(item.get("unit"))
|
|
86
|
+
count = number(item.get("number"))
|
|
87
|
+
reset = item.get("nextResetTime")
|
|
88
|
+
limits.append({
|
|
89
|
+
"type": item["type"], "unit": unit, "number": count,
|
|
90
|
+
"used": number(item.get("currentValue")),
|
|
91
|
+
"limit": number(item.get("usage")),
|
|
92
|
+
"remaining": number(item.get("remaining")),
|
|
93
|
+
"pct": number(item.get("percentage")),
|
|
94
|
+
"resets_at": datetime.fromtimestamp(number(reset) / 1000, timezone.utc).isoformat() if reset is not None else None,
|
|
95
|
+
})
|
|
96
|
+
return {"plan": data.get("level", "unknown"), "source": "api", "updated_at": datetime.now(timezone.utc).isoformat(), "limits": limits}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def fetch_usage(env_file=None):
|
|
100
|
+
request = urllib.request.Request(API_URL, headers={"Authorization": "Bearer " + get_api_key(env_file), "Accept": "application/json"})
|
|
101
|
+
try:
|
|
102
|
+
with urllib.request.urlopen(request, timeout=15) as response:
|
|
103
|
+
return normalize(json.load(response))
|
|
104
|
+
except urllib.error.HTTPError as exc:
|
|
105
|
+
# Never include response bodies or request headers in diagnostics.
|
|
106
|
+
raise RuntimeError(f"Usage request failed (HTTP {exc.code})") from None
|
|
107
|
+
except urllib.error.URLError:
|
|
108
|
+
raise RuntimeError("Could not connect to the usage API") from None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def load_usage(env_file=None, cached=False):
|
|
112
|
+
previous = read_json(cache_path())
|
|
113
|
+
if cached and previous:
|
|
114
|
+
try:
|
|
115
|
+
age = (datetime.now(timezone.utc) - datetime.fromisoformat(previous["updated_at"])).total_seconds()
|
|
116
|
+
if 0 <= age < INTERVAL:
|
|
117
|
+
return previous
|
|
118
|
+
except (KeyError, TypeError, ValueError):
|
|
119
|
+
pass
|
|
120
|
+
try:
|
|
121
|
+
data = fetch_usage(env_file)
|
|
122
|
+
except (RuntimeError, ValueError, OverflowError):
|
|
123
|
+
if not previous:
|
|
124
|
+
raise
|
|
125
|
+
return {**previous, "stale": True}
|
|
126
|
+
atomic_json(cache_path(), data)
|
|
127
|
+
return data
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def label(item):
|
|
131
|
+
if item["unit"] == 3:
|
|
132
|
+
return f"{item['number']:g}-hour"
|
|
133
|
+
if item["unit"] == 6 and item["number"] == 1:
|
|
134
|
+
return "Weekly"
|
|
135
|
+
return f"{item['type']} (unit {item['unit']:g}, number {item['number']:g})"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def display(data, compact=False):
|
|
139
|
+
parts = []
|
|
140
|
+
for item in data["limits"]:
|
|
141
|
+
suffix = " credits" if item["type"] == "CREDIT_LIMIT" else f" {item['type']}"
|
|
142
|
+
text = f"{label(item)}: {item['pct']:g}% ({item['used']:g}/{item['limit']:g}{suffix})"
|
|
143
|
+
if item["resets_at"]:
|
|
144
|
+
reset = datetime.fromisoformat(item["resets_at"]).astimezone()
|
|
145
|
+
text += f" resets {reset:%Y-%m-%d %H:%M %Z}"
|
|
146
|
+
parts.append(text)
|
|
147
|
+
if data.get("stale"):
|
|
148
|
+
parts.append(f"Cached, live fetch failed; updated {data['updated_at']}")
|
|
149
|
+
print(" | ".join(parts) if compact else f"Plan: {data['plan']}\n" + "\n".join(parts))
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def positive_interval(value):
|
|
153
|
+
result = int(value)
|
|
154
|
+
if result <= 0:
|
|
155
|
+
raise argparse.ArgumentTypeError("interval must be positive")
|
|
156
|
+
return result
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def main():
|
|
160
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
161
|
+
parser.add_argument("--version", action="version", version=version("zcode-cli-usage"))
|
|
162
|
+
sub = parser.add_subparsers(dest="command")
|
|
163
|
+
for name in ("status", "json", "refresh", "statusline"):
|
|
164
|
+
sub.add_parser(name)
|
|
165
|
+
daemon = sub.add_parser("daemon", help="Refresh the cache every five minutes")
|
|
166
|
+
daemon.add_argument("--interval", "-i", type=positive_interval, default=INTERVAL)
|
|
167
|
+
configure = sub.add_parser("configure", help="Remember an existing env file path")
|
|
168
|
+
configure.add_argument("--env-file", required=True)
|
|
169
|
+
args = parser.parse_args()
|
|
170
|
+
try:
|
|
171
|
+
if args.command == "configure":
|
|
172
|
+
path = str(Path(args.env_file).expanduser().resolve())
|
|
173
|
+
# Validate the selected file even if a key is present in the environment.
|
|
174
|
+
existing = os.environ.pop("ZAI_API_KEY", None)
|
|
175
|
+
try:
|
|
176
|
+
get_api_key(path)
|
|
177
|
+
finally:
|
|
178
|
+
if existing is not None:
|
|
179
|
+
os.environ["ZAI_API_KEY"] = existing
|
|
180
|
+
atomic_json(config_path(), {"env_file": path})
|
|
181
|
+
print(f"Configured {config_path()}")
|
|
182
|
+
elif args.command == "daemon":
|
|
183
|
+
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
|
|
184
|
+
backoff = args.interval
|
|
185
|
+
while True:
|
|
186
|
+
try:
|
|
187
|
+
data = fetch_usage()
|
|
188
|
+
atomic_json(cache_path(), data)
|
|
189
|
+
display(data, compact=True)
|
|
190
|
+
backoff = args.interval
|
|
191
|
+
except (RuntimeError, ValueError, OSError, OverflowError) as exc:
|
|
192
|
+
print(str(exc), file=sys.stderr, flush=True)
|
|
193
|
+
backoff = min(backoff * 2, max(args.interval, 3600))
|
|
194
|
+
sys.stdout.flush()
|
|
195
|
+
time.sleep(backoff)
|
|
196
|
+
elif args.command == "refresh":
|
|
197
|
+
atomic_json(cache_path(), fetch_usage())
|
|
198
|
+
print(f"Updated {cache_path()}")
|
|
199
|
+
else:
|
|
200
|
+
data = load_usage(cached=args.command == "statusline")
|
|
201
|
+
if args.command == "json":
|
|
202
|
+
print(json.dumps(data, indent=2))
|
|
203
|
+
else:
|
|
204
|
+
display(data, compact=args.command == "statusline")
|
|
205
|
+
except (RuntimeError, ValueError, OSError, OverflowError) as exc:
|
|
206
|
+
print(str(exc), file=sys.stderr)
|
|
207
|
+
return 1
|
|
208
|
+
except KeyboardInterrupt:
|
|
209
|
+
pass
|
|
210
|
+
return 0
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: zcode-cli-usage
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Z.ai Coding Plan quota monitor
|
|
5
|
+
Project-URL: Homepage, https://github.com/wakamex/zcode-cli-usage
|
|
6
|
+
Project-URL: Source, https://github.com/wakamex/zcode-cli-usage
|
|
7
|
+
Requires-Python: >=3.12
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# zcode-cli-usage
|
|
11
|
+
|
|
12
|
+
Monitor your Z.ai Coding Plan's 5-hour and weekly quotas from the terminal. Uses your existing `ZAI_API_KEY`, with no browser login or external Python dependencies.
|
|
13
|
+
|
|
14
|
+
```text
|
|
15
|
+
Plan: lite
|
|
16
|
+
5-hour: 0% (0/2000 credits)
|
|
17
|
+
Weekly: 1% (43/10000 credits) resets 2026-09-10 23:38 EDT
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
Requires Python 3.12 or newer and [uv](https://docs.astral.sh/uv/).
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
uv tool install zcode-cli-usage
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Authentication
|
|
29
|
+
|
|
30
|
+
Export `ZAI_API_KEY` in your environment, or point the tool at an existing `.env` file:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
zcode-cli-usage configure --env-file /path/to/.env
|
|
34
|
+
zcode-cli-usage
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Configuration stores only the file path under `~/.config/zcode-cli-usage/config.json`. The tool reads `ZAI_API_KEY` from that file without executing shell code. It supports plain or quoted assignments, optional `export`, and comments; shell variable expansion is not supported. Credentials are never included in usage output or the cache.
|
|
38
|
+
|
|
39
|
+
An exported `ZAI_API_KEY` takes precedence. Set `ZCODE_USAGE_ENV_FILE` to override the configured file path. `XDG_CONFIG_HOME` and `XDG_CACHE_HOME` are supported.
|
|
40
|
+
|
|
41
|
+
## Commands
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
zcode-cli-usage # Fetch and display current quotas
|
|
45
|
+
zcode-cli-usage status # Same as above
|
|
46
|
+
zcode-cli-usage json # Normalized JSON, including all reported quotas
|
|
47
|
+
zcode-cli-usage refresh # Fetch and update the cache; fail if unavailable
|
|
48
|
+
zcode-cli-usage daemon # Refresh every five minutes, with error backoff
|
|
49
|
+
zcode-cli-usage statusline # Compact output; reuse a cache less than five minutes old
|
|
50
|
+
zcode-cli-usage --version
|
|
51
|
+
python -m zcode_cli_usage --help
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Successful fetches write `~/.cache/zcode-cli-usage/usage.json` atomically. Status, JSON, and statusline commands fall back to cached data when a request fails. Text output explicitly labels stale data; JSON includes `"stale": true` and the original `updated_at`. `refresh` exits unsuccessfully when it cannot fetch current data.
|
|
55
|
+
|
|
56
|
+
Reset times display in your local timezone. The API's reported percentages and remaining balances are preserved, because rounded credit values can differ from arithmetic on the displayed used and total values. An absent reset time stays absent.
|
|
57
|
+
|
|
58
|
+
## Background refresh on Linux
|
|
59
|
+
|
|
60
|
+
After configuring authentication, save this as `~/.config/systemd/user/zcode-cli-usage.service`, adjusting the executable path if needed:
|
|
61
|
+
|
|
62
|
+
```ini
|
|
63
|
+
[Unit]
|
|
64
|
+
Description=Z.ai Coding Plan quota monitor
|
|
65
|
+
After=network-online.target
|
|
66
|
+
|
|
67
|
+
[Service]
|
|
68
|
+
ExecStart=%h/.local/bin/zcode-cli-usage daemon
|
|
69
|
+
Restart=on-failure
|
|
70
|
+
RestartSec=30
|
|
71
|
+
|
|
72
|
+
[Install]
|
|
73
|
+
WantedBy=default.target
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
```sh
|
|
77
|
+
systemctl --user daemon-reload
|
|
78
|
+
systemctl --user enable --now zcode-cli-usage.service
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## API
|
|
82
|
+
|
|
83
|
+
Quota data comes from `GET https://api.z.ai/api/monitor/usage/quota/limit`, authenticated with `Authorization: Bearer <ZAI_API_KEY>`. API-key authentication was verified against the live service on September 5, 2026. The website's separate `credit-usage/usage-detail` endpoint supplies historical reports and is not used by this tool.
|
|
84
|
+
|
|
85
|
+
The normalized JSON maps `currentValue` to `used`, `usage` to `limit`, `percentage` to `pct`, and `nextResetTime` from Unix milliseconds to a UTC `resets_at` string. It retains each quota's `type`, `unit`, `number`, and `remaining`. The current API uses unit `3` for hours and `6` for weeks.
|
|
86
|
+
|
|
87
|
+
## Development
|
|
88
|
+
|
|
89
|
+
```sh
|
|
90
|
+
uv run --locked python -m unittest discover -s tests
|
|
91
|
+
uv run --locked zcode-cli-usage --help
|
|
92
|
+
```
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
zcode_cli_usage/__init__.py,sha256=tcMEGZKYiLAWucRn3cNcZw7L1PtfR8OhrDX5TZ1qvpc,8424
|
|
2
|
+
zcode_cli_usage/__main__.py,sha256=BHLi_-4Bx1gsZn-z6x7wECPn1YTxdc74y0deRea9FzY,45
|
|
3
|
+
zcode_cli_usage-0.1.0.dist-info/METADATA,sha256=qlgJw214Z7IbmWKlpfbj32CzTsTtzW_u1ThtS8U5GWo,3732
|
|
4
|
+
zcode_cli_usage-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
5
|
+
zcode_cli_usage-0.1.0.dist-info/entry_points.txt,sha256=x-52KkSO3dQEiQmX5KytNvxo7XDcVkszv7kxNKSBoKM,57
|
|
6
|
+
zcode_cli_usage-0.1.0.dist-info/RECORD,,
|