Add pi-zai-usage skill: query Z.ai GLM Coding Plan usage

This commit is contained in:
2026-09-14 07:18:55 +02:00
parent 109e09cbf1
commit d155c0247e
3 changed files with 73 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
# Integration Skills Collection
Skills that integrate external services and APIs with the Pi coding agent.
+16
View File
@@ -0,0 +1,16 @@
---
name: zai-usage
description: Query current Z.ai GLM Coding Plan quota and usage (5-hour/weekly credits, model tokens, MCP calls). Use when the user asks about their Z.ai usage, remaining credits, quota, or rate-limit status.
---
Run the script once and report the result:
```bash
bash ~/.pi/agent/skills/zai-usage/scripts/zai-usage.sh # last 24h window
bash ~/.pi/agent/skills/zai-usage/scripts/zai-usage.sh 168 # last 7 days
```
- Credentials come from `~/.pi/agent/auth.json` (`zai.key`) — never print the key.
- Endpoints: `api.z.ai/api/monitor/usage/{model-usage,tool-usage,quota/limit}` (same as Z.ai's Claude Code plugin).
- Present 5-hour and weekly credits (used/remaining/reset) plus model token totals in a small table.
- If the key is missing, tell the user to run `/login zai` in pi first.
+54
View File
@@ -0,0 +1,54 @@
#!/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"
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