zcode-cli-usage 0.1.0__tar.gz → 0.4.0__tar.gz
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.
- {zcode_cli_usage-0.1.0 → zcode_cli_usage-0.4.0}/.gitignore +2 -4
- zcode_cli_usage-0.4.0/LICENSE +21 -0
- zcode_cli_usage-0.4.0/PKG-INFO +25 -0
- zcode_cli_usage-0.4.0/README.md +12 -0
- zcode_cli_usage-0.4.0/pyproject.toml +24 -0
- zcode_cli_usage-0.4.0/zcode_cli_usage/__init__.py +7 -0
- zcode_cli_usage-0.1.0/.github/workflows/publish.yml +0 -30
- zcode_cli_usage-0.1.0/.github/workflows/release-eligibility.yml +0 -12
- zcode_cli_usage-0.1.0/.github/workflows/validation.yml +0 -26
- zcode_cli_usage-0.1.0/.python-version +0 -1
- zcode_cli_usage-0.1.0/PKG-INFO +0 -92
- zcode_cli_usage-0.1.0/README.md +0 -83
- zcode_cli_usage-0.1.0/pyproject.toml +0 -18
- zcode_cli_usage-0.1.0/src/zcode_cli_usage/__init__.py +0 -210
- zcode_cli_usage-0.1.0/tests/test_usage.py +0 -97
- zcode_cli_usage-0.1.0/uv.lock +0 -8
- {zcode_cli_usage-0.1.0/src → zcode_cli_usage-0.4.0}/zcode_cli_usage/__main__.py +0 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mihai
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: zcode-cli-usage
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Z.ai Coding Plan quota monitor
|
|
5
|
+
Project-URL: Homepage, https://github.com/wakamex/clanker-usage
|
|
6
|
+
Project-URL: Source, https://github.com/wakamex/clanker-usage
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: cli,coding-plan,glm,quota,statusline,usage,z.ai,zai
|
|
10
|
+
Requires-Python: >=3.12
|
|
11
|
+
Requires-Dist: clanker-usage==0.4.0
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# zcode-cli-usage
|
|
15
|
+
|
|
16
|
+
Monitor your Z.ai Coding Plan quota from the terminal: current usage, a one-line statusline, and a daemon that keeps a cache fresh.
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
uv tool install zcode-cli-usage
|
|
20
|
+
zcode-cli-usage # current quotas
|
|
21
|
+
zcode-cli-usage statusline # one line, from a cache less than five minutes old
|
|
22
|
+
zcode-cli-usage json # the usage-v1 document
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`zcode-cli-usage` is the Z.ai Coding Plan command of [clanker-usage](https://github.com/wakamex/clanker-usage), so it installs clanker-usage at the same version. The documentation lives there.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# zcode-cli-usage
|
|
2
|
+
|
|
3
|
+
Monitor your Z.ai Coding Plan quota from the terminal: current usage, a one-line statusline, and a daemon that keeps a cache fresh.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
uv tool install zcode-cli-usage
|
|
7
|
+
zcode-cli-usage # current quotas
|
|
8
|
+
zcode-cli-usage statusline # one line, from a cache less than five minutes old
|
|
9
|
+
zcode-cli-usage json # the usage-v1 document
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
`zcode-cli-usage` is the Z.ai Coding Plan command of [clanker-usage](https://github.com/wakamex/clanker-usage), so it installs clanker-usage at the same version. The documentation lives there.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling==1.32.4"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "zcode-cli-usage"
|
|
7
|
+
version = "0.4.0"
|
|
8
|
+
description = "Z.ai Coding Plan quota monitor"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
keywords = ["z.ai", "zai", "glm", "coding-plan", "usage", "quota", "statusline", "cli"]
|
|
11
|
+
requires-python = ">=3.12"
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
dependencies = ["clanker-usage==0.4.0"]
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Homepage = "https://github.com/wakamex/clanker-usage"
|
|
18
|
+
Source = "https://github.com/wakamex/clanker-usage"
|
|
19
|
+
|
|
20
|
+
[project.scripts]
|
|
21
|
+
zcode-cli-usage = "zcode_cli_usage:main"
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel]
|
|
24
|
+
packages = ["zcode_cli_usage"]
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
name: Publish to PyPI
|
|
2
|
-
|
|
3
|
-
on:
|
|
4
|
-
push:
|
|
5
|
-
tags: ["v*"]
|
|
6
|
-
|
|
7
|
-
permissions:
|
|
8
|
-
contents: read
|
|
9
|
-
|
|
10
|
-
jobs:
|
|
11
|
-
validate:
|
|
12
|
-
uses: ./.github/workflows/validation.yml
|
|
13
|
-
publish:
|
|
14
|
-
needs: validate
|
|
15
|
-
runs-on: ubuntu-latest
|
|
16
|
-
environment: pypi
|
|
17
|
-
permissions:
|
|
18
|
-
contents: read
|
|
19
|
-
id-token: write
|
|
20
|
-
steps:
|
|
21
|
-
- uses: actions/checkout@v7.0.1
|
|
22
|
-
- uses: astral-sh/setup-uv@v9.0.0
|
|
23
|
-
with:
|
|
24
|
-
enable-cache: false
|
|
25
|
-
- name: Verify version tag
|
|
26
|
-
run: test "$GITHUB_REF_NAME" = "v$(uv --no-config version --short)"
|
|
27
|
-
- name: Build
|
|
28
|
-
run: uv --no-config build --no-sources
|
|
29
|
-
- name: Publish
|
|
30
|
-
run: uv publish --trusted-publishing always
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
name: Validation
|
|
2
|
-
|
|
3
|
-
on:
|
|
4
|
-
workflow_call:
|
|
5
|
-
pull_request:
|
|
6
|
-
|
|
7
|
-
permissions:
|
|
8
|
-
contents: read
|
|
9
|
-
|
|
10
|
-
jobs:
|
|
11
|
-
validate:
|
|
12
|
-
runs-on: ubuntu-latest
|
|
13
|
-
steps:
|
|
14
|
-
- uses: actions/checkout@v7.0.1
|
|
15
|
-
- uses: astral-sh/setup-uv@v9.0.0
|
|
16
|
-
with:
|
|
17
|
-
enable-cache: false
|
|
18
|
-
- name: Check lockfile
|
|
19
|
-
run: uv --no-config lock --check
|
|
20
|
-
- name: Verify version tag
|
|
21
|
-
if: startsWith(github.ref, 'refs/tags/')
|
|
22
|
-
run: test "$GITHUB_REF_NAME" = "v$(uv --no-config version --short)"
|
|
23
|
-
- name: Test
|
|
24
|
-
run: uv --no-config run --locked python -m unittest discover -s tests
|
|
25
|
-
- name: Build
|
|
26
|
-
run: uv --no-config build --no-sources
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
3.12
|
zcode_cli_usage-0.1.0/PKG-INFO
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
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
|
-
```
|
zcode_cli_usage-0.1.0/README.md
DELETED
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
# zcode-cli-usage
|
|
2
|
-
|
|
3
|
-
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.
|
|
4
|
-
|
|
5
|
-
```text
|
|
6
|
-
Plan: lite
|
|
7
|
-
5-hour: 0% (0/2000 credits)
|
|
8
|
-
Weekly: 1% (43/10000 credits) resets 2026-09-10 23:38 EDT
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
## Install
|
|
12
|
-
|
|
13
|
-
Requires Python 3.12 or newer and [uv](https://docs.astral.sh/uv/).
|
|
14
|
-
|
|
15
|
-
```sh
|
|
16
|
-
uv tool install zcode-cli-usage
|
|
17
|
-
```
|
|
18
|
-
|
|
19
|
-
## Authentication
|
|
20
|
-
|
|
21
|
-
Export `ZAI_API_KEY` in your environment, or point the tool at an existing `.env` file:
|
|
22
|
-
|
|
23
|
-
```sh
|
|
24
|
-
zcode-cli-usage configure --env-file /path/to/.env
|
|
25
|
-
zcode-cli-usage
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
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.
|
|
29
|
-
|
|
30
|
-
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.
|
|
31
|
-
|
|
32
|
-
## Commands
|
|
33
|
-
|
|
34
|
-
```sh
|
|
35
|
-
zcode-cli-usage # Fetch and display current quotas
|
|
36
|
-
zcode-cli-usage status # Same as above
|
|
37
|
-
zcode-cli-usage json # Normalized JSON, including all reported quotas
|
|
38
|
-
zcode-cli-usage refresh # Fetch and update the cache; fail if unavailable
|
|
39
|
-
zcode-cli-usage daemon # Refresh every five minutes, with error backoff
|
|
40
|
-
zcode-cli-usage statusline # Compact output; reuse a cache less than five minutes old
|
|
41
|
-
zcode-cli-usage --version
|
|
42
|
-
python -m zcode_cli_usage --help
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
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.
|
|
46
|
-
|
|
47
|
-
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.
|
|
48
|
-
|
|
49
|
-
## Background refresh on Linux
|
|
50
|
-
|
|
51
|
-
After configuring authentication, save this as `~/.config/systemd/user/zcode-cli-usage.service`, adjusting the executable path if needed:
|
|
52
|
-
|
|
53
|
-
```ini
|
|
54
|
-
[Unit]
|
|
55
|
-
Description=Z.ai Coding Plan quota monitor
|
|
56
|
-
After=network-online.target
|
|
57
|
-
|
|
58
|
-
[Service]
|
|
59
|
-
ExecStart=%h/.local/bin/zcode-cli-usage daemon
|
|
60
|
-
Restart=on-failure
|
|
61
|
-
RestartSec=30
|
|
62
|
-
|
|
63
|
-
[Install]
|
|
64
|
-
WantedBy=default.target
|
|
65
|
-
```
|
|
66
|
-
|
|
67
|
-
```sh
|
|
68
|
-
systemctl --user daemon-reload
|
|
69
|
-
systemctl --user enable --now zcode-cli-usage.service
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
## API
|
|
73
|
-
|
|
74
|
-
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.
|
|
75
|
-
|
|
76
|
-
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.
|
|
77
|
-
|
|
78
|
-
## Development
|
|
79
|
-
|
|
80
|
-
```sh
|
|
81
|
-
uv run --locked python -m unittest discover -s tests
|
|
82
|
-
uv run --locked zcode-cli-usage --help
|
|
83
|
-
```
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
[project]
|
|
2
|
-
name = "zcode-cli-usage"
|
|
3
|
-
version = "0.1.0"
|
|
4
|
-
description = "Z.ai Coding Plan quota monitor"
|
|
5
|
-
readme = "README.md"
|
|
6
|
-
requires-python = ">=3.12"
|
|
7
|
-
dependencies = []
|
|
8
|
-
|
|
9
|
-
[project.scripts]
|
|
10
|
-
zcode-cli-usage = "zcode_cli_usage:main"
|
|
11
|
-
|
|
12
|
-
[project.urls]
|
|
13
|
-
Homepage = "https://github.com/wakamex/zcode-cli-usage"
|
|
14
|
-
Source = "https://github.com/wakamex/zcode-cli-usage"
|
|
15
|
-
|
|
16
|
-
[build-system]
|
|
17
|
-
requires = ["hatchling"]
|
|
18
|
-
build-backend = "hatchling.build"
|
|
@@ -1,210 +0,0 @@
|
|
|
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
|
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
import copy
|
|
2
|
-
import json
|
|
3
|
-
import os
|
|
4
|
-
from pathlib import Path
|
|
5
|
-
import subprocess
|
|
6
|
-
import sys
|
|
7
|
-
import tempfile
|
|
8
|
-
import tomllib
|
|
9
|
-
import unittest
|
|
10
|
-
from unittest.mock import patch
|
|
11
|
-
|
|
12
|
-
import zcode_cli_usage as usage
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
# Actual quota response observed with API-key authentication on 2026-09-05.
|
|
16
|
-
LIVE_RESPONSE = {
|
|
17
|
-
"code": 200, "success": True, "msg": "Operation successful",
|
|
18
|
-
"data": {"level": "lite", "limits": [
|
|
19
|
-
{"type": "CREDIT_LIMIT", "unit": 3, "number": 5, "usage": 2000,
|
|
20
|
-
"currentValue": 0, "remaining": 2000, "percentage": 0},
|
|
21
|
-
{"type": "CREDIT_LIMIT", "unit": 6, "number": 1, "usage": 10000,
|
|
22
|
-
"currentValue": 43, "remaining": 9956, "percentage": 1,
|
|
23
|
-
"nextResetTime": 1789097919995},
|
|
24
|
-
]},
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
class UsageTests(unittest.TestCase):
|
|
29
|
-
def setUp(self):
|
|
30
|
-
self.temp = tempfile.TemporaryDirectory()
|
|
31
|
-
self.addCleanup(self.temp.cleanup)
|
|
32
|
-
self.env = patch.dict(os.environ, {
|
|
33
|
-
"XDG_CONFIG_HOME": self.temp.name, "XDG_CACHE_HOME": self.temp.name,
|
|
34
|
-
})
|
|
35
|
-
self.env.start()
|
|
36
|
-
self.addCleanup(self.env.stop)
|
|
37
|
-
|
|
38
|
-
def test_actual_response(self):
|
|
39
|
-
data = usage.normalize(LIVE_RESPONSE)
|
|
40
|
-
short, weekly = data["limits"]
|
|
41
|
-
self.assertEqual(data["plan"], "lite")
|
|
42
|
-
self.assertIsNone(short["resets_at"])
|
|
43
|
-
self.assertEqual((weekly["used"], weekly["limit"], weekly["pct"], weekly["remaining"]), (43, 10000, 1, 9956))
|
|
44
|
-
self.assertEqual(weekly["resets_at"], "2026-09-11T03:38:39.995000+00:00")
|
|
45
|
-
|
|
46
|
-
def test_invalid_responses(self):
|
|
47
|
-
for response in ({}, {"code": 401, "success": False}, {"code": 200, "success": True, "data": {"limits": []}}):
|
|
48
|
-
with self.assertRaises(ValueError):
|
|
49
|
-
usage.normalize(response)
|
|
50
|
-
for value in (True, -1, float("nan"), "43", None):
|
|
51
|
-
response = copy.deepcopy(LIVE_RESPONSE)
|
|
52
|
-
response["data"]["limits"][0]["currentValue"] = value
|
|
53
|
-
with self.assertRaises(ValueError):
|
|
54
|
-
usage.normalize(response)
|
|
55
|
-
|
|
56
|
-
def test_unknown_quota_preserved(self):
|
|
57
|
-
response = copy.deepcopy(LIVE_RESPONSE)
|
|
58
|
-
response["data"]["limits"][0].update(type="FUTURE_LIMIT", unit=42)
|
|
59
|
-
item = usage.normalize(response)["limits"][0]
|
|
60
|
-
self.assertIn("FUTURE_LIMIT", usage.label(item))
|
|
61
|
-
|
|
62
|
-
def test_env_file_is_not_executed(self):
|
|
63
|
-
path = Path(self.temp.name) / ".env"
|
|
64
|
-
path.write_text('UNRELATED=ignored\nexport ZAI_API_KEY="literal$(false)" # comment\n')
|
|
65
|
-
with patch.dict(os.environ, {"ZAI_API_KEY": ""}):
|
|
66
|
-
self.assertEqual(usage.get_api_key(path), "literal$(false)")
|
|
67
|
-
with patch.dict(os.environ, {"ZAI_API_KEY": "override"}):
|
|
68
|
-
self.assertEqual(usage.get_api_key(path), "override")
|
|
69
|
-
|
|
70
|
-
def test_cache_and_stale_fallback(self):
|
|
71
|
-
data = usage.normalize(LIVE_RESPONSE)
|
|
72
|
-
with patch.object(usage, "fetch_usage", return_value=data) as fetch:
|
|
73
|
-
self.assertEqual(usage.load_usage(), data)
|
|
74
|
-
self.assertEqual(usage.load_usage(cached=True), data)
|
|
75
|
-
fetch.assert_called_once()
|
|
76
|
-
with patch.object(usage, "fetch_usage", side_effect=RuntimeError("HTTP 401")):
|
|
77
|
-
stale = usage.load_usage()
|
|
78
|
-
self.assertTrue(stale["stale"])
|
|
79
|
-
self.assertEqual(stale["updated_at"], data["updated_at"])
|
|
80
|
-
self.assertNotIn("stale", json.loads(usage.cache_path().read_text()))
|
|
81
|
-
self.assertEqual(usage.cache_path().stat().st_mode & 0o777, 0o600)
|
|
82
|
-
|
|
83
|
-
def test_entrypoints(self):
|
|
84
|
-
for command in ([sys.executable, "-m", "zcode_cli_usage"], [str(Path(sys.executable).parent / "zcode-cli-usage")]):
|
|
85
|
-
result = subprocess.run([*command, "--version"], capture_output=True, text=True)
|
|
86
|
-
self.assertEqual(result.returncode, 0, result.stderr)
|
|
87
|
-
expected = tomllib.loads((Path(__file__).parents[1] / "pyproject.toml").read_text())["project"]["version"]
|
|
88
|
-
self.assertEqual(result.stdout.strip(), expected)
|
|
89
|
-
result = subprocess.run([*command, "daemon", "--interval", "0"], capture_output=True)
|
|
90
|
-
self.assertNotEqual(result.returncode, 0)
|
|
91
|
-
env = {**os.environ, "ZAI_API_KEY": "", "ZCODE_USAGE_ENV_FILE": str(Path(self.temp.name) / "missing.env")}
|
|
92
|
-
result = subprocess.run([*command, "refresh"], capture_output=True, env=env)
|
|
93
|
-
self.assertEqual(result.returncode, 1)
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
if __name__ == "__main__":
|
|
97
|
-
unittest.main()
|
zcode_cli_usage-0.1.0/uv.lock
DELETED
|
File without changes
|