Files
skills/integrations/pi-zai-usage/scripts/zai-usage.sh
T

55 lines
2.4 KiB
Bash
Executable File

#!/usr/bin/env bash
# Query Z.ai GLM Coding Plan usage (same endpoints as the Claude Code glm-plan-usage plugin).
# Usage: zai-usage.sh [hours] (default: 24h lookback window)
set -euo pipefail
HOURS="${1:-24}"
AUTH_JSON="$HOME/.pi/agent/auth.json"
export KEY="$(python3 -c "import json;print(json.load(open('$AUTH_JSON'))['zai']['key'])")"
BASE="https://api.z.ai/api/monitor/usage"
NOW="$(date -u +'%Y-%m-%d %H:%M:%S')"
START="$(date -u -d "$HOURS hours ago" +'%Y-%m-%d %H:%M:%S')"
Q="startTime=$(python3 -c "import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1]))" "$START")&endTime=$(python3 -c "import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1]))" "$NOW")"
fetch() { curl -sS -m 20 "$1" -H "Authorization: $KEY" -H 'Accept-Language: en-US'; }
python3 - "$BASE" "$Q" <<'EOF'
import json, subprocess, sys
from datetime import datetime, timezone
base, q = sys.argv[1], sys.argv[2]
def fetch(path, params=""):
out = subprocess.run(["curl", "-sS", "-m", "20", f"{base}/{path}{params}",
"-H", f"Authorization: {__import__('os').environ.get('KEY','')}"],
capture_output=True, text=True, env={**__import__('os').environ}).stdout
return json.loads(out).get("data")
# Quota / limits
data = fetch("quota/limit")
level = data.get("level", "?")
print(f"Plan: {level.upper()}\n")
for lim in data.get("limits", []):
if lim["type"] != "CREDIT_LIMIT":
continue
unit = "5-hour" if lim["unit"] == 3 else ("weekly" if lim["unit"] == 6 else f"unit{lim['unit']}")
reset = datetime.fromtimestamp(lim["nextResetTime"] / 1000, tz=timezone.utc)
delta = reset - datetime.now(timezone.utc)
hrs = int(delta.total_seconds() // 3600); mins = int(delta.total_seconds() % 3600 // 60)
when = f"in {hrs}h{mins:02d}m" if hrs else f"in {mins}m"
print(f"{unit:>7} credits: {lim['currentValue']:>6} / {lim['usage']} used ({lim['percentage']}%)"
f" — remaining {lim['remaining']}, resets {when}")
# Model usage in window
data = fetch("model-usage", f"?{q}")
tot = data.get("totalUsage", {})
print(f"\nLast window: {tot.get('totalModelCallCount', 0)} model calls")
for m in tot.get("modelSummaryList", []):
print(f" {m['modelName']}: {m['totalTokens']:,} tokens")
tools = fetch("tool-usage", f"?{q}").get("totalUsage", {})
ncalls = tools.get("totalNetworkSearchCount", 0) + tools.get("totalWebReadMcpCount", 0) + tools.get("totalZreadMcpCount", 0)
print(f"MCP tool calls: {ncalls}")
EOF