Skip to content

Instantly share code, notes, and snippets.

@Amperstrand
Last active April 14, 2026 12:15
Show Gist options
  • Select an option

  • Save Amperstrand/64d3e13dc917be7c0b7b5baac3361417 to your computer and use it in GitHub Desktop.

Select an option

Save Amperstrand/64d3e13dc917be7c0b7b5baac3361417 to your computer and use it in GitHub Desktop.
opencode-usage: Check provider quotas and auto-disable exhausted providers
#!/usr/bin/env bash
set -euo pipefail
CONFIG_PATH="$HOME/.config/opencode/opencode.json"
AUTH_PATH="$HOME/.local/share/opencode/auth.json"
TMPDIR_WORK="$(mktemp -d)"
export TMPDIR_WORK
export CHECK_ONLY
export JSON_OUTPUT
trap 'rm -rf "$TMPDIR_WORK"' EXIT
# ── Colors ──────────────────────────────────────────────────────────────────
if [[ -t 1 ]] && [[ -z "${NO_COLOR:-}" ]]; then
RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[0;33m'
GRAY='\033[0;90m' CYAN='\033[0;36m' BOLD='\033[1m' DIM='\033[2m'
RESET='\033[0m'
else
RED='' GREEN='' YELLOW='' GRAY='' CYAN='' BOLD='' DIM='' RESET=''
fi
CHECK_ONLY=false
JSON_OUTPUT=false
for arg in "$@"; do
case "$arg" in
--check) CHECK_ONLY=1 ;;
--json) JSON_OUTPUT=1 ;;
-h|--help)
echo "Usage: opencode-usage [--check] [--json]"
echo ""
echo " --check Only show status, don't modify config"
echo " --json Output machine-readable JSON"
echo ""
echo "Probes OpenCode Zen, OpenAI, and GitHub Copilot for quota/usage."
echo "Auto-updates ~/.config/opencode/opencode.json to disable dead providers."
exit 0 ;;
esac
done
export CHECK_ONLY
export JSON_OUTPUT
# ── Helpers ─────────────────────────────────────────────────────────────────
die() { echo -e "${RED}ERROR: $*${RESET}" >&2; exit 1; }
# ── Read auth ───────────────────────────────────────────────────────────────
[[ -f "$AUTH_PATH" ]] || die "Auth file not found: $AUTH_PATH"
read_auth() {
python3 -c "
import json, sys
with open('$AUTH_PATH') as f:
auth = json.load(f)
result = {}
for key in ['opencode', 'openai', 'github-copilot']:
if key in auth:
result[key] = auth[key]
print(json.dumps(result))
"
}
AUTH_JSON="$(read_auth)"
ZEN_KEY="$(echo "$AUTH_JSON" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("opencode",{}).get("key",""))')"
OPENAI_TOKEN="$(echo "$AUTH_JSON" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("openai",{}).get("access",""))')"
OPENAI_ACCOUNT="$(echo "$AUTH_JSON" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("openai",{}).get("accountId",""))')"
GH_TOKEN="$(echo "$AUTH_JSON" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("github-copilot",{}).get("access",""))')"
# ── Probe functions ─────────────────────────────────────────────────────────
# Each function writes a result JSON to $TMPDIR_WORK/<provider>.json
# Format: {"status":"active|disabled|limited|unknown","line1":"...","line2":"...","reset_epoch":0}
probe_zen() {
local out="$TMPDIR_WORK/opencode.json"
if [[ -z "$ZEN_KEY" ]]; then
echo '{"status":"unknown","lines":["No API key configured"],"reset_epoch":0}' > "$out"
return
fi
local resp
resp="$(curl -s --connect-timeout 5 --max-time 10 \
-w '\n__HTTP__%{http_code}' \
"https://opencode.ai/zen/v1/messages" \
-H "x-api-key: $ZEN_KEY" \
-H "Content-Type: application/json" \
-H "anthropic-version: 2023-06-01" \
-d '{"model":"claude-haiku-4-5","max_tokens":1,"messages":[{"role":"user","content":"hi"}]}' 2>/dev/null)"
local http_code body
http_code="$(echo "$resp" | grep '__HTTP__' | sed 's/.*__HTTP__//')"
body="$(echo "$resp" | grep -v '__HTTP__')"
echo "$body" > "$TMPDIR_WORK/zen_resp.json"
echo "$http_code" > "$TMPDIR_WORK/zen_httpcode.txt"
cat > "$TMPDIR_WORK/zen_parse.py" << 'PYEOF'
import json, time, os, re
resp_path = os.environ['TMPDIR_WORK'] + '/zen_resp.json'
with open(os.environ['TMPDIR_WORK'] + '/zen_httpcode.txt') as f:
http_code = int(f.read().strip())
status = 'active'
lines = []
reset_epoch = 0
now = time.time()
if http_code == 200:
lines.append('Working')
else:
try:
with open(resp_path) as f:
d = json.load(f)
err_type = d.get('error', {}).get('type', '')
err_msg = d.get('error', {}).get('message', '')
except:
err_type = ''
err_msg = 'Failed to parse response'
if err_type in ('SubscriptionUsageLimitError', 'FreeUsageLimitError'):
status = 'disabled'
lines.append(f'Quota exceeded: {err_msg}')
m = re.search(r'[Rr]etry in (\d+) (day|hour|minute|week)', err_msg)
if m:
num, unit = int(m.group(1)), m.group(2)
mults = {'minute': 60, 'hour': 3600, 'day': 86400, 'week': 604800}
secs = num * mults.get(unit, 0)
reset_epoch = int(now) + secs
def dh(s):
s = max(0, int(s))
if s < 3600: return f'{s // 60} minutes'
if s < 86400: return f'{s // 3600} hours'
return f'{s // 86400}d {(s % 86400) // 3600}h'
lines.append(f'Available again in {dh(secs)}')
elif err_type in ('AuthError', 'authentication_error'):
status = 'unknown'
lines.append(f'Auth error: {err_msg}')
else:
status = 'unknown'
lines.append(f'HTTP {http_code}: {err_msg[:80]}')
print(json.dumps({'status': status, 'lines': lines, 'reset_epoch': reset_epoch}))
PYEOF
python3 "$TMPDIR_WORK/zen_parse.py" > "$out"
}
probe_openai() {
local out="$TMPDIR_WORK/openai.json"
if [[ -z "$OPENAI_TOKEN" ]]; then
echo '{"status":"unknown","lines":["No OAuth token configured"],"reset_epoch":0}' > "$out"
return
fi
local resp
resp="$(curl -s --connect-timeout 5 --max-time 10 \
-w '\n__HTTP__%{http_code}' \
"https://chatgpt.com/backend-api/wham/usage" \
-H "Authorization: Bearer $OPENAI_TOKEN" \
-H "ChatGPT-Account-Id: $OPENAI_ACCOUNT" 2>/dev/null)"
local http_code body
http_code="$(echo "$resp" | grep '__HTTP__' | sed 's/.*__HTTP__//')"
body="$(echo "$resp" | grep -v '__HTTP__')"
echo "$body" > "$TMPDIR_WORK/oai_resp.json"
if [[ "$http_code" != "200" ]] || [[ -z "$body" ]] || ! python3 -c 'import json; json.load(open("'$TMPDIR_WORK/oai_resp.json'"))' 2>/dev/null; then
echo "{\"status\":\"unknown\",\"lines\":[\"HTTP ${http_code}: token may be expired\"],\"reset_epoch\":0}" > "$out"
return
fi
cat > "$TMPDIR_WORK/oai_parse.py" << 'PYEOF'
import json, time, os
from datetime import datetime
body = open(os.environ['TMPDIR_WORK'] + '/oai_resp.json').read()
d = json.loads(body)
lines = []
status = 'active'
reset_epoch = 0
now = time.time()
plan = d.get('plan_type', 'unknown')
rl = d.get('rate_limit', {})
credits = d.get('credits', {})
allowed = rl.get('allowed', True)
limit_reached = rl.get('limit_reached', False)
primary = rl.get('primary_window', {})
secondary = rl.get('secondary_window', {})
pct_primary = primary.get('used_percent', 0)
pct_secondary = secondary.get('used_percent', 0)
reset_primary_s = primary.get('reset_after_seconds', 0)
reset_secondary_epoch = secondary.get('reset_at', 0)
has_credits = credits.get('has_credits', False)
unlimited = credits.get('unlimited', False)
balance = credits.get('balance', '0')
def dh(s):
s = max(0, int(s))
if s < 3600: return f'{s // 60} minutes'
if s < 86400: return f'{s // 3600} hours'
return f'{s // 86400}d {(s % 86400) // 3600}h'
def ts(epoch_s):
return datetime.fromtimestamp(epoch_s).strftime('%b %d, %H:%M')
lines.append(f'Plan: {plan}')
if not allowed or limit_reached:
status = 'disabled'
lines.append('Rate limit reached')
if reset_secondary_epoch:
reset_epoch = reset_secondary_epoch
lines.append(f'Resets in {dh(reset_secondary_epoch - now)} ({ts(reset_secondary_epoch)})')
elif pct_secondary >= 100:
status = 'disabled'
lines.append(f'Weekly limit: {int(pct_secondary)}% used')
if reset_secondary_epoch:
reset_epoch = reset_secondary_epoch
lines.append(f'Resets in {dh(reset_secondary_epoch - now)} ({ts(reset_secondary_epoch)})')
elif pct_secondary >= 80:
status = 'limited'
lines.append(f'Weekly: {int(pct_secondary)}% used')
lines.append(f'Primary: {int(pct_primary)}% (resets in {dh(reset_primary_s)})')
if reset_secondary_epoch:
reset_epoch = reset_secondary_epoch
else:
status = 'active'
lines.append(f'Weekly: {int(pct_secondary)}% used')
if balance and balance != '0' and not unlimited:
lines.append(f'Credits: ${balance}')
print(json.dumps({'status': status, 'lines': lines, 'reset_epoch': reset_epoch}))
PYEOF
python3 "$TMPDIR_WORK/oai_parse.py" > "$out" 2>/dev/null
}
probe_copilot() {
local out="$TMPDIR_WORK/github-copilot.json"
if [[ -z "$GH_TOKEN" ]]; then
echo '{"status":"unknown","lines":["No OAuth token configured"],"reset_epoch":0}' > "$out"
return
fi
local resp
resp="$(curl -s --connect-timeout 5 --max-time 10 \
-w '\n__HTTP__%{http_code}' \
"https://api.github.com/copilot_internal/user" \
-H "Authorization: token $GH_TOKEN" \
-H "Accept: application/vnd.github+json" 2>/dev/null)"
local http_code body
http_code="$(echo "$resp" | grep '__HTTP__' | sed 's/.*__HTTP__//')"
body="$(echo "$resp" | grep -v '__HTTP__')"
echo "$body" > "$TMPDIR_WORK/gh_resp.json"
if [[ "$http_code" != "200" ]] || [[ -z "$body" ]] || ! python3 -c 'import json; json.load(open("'$TMPDIR_WORK/gh_resp.json'"))' 2>/dev/null; then
echo "{\"status\":\"unknown\",\"lines\":[\"HTTP ${http_code}: token may be expired\"],\"reset_epoch\":0}" > "$out"
return
fi
cat > "$TMPDIR_WORK/gh_parse.py" << 'PYEOF'
import json, time, os
from datetime import datetime
d = json.load(open(os.environ['TMPDIR_WORK'] + '/gh_resp.json'))
lines = []
status = 'active'
reset_epoch = 0
now = time.time()
plan = d.get('copilot_plan', 'unknown')
qs = d.get('quota_snapshots', {})
chat_q = qs.get('chat', {})
comp_q = qs.get('completions', {})
premium_q = qs.get('premium_interactions', {})
chat_unlimited = chat_q.get('unlimited', False)
comp_unlimited = comp_q.get('unlimited', False)
prem_unlimited = premium_q.get('unlimited', False)
prem_remaining = premium_q.get('quota_remaining', 0)
prem_entitlement = premium_q.get('entitlement', 0)
prem_pct = premium_q.get('percent_remaining', 0)
reset_date_str = d.get('quota_reset_date_utc', '')
lines.append(f'Plan: {plan.replace("_", " ").title()}')
if prem_unlimited:
lines.append('Premium: Unlimited')
status = 'active'
elif prem_remaining > 0:
lines.append(f'Premium: {int(prem_remaining)}/{int(prem_entitlement)} ({int(prem_pct)}% remaining)')
status = 'active'
else:
lines.append(f'Premium: 0/{int(prem_entitlement)} (exhausted)')
status = 'disabled'
if chat_unlimited:
lines.append('Chat: Unlimited')
else:
lines.append(f'Chat: {chat_q.get("quota_remaining", 0)} remaining')
if comp_unlimited:
lines.append('Completions: Unlimited')
else:
lines.append(f'Completions: {comp_q.get("quota_remaining", 0)} remaining')
if reset_date_str:
try:
rds = reset_date_str.replace('Z', '+00:00')
if '+' in rds and not rds.endswith('+00:00'):
rds = rds.split('+')[0]
reset_dt = datetime.fromisoformat(rds.replace('+00:00', ''))
reset_epoch = int(reset_dt.timestamp())
lines.append(f'Monthly reset: {reset_dt.strftime("%b %d, %Y")}')
except:
lines.append(f'Monthly reset: {reset_date_str[:10]}')
print(json.dumps({'status': status, 'lines': lines, 'reset_epoch': reset_epoch}))
PYEOF
python3 "$TMPDIR_WORK/gh_parse.py" > "$out" 2>/dev/null
}
# ── Run all probes in parallel ─────────────────────────────────────────────
probe_zen &
PID_ZEN=$!
probe_openai &
PID_OAI=$!
probe_copilot &
PID_GH=$!
wait $PID_ZEN $PID_OAI $PID_GH 2>/dev/null || true
# ── Process results with python3 (single script, no fragile bash↔json handoff) ──
python3 << 'PYEOF'
import json, os, sys, time
from datetime import datetime
TMPDIR = os.environ["TMPDIR_WORK"]
CHECK_ONLY = os.environ.get("CHECK_ONLY", "0") == "1"
JSON_OUTPUT = os.environ.get("JSON_OUTPUT", "0") in ("1", "true")
CONFIG_PATH = os.path.expanduser("~/.config/opencode/opencode.json")
def load_result(name):
path = os.path.join(TMPDIR, f"{name}.json")
try:
with open(path) as f:
return json.load(f)
except:
return {"status": "unknown", "lines": ["Probe failed"], "reset_epoch": 0}
results = {
"opencode": load_result("opencode"),
"openai": load_result("openai"),
"github-copilot": load_result("github-copilot"),
}
# JSON output mode
if JSON_OUTPUT:
print(json.dumps(results, indent=2))
sys.exit(0)
# Colors
now = time.time()
RECOVERY_THRESHOLD = 15 * 60 # 15 minutes in seconds
RED = "\033[0;31m" if os.isatty(1) and not os.environ.get("NO_COLOR") else ""
GREEN = "\033[0;32m" if os.isatty(1) and not os.environ.get("NO_COLOR") else ""
YELLOW = "\033[0;33m" if os.isatty(1) and not os.environ.get("NO_COLOR") else ""
GRAY = "\033[0;90m" if os.isatty(1) and not os.environ.get("NO_COLOR") else ""
CYAN = "\033[0;36m" if os.isatty(1) and not os.environ.get("NO_COLOR") else ""
BOLD = "\033[1m" if os.isatty(1) and not os.environ.get("NO_COLOR") else ""
DIM = "\033[2m" if os.isatty(1) and not os.environ.get("NO_COLOR") else ""
RESET = "\033[0m" if os.isatty(1) and not os.environ.get("NO_COLOR") else ""
def status_label(s):
colors = {"active": GREEN, "disabled": RED, "limited": YELLOW, "unknown": GRAY}
return f"{colors.get(s, GRAY)}[{s.upper()}]{RESET}"
def duration_human(seconds):
seconds = max(0, int(seconds))
if seconds < 3600: return f"{seconds // 60} minutes"
if seconds < 86400: return f"{seconds // 3600} hours"
d, h = seconds // 86400, (seconds % 86400) // 3600
return f"{d}d {h}h"
def relative_future(epoch_s):
now = time.time()
diff = epoch_s - now
if diff <= 0: return "now"
dt = datetime.fromtimestamp(epoch_s)
return f"{duration_human(diff)} ({dt.strftime('%b %d, %H:%M')})"
# Print header
print()
print(f"{BOLD} OpenCode Provider Status{RESET}")
print(f" ─────────────────────────────────────────")
print()
# Provider display info
providers = [
("OpenCode Zen", "opencode", results["opencode"]),
("OpenAI (ChatGPT)","openai", results["openai"]),
("GitHub Copilot", "github-copilot", results["github-copilot"]),
]
for display_name, config_id, result in providers:
status = result["status"]
lines = result.get("lines", [])
print(f" {BOLD}{display_name}{RESET} {status_label(status)}")
for line in lines:
print(f" ↳ {line}")
# Show recovery note for disabled providers within 15 min
if status == "disabled":
reset_epoch = result.get("reset_epoch", 0)
if reset_epoch > 0 and (reset_epoch - now) <= RECOVERY_THRESHOLD:
print(f" {DIM}↳ Recovers soon — keeping enabled{RESET}")
print()
# Compute config changes
# Disable providers that are down, UNLESS they'll recover within 15 minutes.
# A provider that resets soon is better left enabled so it auto-recovers.
disabled = []
for config_id, result in results.items():
if result["status"] not in ("active", "limited"):
reset_epoch = result.get("reset_epoch", 0)
if reset_epoch > 0 and (reset_epoch - now) <= RECOVERY_THRESHOLD:
# Will recover within 15 min — keep enabled, don't disable
pass
else:
disabled.append(config_id)
# Best model selection
if results["github-copilot"]["status"] in ("active", "limited"):
best_model = "github-copilot/claude-sonnet-4.6"
elif results["openai"]["status"] in ("active", "limited"):
best_model = "openai/gpt-5.2-codex"
elif results["opencode"]["status"] in ("active", "limited"):
best_model = "opencode/claude-sonnet-4.5"
else:
best_model = "github-copilot/claude-sonnet-4.6"
# Update config
if not CHECK_ONLY:
if os.path.exists(CONFIG_PATH):
try:
with open(CONFIG_PATH) as f:
config = json.load(f)
except json.JSONDecodeError:
print(f" {RED}Warning: config file is malformed, not modifying{RESET}")
sys.exit(1)
else:
config = {"$schema": "https://opencode.ai/config.json"}
if disabled:
config["disabled_providers"] = disabled
else:
config.pop("disabled_providers", None)
config.pop("enabled_providers", None)
config["model"] = best_model
os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
with open(CONFIG_PATH, "w") as f:
json.dump(config, f, indent=2)
f.write("\n")
print(f" {CYAN}Config updated:{RESET}")
if disabled:
print(f" disabled_providers: {json.dumps(disabled)}")
else:
print(f" disabled_providers: {GREEN}(none — all providers active){RESET}")
print(f" model: {BOLD}{best_model}{RESET}")
else:
print(f" {DIM}--check mode: config not modified{RESET}")
if disabled:
print(f" {DIM}Would disable: {json.dumps(disabled)}{RESET}")
print(f" {DIM}Would set model: {best_model}{RESET}")
print()
# Earliest reset time
earliest_reset = 0
for config_id, result in results.items():
if result["status"] == "disabled" and result.get("reset_epoch", 0) > 0:
if earliest_reset == 0 or result["reset_epoch"] < earliest_reset:
earliest_reset = result["reset_epoch"]
if earliest_reset > 0:
print(f" {DIM}Next provider recovery: {relative_future(earliest_reset)}{RESET}")
print(f" {DIM}Run again after that to auto-re-enable.{RESET}")
print()
# Exit code
any_working = any(r["status"] in ("active", "limited") for r in results.values())
if not any_working:
print(f" {RED}{BOLD}No providers are working!{RESET}")
sys.exit(1)
PYEOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment