#!/usr/bin/env bash # 阿里云百炼 Token Plan 余量/配额查询 — 依赖 bl CLI 的控制台登录(一次性授权) # 用法: bash bailian-token-plan.sh [--summary] # --summary 额外输出统一用量摘要(免费额度 + 近期用量) set -euo pipefail if ! command -v bl >/dev/null 2>&1; then echo "❌ 未找到 bl CLI,请先: npm install -g bailian-cli" >&2 exit 1 fi CFG_FILE="$HOME/.bailian/config.json" # macOS / Linux 兼容的 mtime 秒数 cfg_mtime() { if [ -f "$CFG_FILE" ]; then if command -v stat >/dev/null 2>&1; then stat -f %m "$CFG_FILE" 2>/dev/null || stat -c %Y "$CFG_FILE" 2>/dev/null || echo 0 else echo 0 fi else echo 0 fi } # 尝试查询;失败原因写入 /tmp/bailian-token-plan.err query_token_plan() { echo "🔍 查询百炼 Token Plan 配额 ..." >&2 bl usage token-plan --output json > /tmp/bailian-token-plan.json 2>/tmp/bailian-token-plan.err } # 控制台会话过期/未登录时自动续期:拉起浏览器授权,等 config.json 刷新,然后重试。 # 前提:本机浏览器保持阿里云登录态(勾选「自动登录」),授权页会自动完成回调,无需点击。 relogin_console() { local before after mtime_before mtime_before=$(cfg_mtime) echo "⚠️ 控制台会话已过期/未登录,自动发起浏览器续期(15 分钟内有效)..." >&2 bl auth login --console --console-site domestic >/tmp/bailian-relogin.log 2>&1 & local LPID=$! # 最多等 150s:config.json 被刷新,或登录进程退出 local i for i in $(seq 1 30); do sleep 5 after=$(cfg_mtime) if [ "$after" != "$mtime_before" ] && [ "$after" != "0" ]; then wait "$LPID" 2>/dev/null || true echo "✅ 控制台授权完成,继续查询" >&2 return 0 fi if ! kill -0 "$LPID" 2>/dev/null; then wait "$LPID" 2>/dev/null || true break fi done # 仍然没刷新:杀掉可能残留的登录进程,提示手动完成 kill "$LPID" 2>/dev/null || true wait "$LPID" 2>/dev/null || true echo "⚠️ 未检测到授权回调完成。请检查是否弹出浏览器并完成授权(保持阿里云「自动登录」可免点击),然后重跑本脚本。" >&2 echo " 浏览器授权页若已关闭,可手动执行: bl auth login --console --console-site domestic" >&2 return 1 } if ! query_token_plan; then if grep -qiE "not logged in|has expired|NotLogined" /tmp/bailian-token-plan.err; then if ! relogin_console || ! query_token_plan; then echo "❌ bl usage token-plan 仍失败:" >&2 cat /tmp/bailian-token-plan.err >&2 exit 1 fi else echo "❌ bl usage token-plan 失败:" >&2 cat /tmp/bailian-token-plan.err >&2 exit 1 fi fi cat /tmp/bailian-token-plan.json echo # 友好摘要:周配额已用/剩余比例 + 重置时间(本地时区) if command -v python3 >/dev/null 2>&1; then python3 - <<'PY' import json, sys, datetime, time try: d = json.load(open('/tmp/bailian-token-plan.json')) except Exception as e: print(f"⚠️ 无法解析 JSON: {e}", file=sys.stderr) sys.exit(0) used = d.get('per1WeekPercentage') reset = d.get('per1WeekResetTime') if used is not None: used_pct = used * 100 print(f"📊 本周 Token Plan 已用: {used_pct:.2f}% | 剩余约为: {100 - used_pct:.2f}%") else: print("⚠️ 响应中没有 per1WeekPercentage 字段(结构可能已变化),请参考上方原始 JSON") if reset: dt = datetime.datetime.fromtimestamp(reset / 1000) tzname = time.strftime('%Z') print(f"🔄 本周配额重置时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}(本地时区 {tzname or 'local'})") PY fi if [ "${1:-}" = "--summary" ]; then echo "=== 统一用量摘要(免费额度等) ===" >&2 bl usage summary --output json fi