| 1 | 1 | new file mode 100644 |
| index 0000000..f6b013a | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,16 @@ | ||
| 1 | +# build artifacts | |
| 2 | +/plugin_google_quota | |
| 3 | +/plugin_google_quota.exe | |
| 4 | +/plugin_google_quota.musl | |
| 5 | +/plugin_google_quota.arm64 | |
| 6 | +/plugin_google_quota.macos-arm64 | |
| 7 | +/plugin_google_quota.macos-x86_64 | |
| 8 | +bin/ | |
| 9 | + | |
| 10 | +# test scratch | |
| 11 | +*.tmp | |
| 12 | +/tests/fixtures-out/ | |
| 13 | + | |
| 14 | +# python tooling | |
| 15 | +__pycache__/ | |
| 16 | +*.pyc |
| 1 | 1 | new file mode 100644 |
| index 0000000..ef80120 | ||
| --- /dev/null | ||
| +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) 2026 SCORPIOX INC | |
| 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. |
| 1 | 1 | new file mode 100644 |
| index 0000000..bf29f83 | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,78 @@ | ||
| 1 | +# plugin_google_quota - SCORPIOX BOT open-source Google Antigravity quota monitor | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_google_quota | |
| 5 | +# make musl static musl x86_64 -> ./plugin_google_quota.musl | |
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_google_quota.arm64 | |
| 7 | +# make win64 MinGW-w64 static -> ./plugin_google_quota.exe | |
| 8 | +# make macos Apple clang -> ./plugin_google_quota (run this on macOS) | |
| 9 | +# make ui regenerate src/ui_html.h from src/ui.html | |
| 10 | +# make install copy the binary into this node's plugin directory | |
| 11 | +# make test build + run tests/run.sh | |
| 12 | +# make clean | |
| 13 | + | |
| 14 | +CC ?= cc | |
| 15 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -Wno-format-truncation -I src | |
| 16 | +MUSL_CC ?= musl-gcc | |
| 17 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static | |
| 18 | +ARM_CC ?= aarch64-linux-gnu-gcc | |
| 19 | +ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static | |
| 20 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 21 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static | |
| 22 | +SRC := src/plugin_google_quota.c | |
| 23 | +UI_SRC := src/ui.html | |
| 24 | +UI_HDR := src/ui_html.h | |
| 25 | +BIN := plugin_google_quota | |
| 26 | +EXE := plugin_google_quota.exe | |
| 27 | + | |
| 28 | +.PHONY: all native musl arm64 win64 macos ui install test clean help | |
| 29 | + | |
| 30 | +all: native | |
| 31 | + | |
| 32 | +$(UI_HDR): $(UI_SRC) tools/gen_ui.py | |
| 33 | + @echo "==> regenerating $(UI_HDR)" | |
| 34 | + python3 tools/gen_ui.py | |
| 35 | + | |
| 36 | +ui: $(UI_HDR) | |
| 37 | + | |
| 38 | +native: $(BIN) | |
| 39 | + | |
| 40 | +$(BIN): $(SRC) $(UI_HDR) | |
| 41 | + @echo "==> native build ($(CC))" | |
| 42 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 43 | + | |
| 44 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | |
| 45 | +musl: $(SRC) $(UI_HDR) | |
| 46 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 47 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC) | |
| 48 | + | |
| 49 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | |
| 50 | +arm64: $(SRC) $(UI_HDR) | |
| 51 | + @echo "==> static arm64 build ($(ARM_CC))" | |
| 52 | + $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC) | |
| 53 | + | |
| 54 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | |
| 55 | +win64: $(SRC) $(UI_HDR) | |
| 56 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 57 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) | |
| 58 | + | |
| 59 | +# Apple clang build (run this on macOS) | |
| 60 | +macos: $(SRC) $(UI_HDR) | |
| 61 | + @echo "==> Apple clang build" | |
| 62 | + clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o $(BIN) $(SRC) | |
| 63 | + | |
| 64 | +install: $(BIN) | |
| 65 | + @dest="$${HOME}/.scorpiox/plugins"; [ -d /workspace ] && dest="/workspace/.scorpiox/plugins"; \ | |
| 66 | + mkdir -p "$$dest" && cp $(BIN) "$$dest/$(BIN)" && chmod 0755 "$$dest/$(BIN)" && \ | |
| 67 | + echo "==> installed $$dest/$(BIN)" | |
| 68 | + | |
| 69 | +test: $(BIN) | |
| 70 | + sh tests/run.sh | |
| 71 | + | |
| 72 | +clean: | |
| 73 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 \ | |
| 74 | + $(BIN).macos-arm64 $(BIN).macos-x86_64 | |
| 75 | + rm -rf bin tests/__pycache__ | |
| 76 | + | |
| 77 | +help: | |
| 78 | + @sed -n '2,14p' $(MAKEFILE_LIST) |
| 1 | 1 | new file mode 100644 |
| index 0000000..209efcb | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,77 @@ | ||
| 1 | +# plugin_google_quota — Google Antigravity Quotas for SCORPIOX BOT | |
| 2 | + | |
| 3 | +`plugin_google_quota` is a **zero-dependency C99 node plugin** for | |
| 4 | +[SCORPIOX BOT](https://bot.scorpiox.net). It reads the local Google Antigravity | |
| 5 | +account list (`antigravity_accounts.json`) and active selection | |
| 6 | +(`selected_account.txt`), queries per-model quota pools through the node's | |
| 7 | +`scorpiox-google-quota` CLI, and lets you switch the active account in one | |
| 8 | +click. | |
| 9 | + | |
| 10 | +* `--meta` -> `{"name":"google quota","desc":"Account quotas"}` | |
| 11 | +* `--version` -> `plugin_google_quota 1.0.0` | |
| 12 | +* Catalog slug `google-quota`, category `devtools` | |
| 13 | +* Public source: <https://plugingit.scorpiox.net/scorpiox-bot-plugin-google-quota.git> | |
| 14 | +* Prebuilt binaries: <https://dist.scorpiox.net/bot-plugins/google-quota/> | |
| 15 | + | |
| 16 | +--- | |
| 17 | + | |
| 18 | +## Why this plugin has no TLS code and no client secret | |
| 19 | + | |
| 20 | +Refreshing Google OAuth tokens and calling `cloudcode-pa` requires an OAuth | |
| 21 | +client identity and TLS. A public, clean-room repository must not carry an | |
| 22 | +OAuth client secret, so this plugin does not speak TLS at all. It drives the | |
| 23 | +node's own `scorpiox-google-quota` CLI (which ships with SCORPIOX CODE) and | |
| 24 | +reads the same credential files written by `scorpiox-antigravity-login`: | |
| 25 | + | |
| 26 | +| Path | Access | Purpose | | |
| 27 | +|---|---|---| | |
| 28 | +| `~/.config/google-accounts/antigravity_accounts.json` | Read-only | Account emails + `refresh_token` presence | | |
| 29 | +| `~/.config/google-accounts/selected_account.txt` | Read / Write | Active account email (updated on `switch`) | | |
| 30 | + | |
| 31 | +**No token is ever printed, logged or returned.** When reading | |
| 32 | +`antigravity_accounts.json`, only `email` and a boolean `has_refresh` flag are | |
| 33 | +extracted; token strings are never copied or emitted. | |
| 34 | + | |
| 35 | +--- | |
| 36 | + | |
| 37 | +## Requirements on the node | |
| 38 | + | |
| 39 | +| Platform | Needs | | |
| 40 | +|---|---| | |
| 41 | +| Linux / macOS / Windows | `scorpiox-google-quota` on `PATH` (ships with SCORPIOX CODE) | | |
| 42 | +| Build / runtime | Zero external library dependencies (pure C99 stdlib) | | |
| 43 | + | |
| 44 | +--- | |
| 45 | + | |
| 46 | +## Environment overrides | |
| 47 | + | |
| 48 | +| Variable | Effect | | |
| 49 | +|---|---| | |
| 50 | +| `GOOGLE_ACCOUNTS_FILE` | Path to `antigravity_accounts.json` (also accepts `ANTIGRAVITY_CREDS_PATH`) | | |
| 51 | +| `GOOGLE_SELECTED_FILE` | Path to `selected_account.txt` (default: sibling of `GOOGLE_ACCOUNTS_FILE`) | | |
| 52 | +| `GOOGLE_QUOTA_BIN` | Quota CLI binary (default: `scorpiox-google-quota`) | | |
| 53 | +| `BOT_PASSWORD` | When set, every route except `--meta` and `--version` requires it | | |
| 54 | + | |
| 55 | +--- | |
| 56 | + | |
| 57 | +## API | |
| 58 | + | |
| 59 | +All actions accept `X-Bot-Password`, `Authorization: Bearer`, or `?pwd=`. | |
| 60 | + | |
| 61 | +* `GET ?action=status` — fast local read of configured accounts, `selected`, paths, and `cli_present` | |
| 62 | +* `GET ?action=quota` (or `?format=json`) — queries all accounts concurrently and returns Gemini/Claude pool summaries, reset times, per-model buckets, `best_gemini`, and `best_claude` | |
| 63 | +* `GET ?action=quota&account=<email>` — queries a single account | |
| 64 | +* `GET/POST ?action=switch&account=<email>` (or JSON body `{"account":"..."}`) — validates the email against `antigravity_accounts.json` and writes `selected_account.txt` | |
| 65 | + | |
| 66 | +--- | |
| 67 | + | |
| 68 | +## Build, test & install | |
| 69 | + | |
| 70 | +```sh | |
| 71 | +make # build ./plugin_google_quota | |
| 72 | +make test # run offline test suite (tests/run.sh) | |
| 73 | +make install # install to ~/.scorpiox/plugins/ (or /workspace/.scorpiox/plugins/) | |
| 74 | +``` | |
| 75 | + | |
| 76 | +Cross-compile targets: `make musl`, `make arm64`, `make win64`, `make macos`, or | |
| 77 | +`powershell -ExecutionPolicy Bypass -File build.ps1` on Windows. |
| 1 | 1 | new file mode 100644 |
| index 0000000..bdc0406 | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,48 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_google_quota | |
| 2 | +# | |
| 3 | +# Usage (from the repo root, PowerShell): | |
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 5 | +# | |
| 6 | +# Produces .\plugin_google_quota.exe (static PE, runs on any Windows 10/11 x64 node). | |
| 7 | +# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin). | |
| 8 | + | |
| 9 | +$ErrorActionPreference = "Stop" | |
| 10 | +$ScriptDir = $PSScriptRoot | |
| 11 | +Push-Location $ScriptDir | |
| 12 | +try { | |
| 13 | + $Src = Join-Path $ScriptDir "src\plugin_google_quota.c" | |
| 14 | + $Out = Join-Path $ScriptDir "plugin_google_quota.exe" | |
| 15 | + $Cc = "x86_64-w64-mingw32-gcc" | |
| 16 | + | |
| 17 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | |
| 18 | + | |
| 19 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | |
| 20 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | |
| 21 | + $Cc = "C:\gcc16\bin\gcc.exe" | |
| 22 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | |
| 23 | + $Cc = "gcc" | |
| 24 | + } else { | |
| 25 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | |
| 26 | + } | |
| 27 | + } | |
| 28 | + | |
| 29 | + if (Get-Command python -ErrorAction SilentlyContinue) { | |
| 30 | + python tools\gen_ui.py | |
| 31 | + } | |
| 32 | + | |
| 33 | + Write-Host "==> building plugin_google_quota.exe with $Cc" | |
| 34 | + & $Cc -O2 -std=c99 -Wall -Wextra -I src -static -o $Out $Src | |
| 35 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | |
| 36 | + | |
| 37 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | |
| 38 | + | |
| 39 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | |
| 40 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | |
| 41 | + throw "output is not a PE executable (missing MZ header)" | |
| 42 | + } | |
| 43 | + | |
| 44 | + Write-Host "==> ok: $Out ($($bytes.Length) bytes)" | |
| 45 | + Write-Host " smoke test: .\plugin_google_quota.exe --meta" | |
| 46 | +} finally { | |
| 47 | + Pop-Location | |
| 48 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..58d102f | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,17 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "google-quota", | |
| 3 | + "id": "plugin_google_quota", | |
| 4 | + "title": "Google Account Quotas", | |
| 5 | + "summary": "Zero-dependency Google Antigravity multi-account quota monitor and active-account switcher for your node. Reads the local antigravity_accounts.json and selected_account.txt files, queries per-model quota pools through the node's scorpiox-google-quota CLI, and lets you switch the active account in one click. Holds no OAuth client secret and never prints, logs or returns any refresh or access token.", | |
| 6 | + "category": "devtools", | |
| 7 | + "license": "MIT", | |
| 8 | + "capabilities": [ | |
| 9 | + "spawn_quota_cli", | |
| 10 | + "read_credentials_metadata", | |
| 11 | + "write_selected_account", | |
| 12 | + "network_via_quota_cli" | |
| 13 | + ], | |
| 14 | + "trust_notice": "Executes native C code on your node. It runs scorpiox-google-quota (from SCORPIOX CODE) as a child process; that binary is what talks to Google over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only ~/.config/google-accounts/antigravity_accounts.json (email and token presence only) and selected_account.txt, writes only selected_account.txt on switch, and never prints or returns any token value.", | |
| 15 | + "author": "SCORPIOX INC", | |
| 16 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-google-quota" | |
| 17 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..0bdcbd5 | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,13 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# release-dist.sh - audit, build and publish plugin_google_quota via scorpiox-cli-botplugin. | |
| 3 | +set -euo pipefail | |
| 4 | + | |
| 5 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | |
| 6 | +cd "$ROOT" | |
| 7 | + | |
| 8 | +if ! command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 9 | + echo "error: scorpiox-cli-botplugin is required to publish" >&2 | |
| 10 | + exit 1 | |
| 11 | +fi | |
| 12 | + | |
| 13 | +exec scorpiox-cli-botplugin publish "$ROOT" "$@" |
| 1 | 1 | new file mode 100644 |
| index 0000000..0dd243b | ||
| --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | ||
| 1 | +/* | |
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | |
| 3 | + * | |
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | |
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | |
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | |
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | |
| 8 | + * localStorage key, same prepaint order. | |
| 9 | + * | |
| 10 | + * Three rules, and nothing else: | |
| 11 | + * | |
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | |
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | |
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | |
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | |
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | |
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | |
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | |
| 19 | + * it was already open when the bot changed theme. | |
| 20 | + * | |
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | |
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | |
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | |
| 24 | + * are var() references, one definition covers both themes. | |
| 25 | + * | |
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 27 | + */ | |
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | |
| 29 | +#define SX_BOT_THEME_PLUGIN_H | |
| 30 | + | |
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | |
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | |
| 33 | +#define SX_BOT_THEME_TOKENS \ | |
| 34 | +":root{color-scheme:dark;" \ | |
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | |
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | |
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | |
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | |
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | |
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | |
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | |
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | |
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | |
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | |
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | |
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | |
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | |
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | |
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | |
| 50 | +"}" \ | |
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | |
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 58 | + "--accent-dim:#0066d6;" \ | |
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 62 | + "color-scheme:light}}" \ | |
| 63 | +"html[data-theme=light]{" \ | |
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 70 | + "--accent-dim:#0066d6;" \ | |
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 74 | + "color-scheme:light}" \ | |
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | |
| 76 | +"*{box-sizing:border-box}" \ | |
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | |
| 78 | + "-webkit-font-smoothing:antialiased}" \ | |
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | |
| 80 | +"button:active{transform:scale(.98)}" \ | |
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | |
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | |
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | |
| 84 | +" * hides its own back link and its own toggle. */" \ | |
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | |
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | |
| 87 | + | |
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | |
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | |
| 90 | + * html.embedded so the embed rules apply before first paint. */ | |
| 91 | +#define SX_BOT_THEME_PREPAINT \ | |
| 92 | +"<script>(function(){var t='';" \ | |
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | |
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | |
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | |
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | |
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 99 | +"})();</script>\n" | |
| 100 | + | |
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | |
| 102 | + * at startup in case it changed while this page was already open. Fires the | |
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | |
| 104 | + * re-skin themselves from one listener. */ | |
| 105 | +#define SX_BOT_THEME_HANDOFF \ | |
| 106 | +"<script>(function(){" \ | |
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | |
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | |
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | |
| 112 | +"window.sxApplyTheme=apply;" \ | |
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | |
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | |
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | |
| 116 | +"})();</script>\n" | |
| 117 | + | |
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | |
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | |
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | |
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | |
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | |
| 123 | + | |
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | |
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | |
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | |
| 127 | +"})();</script>\n" | |
| 128 | + | |
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..97e4490 | ||
| --- /dev/null | ||
| +++ b/src/plugin_google_quota.c | ||
| @@ -0,0 +1,1542 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_google_quota - SCORPIOX BOT open-source Google Antigravity | |
| 3 | + * multi-account quota monitor and active-account switcher for your node. | |
| 4 | + * | |
| 5 | + * A single clean-room C99 binary that serves THREE modes: | |
| 6 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata | |
| 7 | + * 2. ?action=... / ?format=json -> JSON node API | |
| 8 | + * 3. GET (default) -> responsive HTML UI | |
| 9 | + * | |
| 10 | + * DESIGN NOTE (why there is no TLS and no OAuth client secret here): | |
| 11 | + * Refreshing Google OAuth tokens and calling cloudcode-pa requires an OAuth | |
| 12 | + * client identity and TLS. A public clean-room repository must never carry an | |
| 13 | + * OAuth client secret, so this plugin does not speak TLS at all. It reads the | |
| 14 | + * local account list and active selection files written by | |
| 15 | + * scorpiox-antigravity-login and invokes the node's scorpiox-google-quota CLI: | |
| 16 | + * | |
| 17 | + * ~/.config/google-accounts/antigravity_accounts.json (emails + presence) | |
| 18 | + * ~/.config/google-accounts/selected_account.txt (active email) | |
| 19 | + * | |
| 20 | + * Every path and the quota CLI can be overridden for testing or relocation: | |
| 21 | + * | |
| 22 | + * GOOGLE_ACCOUNTS_FILE accounts JSON (also accepts ANTIGRAVITY_CREDS_PATH) | |
| 23 | + * GOOGLE_SELECTED_FILE selected account file (default: sibling selected_account.txt) | |
| 24 | + * GOOGLE_QUOTA_BIN quota CLI binary (default: scorpiox-google-quota) | |
| 25 | + * | |
| 26 | + * NO TOKEN IS EVER PRINTED, LOGGED OR RETURNED. When reading | |
| 27 | + * antigravity_accounts.json, only email and refresh_token presence (boolean) | |
| 28 | + * are recorded; token strings are never copied or emitted. | |
| 29 | + * | |
| 30 | + * Zero external dependencies. Builds with gcc, musl-gcc -static, Apple clang | |
| 31 | + * and x86_64-w64-mingw32-gcc -static. | |
| 32 | + * | |
| 33 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 34 | + */ | |
| 35 | + | |
| 36 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 37 | +# define _WIN32_WINNT 0x0601 | |
| 38 | +#endif | |
| 39 | + | |
| 40 | +#if !defined(_WIN32) | |
| 41 | +# define _POSIX_C_SOURCE 200809L | |
| 42 | +# define _DEFAULT_SOURCE 1 | |
| 43 | +# if defined(__APPLE__) | |
| 44 | +# define _DARWIN_C_SOURCE 1 | |
| 45 | +# endif | |
| 46 | +#endif | |
| 47 | + | |
| 48 | +#include <stdio.h> | |
| 49 | +#include <stdlib.h> | |
| 50 | +#include <string.h> | |
| 51 | +#include <ctype.h> | |
| 52 | +#include <errno.h> | |
| 53 | +#include <stdarg.h> | |
| 54 | + | |
| 55 | +#if defined(_WIN32) | |
| 56 | +# define WIN32_LEAN_AND_MEAN | |
| 57 | +# include <windows.h> | |
| 58 | +# include <direct.h> | |
| 59 | +# include <io.h> | |
| 60 | +# define popen _popen | |
| 61 | +# define pclose _pclose | |
| 62 | +# define PATH_SEP '\\' | |
| 63 | +#else | |
| 64 | +# include <unistd.h> | |
| 65 | +# include <fcntl.h> | |
| 66 | +# include <poll.h> | |
| 67 | +# include <sys/stat.h> | |
| 68 | +# include <sys/types.h> | |
| 69 | +# include <sys/wait.h> | |
| 70 | +# define PATH_SEP '/' | |
| 71 | +#endif | |
| 72 | + | |
| 73 | +#include "bot_theme_plugin.h" | |
| 74 | +#include "ui_html.h" | |
| 75 | + | |
| 76 | +#define PLUGIN_SLUG "google-quota" | |
| 77 | +#define PLUGIN_ID "plugin_google_quota" | |
| 78 | +#define PLUGIN_VER "1.0.0" | |
| 79 | +#define PLUGIN_NAME "google quota" | |
| 80 | +#define PLUGIN_DESC "Account quotas" | |
| 81 | + | |
| 82 | +#define DEFAULT_QUOTA_BIN "scorpiox-google-quota" | |
| 83 | + | |
| 84 | +#define PATH_SZ 1024 | |
| 85 | +#define EMAIL_SZ 256 | |
| 86 | +#define PROJ_SZ 256 | |
| 87 | +#define MODEL_SZ 128 | |
| 88 | +#define RESET_SZ 64 | |
| 89 | +#define CMD_SZ 4096 | |
| 90 | +#define FIELD_SZ 512 | |
| 91 | +#define OUT_MAX (512 * 1024) | |
| 92 | +#define MAX_ACCOUNTS 64 | |
| 93 | +#define MAX_MODELS 64 | |
| 94 | +#define MAX_WORKERS 8 | |
| 95 | + | |
| 96 | +/* ------------------------------------------------------------------ */ | |
| 97 | +/* Growable byte buffer */ | |
| 98 | +/* ------------------------------------------------------------------ */ | |
| 99 | + | |
| 100 | +typedef struct { | |
| 101 | + char *p; | |
| 102 | + size_t n; | |
| 103 | + size_t cap; | |
| 104 | +} buf_t; | |
| 105 | + | |
| 106 | +static void buf_init(buf_t *b) | |
| 107 | +{ | |
| 108 | + b->p = NULL; | |
| 109 | + b->n = 0; | |
| 110 | + b->cap = 0; | |
| 111 | +} | |
| 112 | + | |
| 113 | +static int buf_need(buf_t *b, size_t extra) | |
| 114 | +{ | |
| 115 | + size_t want = b->n + extra + 1; | |
| 116 | + char *np; | |
| 117 | + | |
| 118 | + if (want <= b->cap) return 1; | |
| 119 | + if (b->cap == 0) b->cap = 1024; | |
| 120 | + while (b->cap < want) { | |
| 121 | + if (b->cap > (size_t)32 * 1024 * 1024) return 0; | |
| 122 | + b->cap *= 2; | |
| 123 | + } | |
| 124 | + np = (char *)realloc(b->p, b->cap); | |
| 125 | + if (!np) return 0; | |
| 126 | + b->p = np; | |
| 127 | + return 1; | |
| 128 | +} | |
| 129 | + | |
| 130 | +static int buf_add(buf_t *b, const char *s, size_t len) | |
| 131 | +{ | |
| 132 | + if (!s || len == 0) return 1; | |
| 133 | + if (!buf_need(b, len)) return 0; | |
| 134 | + memcpy(b->p + b->n, s, len); | |
| 135 | + b->n += len; | |
| 136 | + b->p[b->n] = '\0'; | |
| 137 | + return 1; | |
| 138 | +} | |
| 139 | + | |
| 140 | +static int buf_adds(buf_t *b, const char *s) | |
| 141 | +{ | |
| 142 | + return s ? buf_add(b, s, strlen(s)) : 1; | |
| 143 | +} | |
| 144 | + | |
| 145 | +static int buf_addc(buf_t *b, char c) | |
| 146 | +{ | |
| 147 | + return buf_add(b, &c, 1); | |
| 148 | +} | |
| 149 | + | |
| 150 | +static int buf_addf(buf_t *b, const char *fmt, ...) | |
| 151 | +{ | |
| 152 | + char tmp[2048]; | |
| 153 | + int n; | |
| 154 | + va_list ap; | |
| 155 | + | |
| 156 | + va_start(ap, fmt); | |
| 157 | + n = vsnprintf(tmp, sizeof(tmp), fmt, ap); | |
| 158 | + va_end(ap); | |
| 159 | + if (n < 0) return 0; | |
| 160 | + if ((size_t)n < sizeof(tmp)) return buf_add(b, tmp, (size_t)n); | |
| 161 | + | |
| 162 | + { | |
| 163 | + char *big = (char *)malloc((size_t)n + 1); | |
| 164 | + int ok; | |
| 165 | + if (!big) return 0; | |
| 166 | + va_start(ap, fmt); | |
| 167 | + vsnprintf(big, (size_t)n + 1, fmt, ap); | |
| 168 | + va_end(ap); | |
| 169 | + ok = buf_add(b, big, (size_t)n); | |
| 170 | + free(big); | |
| 171 | + return ok; | |
| 172 | + } | |
| 173 | +} | |
| 174 | + | |
| 175 | +static int buf_json(buf_t *b, const char *s) | |
| 176 | +{ | |
| 177 | + const unsigned char *p = (const unsigned char *)(s ? s : ""); | |
| 178 | + if (!buf_addc(b, '"')) return 0; | |
| 179 | + for (; *p; p++) { | |
| 180 | + switch (*p) { | |
| 181 | + case '"': if (!buf_adds(b, "\\\"")) return 0; break; | |
| 182 | + case '\\': if (!buf_adds(b, "\\\\")) return 0; break; | |
| 183 | + case '\n': if (!buf_adds(b, "\\n")) return 0; break; | |
| 184 | + case '\r': if (!buf_adds(b, "\\r")) return 0; break; | |
| 185 | + case '\t': if (!buf_adds(b, "\\t")) return 0; break; | |
| 186 | + default: | |
| 187 | + if (*p < 0x20) { | |
| 188 | + if (!buf_addf(b, "\\u%04x", (unsigned)*p)) return 0; | |
| 189 | + } else { | |
| 190 | + if (!buf_addc(b, (char)*p)) return 0; | |
| 191 | + } | |
| 192 | + } | |
| 193 | + } | |
| 194 | + return buf_addc(b, '"'); | |
| 195 | +} | |
| 196 | + | |
| 197 | +static const char *buf_str(const buf_t *b) | |
| 198 | +{ | |
| 199 | + return b->p ? b->p : ""; | |
| 200 | +} | |
| 201 | + | |
| 202 | +static void buf_free(buf_t *b) | |
| 203 | +{ | |
| 204 | + free(b->p); | |
| 205 | + b->p = NULL; | |
| 206 | + b->n = 0; | |
| 207 | + b->cap = 0; | |
| 208 | +} | |
| 209 | + | |
| 210 | +/* ------------------------------------------------------------------ */ | |
| 211 | +/* String, query & env helpers */ | |
| 212 | +/* ------------------------------------------------------------------ */ | |
| 213 | + | |
| 214 | +static int ascii_strncasecmp(const char *a, const char *b, size_t n) | |
| 215 | +{ | |
| 216 | + size_t i; | |
| 217 | + for (i = 0; i < n; i++) { | |
| 218 | + unsigned char ca = (unsigned char)a[i]; | |
| 219 | + unsigned char cb = (unsigned char)b[i]; | |
| 220 | + int da = tolower(ca); | |
| 221 | + int db = tolower(cb); | |
| 222 | + if (da != db) return da - db; | |
| 223 | + if (ca == '\0') return 0; | |
| 224 | + } | |
| 225 | + return 0; | |
| 226 | +} | |
| 227 | + | |
| 228 | +static void trim_tail(char *s) | |
| 229 | +{ | |
| 230 | + size_t n; | |
| 231 | + if (!s) return; | |
| 232 | + n = strlen(s); | |
| 233 | + while (n > 0 && (s[n - 1] == ' ' || s[n - 1] == '\t' || | |
| 234 | + s[n - 1] == '\r' || s[n - 1] == '\n')) { | |
| 235 | + s[--n] = '\0'; | |
| 236 | + } | |
| 237 | +} | |
| 238 | + | |
| 239 | +static void url_decode(char *s) | |
| 240 | +{ | |
| 241 | + char *w = s; | |
| 242 | + char *r = s; | |
| 243 | + if (!s) return; | |
| 244 | + while (*r) { | |
| 245 | + if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) { | |
| 246 | + int hi = isdigit((unsigned char)r[1]) ? r[1] - '0' : tolower((unsigned char)r[1]) - 'a' + 10; | |
| 247 | + int lo = isdigit((unsigned char)r[2]) ? r[2] - '0' : tolower((unsigned char)r[2]) - 'a' + 10; | |
| 248 | + *w++ = (char)((hi << 4) | lo); | |
| 249 | + r += 3; | |
| 250 | + } else if (*r == '+') { | |
| 251 | + *w++ = ' '; | |
| 252 | + r++; | |
| 253 | + } else { | |
| 254 | + *w++ = *r++; | |
| 255 | + } | |
| 256 | + } | |
| 257 | + *w = '\0'; | |
| 258 | +} | |
| 259 | + | |
| 260 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 261 | +{ | |
| 262 | + size_t klen; | |
| 263 | + const char *p; | |
| 264 | + | |
| 265 | + if (!out || outsz == 0) return 0; | |
| 266 | + out[0] = '\0'; | |
| 267 | + if (!qs || !key) return 0; | |
| 268 | + klen = strlen(key); | |
| 269 | + p = qs; | |
| 270 | + while (*p) { | |
| 271 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 272 | + size_t i = 0; | |
| 273 | + p += klen + 1; | |
| 274 | + while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; | |
| 275 | + out[i] = '\0'; | |
| 276 | + url_decode(out); | |
| 277 | + return 1; | |
| 278 | + } | |
| 279 | + p = strchr(p, '&'); | |
| 280 | + if (!p) break; | |
| 281 | + p++; | |
| 282 | + } | |
| 283 | + return 0; | |
| 284 | +} | |
| 285 | + | |
| 286 | +static int query_has(const char *qs, const char *key) | |
| 287 | +{ | |
| 288 | + size_t klen; | |
| 289 | + const char *p; | |
| 290 | + | |
| 291 | + if (!qs || !key) return 0; | |
| 292 | + klen = strlen(key); | |
| 293 | + p = qs; | |
| 294 | + while (p && *p) { | |
| 295 | + if (strncmp(p, key, klen) == 0 && (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&')) | |
| 296 | + return 1; | |
| 297 | + p = strchr(p, '&'); | |
| 298 | + if (!p) break; | |
| 299 | + p++; | |
| 300 | + } | |
| 301 | + return 0; | |
| 302 | +} | |
| 303 | + | |
| 304 | +static void set_env_var(const char *k, const char *v) | |
| 305 | +{ | |
| 306 | +#if defined(_WIN32) | |
| 307 | + _putenv_s(k, v ? v : ""); | |
| 308 | +#else | |
| 309 | + setenv(k, v ? v : "", 1); | |
| 310 | +#endif | |
| 311 | +} | |
| 312 | + | |
| 313 | +static void unset_env_var(const char *k) | |
| 314 | +{ | |
| 315 | +#if defined(_WIN32) | |
| 316 | + _putenv_s(k, ""); | |
| 317 | +#else | |
| 318 | + unsetenv(k); | |
| 319 | +#endif | |
| 320 | +} | |
| 321 | + | |
| 322 | +/* ------------------------------------------------------------------ */ | |
| 323 | +/* Node auth (X-Bot-Password / Bearer / ?pwd=) */ | |
| 324 | +/* ------------------------------------------------------------------ */ | |
| 325 | + | |
| 326 | +static void require_node_auth(void) | |
| 327 | +{ | |
| 328 | + const char *np = getenv("BOT_PASSWORD"); | |
| 329 | + const char *xp; | |
| 330 | + const char *auth; | |
| 331 | + char qpwd[256] = {0}; | |
| 332 | + | |
| 333 | + if (!np || !*np) return; | |
| 334 | + | |
| 335 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 336 | + if (xp && strcmp(xp, np) == 0) return; | |
| 337 | + | |
| 338 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 339 | + if (auth) { | |
| 340 | + while (*auth == ' ') auth++; | |
| 341 | + if (ascii_strncasecmp(auth, "Bearer ", 7) == 0) { | |
| 342 | + auth += 7; | |
| 343 | + while (*auth == ' ') auth++; | |
| 344 | + if (strcmp(auth, np) == 0) return; | |
| 345 | + } | |
| 346 | + } | |
| 347 | + | |
| 348 | + if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) && | |
| 349 | + strcmp(qpwd, np) == 0) return; | |
| 350 | + | |
| 351 | + fputs("Status: 401 Unauthorized\r\n" | |
| 352 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 353 | + "Cache-Control: no-store\r\n\r\n" | |
| 354 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 355 | + exit(0); | |
| 356 | +} | |
| 357 | + | |
| 358 | +/* ------------------------------------------------------------------ */ | |
| 359 | +/* Paths & files */ | |
| 360 | +/* ------------------------------------------------------------------ */ | |
| 361 | + | |
| 362 | +static const char *home_dir(void) | |
| 363 | +{ | |
| 364 | +#ifdef _WIN32 | |
| 365 | + static char home[512]; | |
| 366 | + DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)); | |
| 367 | + if (n > 0 && n < sizeof(home)) return home; | |
| 368 | + { | |
| 369 | + const char *h = getenv("USERPROFILE"); | |
| 370 | + if (h && *h) return h; | |
| 371 | + h = getenv("HOME"); | |
| 372 | + return (h && *h) ? h : NULL; | |
| 373 | + } | |
| 374 | +#else | |
| 375 | + const char *h = getenv("HOME"); | |
| 376 | + return (h && *h) ? h : NULL; | |
| 377 | +#endif | |
| 378 | +} | |
| 379 | + | |
| 380 | +static void accounts_path(char *out, size_t n) | |
| 381 | +{ | |
| 382 | + const char *env = getenv("GOOGLE_ACCOUNTS_FILE"); | |
| 383 | + const char *home; | |
| 384 | + | |
| 385 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | |
| 386 | + env = getenv("ANTIGRAVITY_CREDS_PATH"); | |
| 387 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | |
| 388 | + | |
| 389 | + home = home_dir(); | |
| 390 | + if (!home) { snprintf(out, n, "antigravity_accounts.json"); return; } | |
| 391 | + snprintf(out, n, "%s%c.config%cgoogle-accounts%cantigravity_accounts.json", | |
| 392 | + home, PATH_SEP, PATH_SEP, PATH_SEP); | |
| 393 | +} | |
| 394 | + | |
| 395 | +static void selected_path(char *out, size_t n) | |
| 396 | +{ | |
| 397 | + const char *env = getenv("GOOGLE_SELECTED_FILE"); | |
| 398 | + char base[PATH_SZ]; | |
| 399 | + char *slash; | |
| 400 | + | |
| 401 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | |
| 402 | + | |
| 403 | + accounts_path(base, sizeof(base)); | |
| 404 | + slash = strrchr(base, PATH_SEP); | |
| 405 | + if (!slash) slash = strrchr(base, '/'); | |
| 406 | + if (!slash) { snprintf(out, n, "selected_account.txt"); return; } | |
| 407 | + *(slash + 1) = '\0'; | |
| 408 | + snprintf(out, n, "%sselected_account.txt", base); | |
| 409 | +} | |
| 410 | + | |
| 411 | +static const char *quota_bin(void) | |
| 412 | +{ | |
| 413 | + const char *b = getenv("GOOGLE_QUOTA_BIN"); | |
| 414 | + return (b && *b) ? b : DEFAULT_QUOTA_BIN; | |
| 415 | +} | |
| 416 | + | |
| 417 | +#if defined(_WIN32) | |
| 418 | +static int file_exists(const char *p) | |
| 419 | +{ | |
| 420 | + DWORD a = GetFileAttributesA(p); | |
| 421 | + return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); | |
| 422 | +} | |
| 423 | +#endif | |
| 424 | + | |
| 425 | +static int bin_available(const char *bin) | |
| 426 | +{ | |
| 427 | + if (!bin || !*bin) return 0; | |
| 428 | +#if defined(_WIN32) | |
| 429 | + { | |
| 430 | + char full[MAX_PATH]; | |
| 431 | + DWORD n; | |
| 432 | + if (strchr(bin, '\\') || strchr(bin, '/') || strchr(bin, ':')) | |
| 433 | + return file_exists(bin); | |
| 434 | + n = SearchPathA(NULL, bin, ".exe", (DWORD)sizeof(full), full, NULL); | |
| 435 | + return n > 0 && n < (DWORD)sizeof(full); | |
| 436 | + } | |
| 437 | +#else | |
| 438 | + if (strchr(bin, '/')) { | |
| 439 | + struct stat st; | |
| 440 | + return stat(bin, &st) == 0 && S_ISREG(st.st_mode) && access(bin, X_OK) == 0; | |
| 441 | + } | |
| 442 | + { | |
| 443 | + const char *path_env = getenv("PATH"); | |
| 444 | + const char *p; | |
| 445 | + if (!path_env || !*path_env) return 0; | |
| 446 | + p = path_env; | |
| 447 | + while (*p) { | |
| 448 | + const char *colon = strchr(p, ':'); | |
| 449 | + size_t dlen = colon ? (size_t)(colon - p) : strlen(p); | |
| 450 | + char cand[PATH_SZ]; | |
| 451 | + if (dlen > 0 && dlen + 1 + strlen(bin) + 1 < sizeof(cand)) { | |
| 452 | + struct stat st; | |
| 453 | + memcpy(cand, p, dlen); | |
| 454 | + cand[dlen] = '/'; | |
| 455 | + strcpy(cand + dlen + 1, bin); | |
| 456 | + if (stat(cand, &st) == 0 && S_ISREG(st.st_mode) && access(cand, X_OK) == 0) | |
| 457 | + return 1; | |
| 458 | + } | |
| 459 | + if (!colon) break; | |
| 460 | + p = colon + 1; | |
| 461 | + } | |
| 462 | + return 0; | |
| 463 | + } | |
| 464 | +#endif | |
| 465 | +} | |
| 466 | + | |
| 467 | +static char *read_file(const char *path) | |
| 468 | +{ | |
| 469 | + FILE *f; | |
| 470 | + long sz; | |
| 471 | + char *buf; | |
| 472 | + | |
| 473 | + if (!path || !*path) return NULL; | |
| 474 | + f = fopen(path, "rb"); | |
| 475 | + if (!f) return NULL; | |
| 476 | + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } | |
| 477 | + sz = ftell(f); | |
| 478 | + if (sz < 0 || sz > 4 * 1024 * 1024) { fclose(f); return NULL; } | |
| 479 | + rewind(f); | |
| 480 | + buf = (char *)malloc((size_t)sz + 1); | |
| 481 | + if (!buf) { fclose(f); return NULL; } | |
| 482 | + if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) { | |
| 483 | + free(buf); | |
| 484 | + fclose(f); | |
| 485 | + return NULL; | |
| 486 | + } | |
| 487 | + buf[sz] = '\0'; | |
| 488 | + fclose(f); | |
| 489 | + return buf; | |
| 490 | +} | |
| 491 | + | |
| 492 | +/* ------------------------------------------------------------------ */ | |
| 493 | +/* Minimal JSON scanner (read-only, zero dependencies) */ | |
| 494 | +/* ------------------------------------------------------------------ */ | |
| 495 | + | |
| 496 | +static const char *json_skip_ws(const char *p, const char *end) | |
| 497 | +{ | |
| 498 | + while (p && p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; | |
| 499 | + return p; | |
| 500 | +} | |
| 501 | + | |
| 502 | +static const char *json_skip_value(const char *p) | |
| 503 | +{ | |
| 504 | + int depth = 0; | |
| 505 | + int in_str = 0; | |
| 506 | + | |
| 507 | + if (!p) return NULL; | |
| 508 | + while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; | |
| 509 | + if (!*p) return NULL; | |
| 510 | + | |
| 511 | + if (*p != '{' && *p != '[' && *p != '"') { | |
| 512 | + while (*p && *p != ',' && *p != '}' && *p != ']' && | |
| 513 | + *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r') p++; | |
| 514 | + return p; | |
| 515 | + } | |
| 516 | + | |
| 517 | + for (; *p; p++) { | |
| 518 | + if (in_str) { | |
| 519 | + if (*p == '\\' && p[1]) { p++; continue; } | |
| 520 | + if (*p == '"') { | |
| 521 | + in_str = 0; | |
| 522 | + if (depth == 0) return p + 1; | |
| 523 | + } | |
| 524 | + continue; | |
| 525 | + } | |
| 526 | + if (*p == '"') { in_str = 1; continue; } | |
| 527 | + if (*p == '{' || *p == '[') { depth++; continue; } | |
| 528 | + if (*p == '}' || *p == ']') { | |
| 529 | + depth--; | |
| 530 | + if (depth <= 0) return p + 1; | |
| 531 | + } | |
| 532 | + } | |
| 533 | + return p; | |
| 534 | +} | |
| 535 | + | |
| 536 | +static int json_read_string_at(const char **pp, char *out, size_t outsz) | |
| 537 | +{ | |
| 538 | + const char *p = *pp; | |
| 539 | + size_t o = 0; | |
| 540 | + | |
| 541 | + if (!p || *p != '"') return 0; | |
| 542 | + p++; | |
| 543 | + while (*p && *p != '"') { | |
| 544 | + unsigned char c = (unsigned char)*p++; | |
| 545 | + if (c == '\\' && *p) { | |
| 546 | + char e = *p++; | |
| 547 | + switch (e) { | |
| 548 | + case '"': c = '"'; break; | |
| 549 | + case '\\': c = '\\'; break; | |
| 550 | + case '/': c = '/'; break; | |
| 551 | + case 'n': c = '\n'; break; | |
| 552 | + case 'r': c = '\r'; break; | |
| 553 | + case 't': c = '\t'; break; | |
| 554 | + default: c = (unsigned char)e; break; | |
| 555 | + } | |
| 556 | + } | |
| 557 | + if (o + 1 < outsz) out[o++] = (char)c; | |
| 558 | + } | |
| 559 | + if (*p == '"') p++; | |
| 560 | + out[o] = '\0'; | |
| 561 | + *pp = p; | |
| 562 | + return 1; | |
| 563 | +} | |
| 564 | + | |
| 565 | +static const char *json_find_key(const char *obj, const char *end, const char *key) | |
| 566 | +{ | |
| 567 | + const char *p = obj; | |
| 568 | + size_t klen = strlen(key); | |
| 569 | + int depth = 0; | |
| 570 | + | |
| 571 | + p = json_skip_ws(p, end); | |
| 572 | + if (p < end && *p == '{') p++; | |
| 573 | + | |
| 574 | + while (p && p < end) { | |
| 575 | + if (*p == '"') { | |
| 576 | + char name[128]; | |
| 577 | + json_read_string_at(&p, name, sizeof(name)); | |
| 578 | + if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) { | |
| 579 | + const char *q = json_skip_ws(p, end); | |
| 580 | + if (q < end && *q == ':') { | |
| 581 | + q = json_skip_ws(q + 1, end); | |
| 582 | + return (q < end) ? q : NULL; | |
| 583 | + } | |
| 584 | + } | |
| 585 | + continue; | |
| 586 | + } | |
| 587 | + if (*p == '{' || *p == '[') depth++; | |
| 588 | + else if (*p == '}' || *p == ']') depth--; | |
| 589 | + p++; | |
| 590 | + } | |
| 591 | + return NULL; | |
| 592 | +} | |
| 593 | + | |
| 594 | +static int json_str_field(const char *obj, const char *end, const char *key, | |
| 595 | + char *out, size_t outsz) | |
| 596 | +{ | |
| 597 | + const char *v; | |
| 598 | + | |
| 599 | + if (!out || outsz == 0) return 0; | |
| 600 | + v = json_find_key(obj, end, key); | |
| 601 | + if (!v || *v == 'n') return 0; | |
| 602 | + out[0] = '\0'; | |
| 603 | + if (*v == '"') return json_read_string_at(&v, out, outsz); | |
| 604 | + { | |
| 605 | + size_t i = 0; | |
| 606 | + while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++; | |
| 607 | + out[i] = '\0'; | |
| 608 | + trim_tail(out); | |
| 609 | + return out[0] ? 1 : 0; | |
| 610 | + } | |
| 611 | +} | |
| 612 | + | |
| 613 | +static int json_bool_field(const char *obj, const char *end, const char *key, int dflt) | |
| 614 | +{ | |
| 615 | + const char *v = json_find_key(obj, end, key); | |
| 616 | + if (!v) return dflt; | |
| 617 | + if (strncmp(v, "true", 4) == 0) return 1; | |
| 618 | + if (strncmp(v, "false", 5) == 0) return 0; | |
| 619 | + if (*v == '1') return 1; | |
| 620 | + return 0; | |
| 621 | +} | |
| 622 | + | |
| 623 | +/* Returns 1 if numeric value parsed into *out, 0 if missing or null. */ | |
| 624 | +static int json_double_field(const char *obj, const char *end, const char *key, double *out) | |
| 625 | +{ | |
| 626 | + const char *v = json_find_key(obj, end, key); | |
| 627 | + char *ep = NULL; | |
| 628 | + double val; | |
| 629 | + | |
| 630 | + if (!v || *v == 'n') return 0; | |
| 631 | + if (*v != '-' && !isdigit((unsigned char)*v) && *v != '.') return 0; | |
| 632 | + val = strtod(v, &ep); | |
| 633 | + if (ep == v) return 0; | |
| 634 | + *out = val; | |
| 635 | + return 1; | |
| 636 | +} | |
| 637 | + | |
| 638 | +/* ------------------------------------------------------------------ */ | |
| 639 | +/* Account list loading (never copies refresh_token) */ | |
| 640 | +/* ------------------------------------------------------------------ */ | |
| 641 | + | |
| 642 | +typedef struct { | |
| 643 | + char email[EMAIL_SZ]; | |
| 644 | + int has_refresh; | |
| 645 | + int selected; | |
| 646 | +} acct_entry_t; | |
| 647 | + | |
| 648 | +static int is_safe_email(const char *s) | |
| 649 | +{ | |
| 650 | + int has_at = 0; | |
| 651 | + const char *p; | |
| 652 | + | |
| 653 | + if (!s || !*s || strlen(s) >= EMAIL_SZ) return 0; | |
| 654 | + for (p = s; *p; p++) { | |
| 655 | + unsigned char c = (unsigned char)*p; | |
| 656 | + if (c == '@') { has_at = 1; continue; } | |
| 657 | + if (isalnum(c) || c == '.' || c == '_' || c == '-' || c == '+') continue; | |
| 658 | + return 0; | |
| 659 | + } | |
| 660 | + return has_at; | |
| 661 | +} | |
| 662 | + | |
| 663 | +static int load_accounts(acct_entry_t *list, int max_n, char *selected_out, size_t sel_sz) | |
| 664 | +{ | |
| 665 | + char apath[PATH_SZ], spath[PATH_SZ]; | |
| 666 | + char *raw_sel, *raw_accts; | |
| 667 | + int count = 0; | |
| 668 | + | |
| 669 | + selected_out[0] = '\0'; | |
| 670 | + selected_path(spath, sizeof(spath)); | |
| 671 | + raw_sel = read_file(spath); | |
| 672 | + if (raw_sel) { | |
| 673 | + trim_tail(raw_sel); | |
| 674 | + if (is_safe_email(raw_sel)) snprintf(selected_out, sel_sz, "%s", raw_sel); | |
| 675 | + free(raw_sel); | |
| 676 | + } | |
| 677 | + | |
| 678 | + accounts_path(apath, sizeof(apath)); | |
| 679 | + raw_accts = read_file(apath); | |
| 680 | + if (!raw_accts) return 0; | |
| 681 | + | |
| 682 | + { | |
| 683 | + const char *p = raw_accts; | |
| 684 | + while (p && *p && count < max_n) { | |
| 685 | + const char *open = strchr(p, '{'); | |
| 686 | + const char *end; | |
| 687 | + char email[EMAIL_SZ] = {0}; | |
| 688 | + char rt_probe[8] = {0}; | |
| 689 | + int has_rt = 0; | |
| 690 | + int dup = 0; | |
| 691 | + int i; | |
| 692 | + | |
| 693 | + if (!open) break; | |
| 694 | + end = json_skip_value(open); | |
| 695 | + if (!end || end <= open) break; | |
| 696 | + | |
| 697 | + json_str_field(open, end, "email", email, sizeof(email)); | |
| 698 | + /* Presence check only: never copy or retain the refresh token. */ | |
| 699 | + if (json_str_field(open, end, "refresh_token", rt_probe, sizeof(rt_probe)) && rt_probe[0]) | |
| 700 | + has_rt = 1; | |
| 701 | + | |
| 702 | + if (is_safe_email(email)) { | |
| 703 | + for (i = 0; i < count; i++) { | |
| 704 | + if (strcmp(list[i].email, email) == 0) { | |
| 705 | + if (has_rt) list[i].has_refresh = 1; | |
| 706 | + dup = 1; | |
| 707 | + break; | |
| 708 | + } | |
| 709 | + } | |
| 710 | + if (!dup) { | |
| 711 | + snprintf(list[count].email, sizeof(list[count].email), "%s", email); | |
| 712 | + list[count].has_refresh = has_rt; | |
| 713 | + list[count].selected = (selected_out[0] && strcmp(selected_out, email) == 0) ? 1 : 0; | |
| 714 | + count++; | |
| 715 | + } | |
| 716 | + } | |
| 717 | + p = end; | |
| 718 | + } | |
| 719 | + } | |
| 720 | + | |
| 721 | + free(raw_accts); | |
| 722 | + return count; | |
| 723 | +} | |
| 724 | + | |
| 725 | +/* ------------------------------------------------------------------ */ | |
| 726 | +/* Child process execution */ | |
| 727 | +/* ------------------------------------------------------------------ */ | |
| 728 | + | |
| 729 | +static void prepare_quota_env(void) | |
| 730 | +{ | |
| 731 | + char apath[PATH_SZ]; | |
| 732 | + accounts_path(apath, sizeof(apath)); | |
| 733 | + | |
| 734 | + /* Clear profile/token overrides so --account always resolves from the | |
| 735 | + * local accounts file rather than an inherited agent profile. */ | |
| 736 | + unset_env_var("ACTIVE_PROFILE"); | |
| 737 | + unset_env_var("GOOGLE_ACCESS_TOKEN"); | |
| 738 | + unset_env_var("GOOGLE_REMOTE_URL"); | |
| 739 | + unset_env_var("GOOGLE_PROJECT_ID"); | |
| 740 | + unset_env_var("GOOGLE_ACCOUNT"); | |
| 741 | + set_env_var("GOOGLE_TOKEN_SOURCE", "local"); | |
| 742 | + set_env_var("GOOGLE_ACCOUNTS_FILE", apath); | |
| 743 | +} | |
| 744 | + | |
| 745 | +#if defined(_WIN32) | |
| 746 | +static void shell_quote_into(const char *in, char *out, size_t outsz) | |
| 747 | +{ | |
| 748 | + size_t o = 0; | |
| 749 | + const char *p; | |
| 750 | + | |
| 751 | + if (outsz < 3) { if (outsz) out[0] = '\0'; return; } | |
| 752 | + out[o++] = '"'; | |
| 753 | + for (p = in; p && *p; p++) { | |
| 754 | + if (*p == '"') { | |
| 755 | + if (o + 3 >= outsz) break; | |
| 756 | + out[o++] = '\\'; | |
| 757 | + out[o++] = '"'; | |
| 758 | + } else { | |
| 759 | + if (o + 2 >= outsz) break; | |
| 760 | + out[o++] = *p; | |
| 761 | + } | |
| 762 | + } | |
| 763 | + out[o++] = '"'; | |
| 764 | + out[o] = '\0'; | |
| 765 | +} | |
| 766 | + | |
| 767 | +static int run_quota_one(const char *bin, const char *email, buf_t *out) | |
| 768 | +{ | |
| 769 | + char cmd[CMD_SZ]; | |
| 770 | + char qbin[FIELD_SZ]; | |
| 771 | + char qemail[EMAIL_SZ + 16]; | |
| 772 | + FILE *f; | |
| 773 | + char line[2048]; | |
| 774 | + size_t total = 0; | |
| 775 | + int rc; | |
| 776 | + | |
| 777 | + if (!bin || !*bin || !is_safe_email(email)) return 0; | |
| 778 | + if (!bin_available(bin)) return -1; | |
| 779 | + shell_quote_into(bin, qbin, sizeof(qbin)); | |
| 780 | + shell_quote_into(email, qemail, sizeof(qemail)); | |
| 781 | + snprintf(cmd, sizeof(cmd), "%s --account %s --json 2>NUL", qbin, qemail); | |
| 782 | + | |
| 783 | + f = popen(cmd, "r"); | |
| 784 | + if (!f) return 0; | |
| 785 | + while (fgets(line, sizeof(line), f)) { | |
| 786 | + total += strlen(line); | |
| 787 | + if (total > OUT_MAX) break; | |
| 788 | + buf_adds(out, line); | |
| 789 | + } | |
| 790 | + rc = pclose(f); | |
| 791 | + if (rc != -1 && ((rc >> 8) & 0xff) == 127) return -1; | |
| 792 | + return (rc == 0) ? 1 : 0; | |
| 793 | +} | |
| 794 | +#else | |
| 795 | +static int run_quota_one(const char *bin, const char *email, buf_t *out) | |
| 796 | +{ | |
| 797 | + int pfd[2]; | |
| 798 | + pid_t pid; | |
| 799 | + char chunk[4096]; | |
| 800 | + ssize_t n; | |
| 801 | + int status = 0; | |
| 802 | + | |
| 803 | + if (!bin || !*bin || !is_safe_email(email)) return 0; | |
| 804 | + if (!bin_available(bin)) return -1; | |
| 805 | + if (pipe(pfd) != 0) return 0; | |
| 806 | + | |
| 807 | + pid = fork(); | |
| 808 | + if (pid < 0) { | |
| 809 | + close(pfd[0]); | |
| 810 | + close(pfd[1]); | |
| 811 | + return 0; | |
| 812 | + } | |
| 813 | + if (pid == 0) { | |
| 814 | + int devnull = open("/dev/null", O_WRONLY); | |
| 815 | + char *argv_exec[5]; | |
| 816 | + close(pfd[0]); | |
| 817 | + dup2(pfd[1], STDOUT_FILENO); | |
| 818 | + close(pfd[1]); | |
| 819 | + if (devnull >= 0) { | |
| 820 | + dup2(devnull, STDERR_FILENO); | |
| 821 | + close(devnull); | |
| 822 | + } | |
| 823 | + argv_exec[0] = (char *)bin; | |
| 824 | + argv_exec[1] = "--account"; | |
| 825 | + argv_exec[2] = (char *)email; | |
| 826 | + argv_exec[3] = "--json"; | |
| 827 | + argv_exec[4] = NULL; | |
| 828 | + execvp(bin, argv_exec); | |
| 829 | + _exit(127); | |
| 830 | + } | |
| 831 | + | |
| 832 | + close(pfd[1]); | |
| 833 | + while ((n = read(pfd[0], chunk, sizeof(chunk))) > 0) { | |
| 834 | + if (out->n + (size_t)n <= OUT_MAX) buf_add(out, chunk, (size_t)n); | |
| 835 | + } | |
| 836 | + close(pfd[0]); | |
| 837 | + if (waitpid(pid, &status, 0) < 0) return 0; | |
| 838 | + if (WIFEXITED(status) && WEXITSTATUS(status) == 127) return -1; | |
| 839 | + return (WIFEXITED(status) && WEXITSTATUS(status) == 0) ? 1 : 0; | |
| 840 | +} | |
| 841 | +#endif | |
| 842 | + | |
| 843 | +/* ------------------------------------------------------------------ */ | |
| 844 | +/* Quota parsing & pool aggregation */ | |
| 845 | +/* ------------------------------------------------------------------ */ | |
| 846 | + | |
| 847 | +typedef struct { | |
| 848 | + char id[MODEL_SZ]; | |
| 849 | + char pool[16]; | |
| 850 | + double pct; | |
| 851 | + int exhausted; | |
| 852 | + char reset_time[RESET_SZ]; | |
| 853 | +} model_quota_t; | |
| 854 | + | |
| 855 | +typedef struct { | |
| 856 | + int present; | |
| 857 | + double pct; | |
| 858 | + int exhausted; | |
| 859 | + char reset_time[RESET_SZ]; | |
| 860 | + int count; | |
| 861 | +} pool_summary_t; | |
| 862 | + | |
| 863 | +typedef struct { | |
| 864 | + int ok; | |
| 865 | + int cli_missing; | |
| 866 | + char error[64]; | |
| 867 | + char project[PROJ_SZ]; | |
| 868 | + pool_summary_t gemini; | |
| 869 | + pool_summary_t claude; | |
| 870 | + model_quota_t models[MAX_MODELS]; | |
| 871 | + int model_count; | |
| 872 | +} acct_quota_t; | |
| 873 | + | |
| 874 | +static void pool_init(pool_summary_t *p) | |
| 875 | +{ | |
| 876 | + p->present = 0; | |
| 877 | + p->pct = -1.0; | |
| 878 | + p->exhausted = 0; | |
| 879 | + p->reset_time[0] = '\0'; | |
| 880 | + p->count = 0; | |
| 881 | +} | |
| 882 | + | |
| 883 | +static void pool_add(pool_summary_t *p, double pct, int exhausted, const char *reset) | |
| 884 | +{ | |
| 885 | + if (!p->present || pct < p->pct) p->pct = pct; | |
| 886 | + p->present = 1; | |
| 887 | + if (exhausted || pct <= 0.0) p->exhausted = 1; | |
| 888 | + if (!p->reset_time[0] && reset && reset[0]) | |
| 889 | + snprintf(p->reset_time, sizeof(p->reset_time), "%s", reset); | |
| 890 | + p->count++; | |
| 891 | +} | |
| 892 | + | |
| 893 | +static const char *find_json_root(const buf_t *b) | |
| 894 | +{ | |
| 895 | + const char *p; | |
| 896 | + if (!b || !b->p) return NULL; | |
| 897 | + p = b->p; | |
| 898 | + while (*p) { | |
| 899 | + if (*p == '{') return p; | |
| 900 | + p = strchr(p, '\n'); | |
| 901 | + if (!p) break; | |
| 902 | + p++; | |
| 903 | + } | |
| 904 | + return strchr(b->p, '{'); | |
| 905 | +} | |
| 906 | + | |
| 907 | +static void parse_quota_output(const buf_t *raw, int run_rc, acct_quota_t *q) | |
| 908 | +{ | |
| 909 | + const char *root; | |
| 910 | + const char *root_end; | |
| 911 | + const char *buckets; | |
| 912 | + const char *buckets_end; | |
| 913 | + const char *p; | |
| 914 | + | |
| 915 | + memset(q, 0, sizeof(*q)); | |
| 916 | + pool_init(&q->gemini); | |
| 917 | + pool_init(&q->claude); | |
| 918 | + | |
| 919 | + if (run_rc == -1) { | |
| 920 | + q->cli_missing = 1; | |
| 921 | + snprintf(q->error, sizeof(q->error), "cli_unavailable"); | |
| 922 | + return; | |
| 923 | + } | |
| 924 | + | |
| 925 | + root = find_json_root(raw); | |
| 926 | + if (!root) { | |
| 927 | + snprintf(q->error, sizeof(q->error), "quota_fetch_failed"); | |
| 928 | + return; | |
| 929 | + } | |
| 930 | + root_end = json_skip_value(root); | |
| 931 | + if (!root_end || root_end <= root) { | |
| 932 | + snprintf(q->error, sizeof(q->error), "invalid_quota_json"); | |
| 933 | + return; | |
| 934 | + } | |
| 935 | + | |
| 936 | + if (!json_bool_field(root, root_end, "ok", 0)) { | |
| 937 | + json_str_field(root, root_end, "error", q->error, sizeof(q->error)); | |
| 938 | + if (!q->error[0]) snprintf(q->error, sizeof(q->error), "quota_fetch_failed"); | |
| 939 | + return; | |
| 940 | + } | |
| 941 | + | |
| 942 | + json_str_field(root, root_end, "project", q->project, sizeof(q->project)); | |
| 943 | + buckets = json_find_key(root, root_end, "buckets"); | |
| 944 | + if (!buckets || *buckets != '[') { | |
| 945 | + snprintf(q->error, sizeof(q->error), "missing_buckets"); | |
| 946 | + return; | |
| 947 | + } | |
| 948 | + buckets_end = json_skip_value(buckets); | |
| 949 | + if (!buckets_end || buckets_end <= buckets) { | |
| 950 | + snprintf(q->error, sizeof(q->error), "invalid_buckets"); | |
| 951 | + return; | |
| 952 | + } | |
| 953 | + | |
| 954 | + p = buckets + 1; | |
| 955 | + while (p && p < buckets_end) { | |
| 956 | + const char *open = strchr(p, '{'); | |
| 957 | + const char *end; | |
| 958 | + char mid[MODEL_SZ] = {0}; | |
| 959 | + char rst[RESET_SZ] = {0}; | |
| 960 | + double frac = 0.0; | |
| 961 | + double pct = 0.0; | |
| 962 | + int exhausted = 0; | |
| 963 | + const char *pool_name = "other"; | |
| 964 | + | |
| 965 | + if (!open || open >= buckets_end) break; | |
| 966 | + end = json_skip_value(open); | |
| 967 | + if (!end || end <= open || end > buckets_end) break; | |
| 968 | + | |
| 969 | + json_str_field(open, end, "modelId", mid, sizeof(mid)); | |
| 970 | + json_str_field(open, end, "resetTime", rst, sizeof(rst)); | |
| 971 | + | |
| 972 | + if (mid[0] && strncmp(mid, "chat_", 5) != 0 && strncmp(mid, "tab_", 4) != 0) { | |
| 973 | + if (json_double_field(open, end, "remainingFraction", &frac)) { | |
| 974 | + pct = frac * 100.0; | |
| 975 | + if (pct < 0.0) pct = 0.0; | |
| 976 | + if (pct > 100.0) pct = 100.0; | |
| 977 | + if (frac <= 0.0) exhausted = 1; | |
| 978 | + } else { | |
| 979 | + /* Absent or null remainingFraction means exhausted. */ | |
| 980 | + pct = 0.0; | |
| 981 | + exhausted = 1; | |
| 982 | + } | |
| 983 | + | |
| 984 | + if (strncmp(mid, "gemini-", 7) == 0) { | |
| 985 | + pool_name = "gemini"; | |
| 986 | + pool_add(&q->gemini, pct, exhausted, rst); | |
| 987 | + } else if (strncmp(mid, "claude-", 7) == 0) { | |
| 988 | + pool_name = "claude"; | |
| 989 | + pool_add(&q->claude, pct, exhausted, rst); | |
| 990 | + } | |
| 991 | + | |
| 992 | + if (q->model_count < MAX_MODELS) { | |
| 993 | + model_quota_t *m = &q->models[q->model_count++]; | |
| 994 | + snprintf(m->id, sizeof(m->id), "%s", mid); | |
| 995 | + snprintf(m->pool, sizeof(m->pool), "%s", pool_name); | |
| 996 | + m->pct = pct; | |
| 997 | + m->exhausted = exhausted; | |
| 998 | + snprintf(m->reset_time, sizeof(m->reset_time), "%s", rst); | |
| 999 | + } | |
| 1000 | + } | |
| 1001 | + p = end; | |
| 1002 | + } | |
| 1003 | + | |
| 1004 | + q->ok = 1; | |
| 1005 | +} | |
| 1006 | + | |
| 1007 | +static void fetch_all_quotas(const char *bin, const acct_entry_t *accts, int count, | |
| 1008 | + acct_quota_t *out_q) | |
| 1009 | +{ | |
| 1010 | +#if defined(_WIN32) | |
| 1011 | + int i; | |
| 1012 | + for (i = 0; i < count; i++) { | |
| 1013 | + buf_t raw; | |
| 1014 | + int rc; | |
| 1015 | + buf_init(&raw); | |
| 1016 | + rc = run_quota_one(bin, accts[i].email, &raw); | |
| 1017 | + parse_quota_output(&raw, rc, &out_q[i]); | |
| 1018 | + buf_free(&raw); | |
| 1019 | + } | |
| 1020 | +#else | |
| 1021 | + int next_idx = 0; | |
| 1022 | + int done = 0; | |
| 1023 | + | |
| 1024 | + if (count <= 0) return; | |
| 1025 | + if (!bin_available(bin)) { | |
| 1026 | + int i; | |
| 1027 | + for (i = 0; i < count; i++) { | |
| 1028 | + buf_t empty; | |
| 1029 | + buf_init(&empty); | |
| 1030 | + parse_quota_output(&empty, -1, &out_q[i]); | |
| 1031 | + } | |
| 1032 | + return; | |
| 1033 | + } | |
| 1034 | + | |
| 1035 | + { | |
| 1036 | + typedef struct { | |
| 1037 | + int active; | |
| 1038 | + int acct_idx; | |
| 1039 | + int fd; | |
| 1040 | + pid_t pid; | |
| 1041 | + buf_t raw; | |
| 1042 | + } worker_t; | |
| 1043 | + | |
| 1044 | + worker_t w[MAX_WORKERS]; | |
| 1045 | + int i; | |
| 1046 | + memset(w, 0, sizeof(w)); | |
| 1047 | + | |
| 1048 | + while (done < count) { | |
| 1049 | + struct pollfd pfds[MAX_WORKERS]; | |
| 1050 | + int pmap[MAX_WORKERS]; | |
| 1051 | + int nfds = 0; | |
| 1052 | + | |
| 1053 | + for (i = 0; i < MAX_WORKERS && next_idx < count; i++) { | |
| 1054 | + if (w[i].active) continue; | |
| 1055 | + { | |
| 1056 | + int pfd[2]; | |
| 1057 | + pid_t pid; | |
| 1058 | + if (pipe(pfd) != 0) { | |
| 1059 | + buf_t empty; | |
| 1060 | + buf_init(&empty); | |
| 1061 | + parse_quota_output(&empty, 0, &out_q[next_idx]); | |
| 1062 | + next_idx++; | |
| 1063 | + done++; | |
| 1064 | + continue; | |
| 1065 | + } | |
| 1066 | + pid = fork(); | |
| 1067 | + if (pid < 0) { | |
| 1068 | + close(pfd[0]); | |
| 1069 | + close(pfd[1]); | |
| 1070 | + buf_t empty; | |
| 1071 | + buf_init(&empty); | |
| 1072 | + parse_quota_output(&empty, 0, &out_q[next_idx]); | |
| 1073 | + next_idx++; | |
| 1074 | + done++; | |
| 1075 | + continue; | |
| 1076 | + } | |
| 1077 | + if (pid == 0) { | |
| 1078 | + int devnull = open("/dev/null", O_WRONLY); | |
| 1079 | + char *argv_exec[5]; | |
| 1080 | + close(pfd[0]); | |
| 1081 | + dup2(pfd[1], STDOUT_FILENO); | |
| 1082 | + close(pfd[1]); | |
| 1083 | + if (devnull >= 0) { | |
| 1084 | + dup2(devnull, STDERR_FILENO); | |
| 1085 | + close(devnull); | |
| 1086 | + } | |
| 1087 | + argv_exec[0] = (char *)bin; | |
| 1088 | + argv_exec[1] = "--account"; | |
| 1089 | + argv_exec[2] = (char *)accts[next_idx].email; | |
| 1090 | + argv_exec[3] = "--json"; | |
| 1091 | + argv_exec[4] = NULL; | |
| 1092 | + execvp(bin, argv_exec); | |
| 1093 | + _exit(127); | |
| 1094 | + } | |
| 1095 | + close(pfd[1]); | |
| 1096 | + w[i].active = 1; | |
| 1097 | + w[i].acct_idx = next_idx; | |
| 1098 | + w[i].fd = pfd[0]; | |
| 1099 | + w[i].pid = pid; | |
| 1100 | + buf_init(&w[i].raw); | |
| 1101 | + next_idx++; | |
| 1102 | + } | |
| 1103 | + } | |
| 1104 | + | |
| 1105 | + for (i = 0; i < MAX_WORKERS; i++) { | |
| 1106 | + if (!w[i].active) continue; | |
| 1107 | + pfds[nfds].fd = w[i].fd; | |
| 1108 | + pfds[nfds].events = POLLIN; | |
| 1109 | + pfds[nfds].revents = 0; | |
| 1110 | + pmap[nfds] = i; | |
| 1111 | + nfds++; | |
| 1112 | + } | |
| 1113 | + if (nfds == 0) break; | |
| 1114 | + | |
| 1115 | + if (poll(pfds, (nfds_t)nfds, 30000) < 0) { | |
| 1116 | + if (errno == EINTR) continue; | |
| 1117 | + break; | |
| 1118 | + } | |
| 1119 | + | |
| 1120 | + for (i = 0; i < nfds; i++) { | |
| 1121 | + int wi = pmap[i]; | |
| 1122 | + if (pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) { | |
| 1123 | + char chunk[4096]; | |
| 1124 | + ssize_t n = read(w[wi].fd, chunk, sizeof(chunk)); | |
| 1125 | + if (n > 0) { | |
| 1126 | + if (w[wi].raw.n + (size_t)n <= OUT_MAX) | |
| 1127 | + buf_add(&w[wi].raw, chunk, (size_t)n); | |
| 1128 | + } else if (n == 0 || (n < 0 && errno != EINTR)) { | |
| 1129 | + int status = 0; | |
| 1130 | + int rc = 0; | |
| 1131 | + close(w[wi].fd); | |
| 1132 | + if (waitpid(w[wi].pid, &status, 0) >= 0) { | |
| 1133 | + if (WIFEXITED(status) && WEXITSTATUS(status) == 127) rc = -1; | |
| 1134 | + else if (WIFEXITED(status) && WEXITSTATUS(status) == 0) rc = 1; | |
| 1135 | + } | |
| 1136 | + parse_quota_output(&w[wi].raw, rc, &out_q[w[wi].acct_idx]); | |
| 1137 | + buf_free(&w[wi].raw); | |
| 1138 | + w[wi].active = 0; | |
| 1139 | + done++; | |
| 1140 | + } | |
| 1141 | + } | |
| 1142 | + } | |
| 1143 | + } | |
| 1144 | + | |
| 1145 | + for (i = 0; i < MAX_WORKERS; i++) { | |
| 1146 | + if (w[i].active) { | |
| 1147 | + int status = 0; | |
| 1148 | + close(w[i].fd); | |
| 1149 | + waitpid(w[i].pid, &status, 0); | |
| 1150 | + parse_quota_output(&w[i].raw, 0, &out_q[w[i].acct_idx]); | |
| 1151 | + buf_free(&w[i].raw); | |
| 1152 | + w[i].active = 0; | |
| 1153 | + } | |
| 1154 | + } | |
| 1155 | + } | |
| 1156 | +#endif | |
| 1157 | +} | |
| 1158 | + | |
| 1159 | +/* ------------------------------------------------------------------ */ | |
| 1160 | +/* JSON emitters */ | |
| 1161 | +/* ------------------------------------------------------------------ */ | |
| 1162 | + | |
| 1163 | +static void json_headers(void) | |
| 1164 | +{ | |
| 1165 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 1166 | + "Cache-Control: no-store\r\n" | |
| 1167 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1168 | +} | |
| 1169 | + | |
| 1170 | +static void emit_error(int code, const char *status, const char *err, const char *detail) | |
| 1171 | +{ | |
| 1172 | + buf_t b; | |
| 1173 | + | |
| 1174 | + buf_init(&b); | |
| 1175 | + buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n" | |
| 1176 | + "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n", | |
| 1177 | + code, status); | |
| 1178 | + buf_adds(&b, "{\"ok\":false,\"error\":"); | |
| 1179 | + buf_json(&b, err); | |
| 1180 | + if (detail && *detail) { | |
| 1181 | + buf_adds(&b, ",\"detail\":"); | |
| 1182 | + buf_json(&b, detail); | |
| 1183 | + } | |
| 1184 | + buf_adds(&b, "}\n"); | |
| 1185 | + fputs(buf_str(&b), stdout); | |
| 1186 | + buf_free(&b); | |
| 1187 | +} | |
| 1188 | + | |
| 1189 | +static void emit_pool_json(buf_t *b, const pool_summary_t *p) | |
| 1190 | +{ | |
| 1191 | + if (!p->present) { | |
| 1192 | + buf_adds(b, "{\"pct\":-1,\"exhausted\":false,\"reset_time\":\"\",\"count\":0}"); | |
| 1193 | + return; | |
| 1194 | + } | |
| 1195 | + buf_addf(b, "{\"pct\":%.2f,\"exhausted\":%s,\"reset_time\":", | |
| 1196 | + p->pct, p->exhausted ? "true" : "false"); | |
| 1197 | + buf_json(b, p->reset_time); | |
| 1198 | + buf_addf(b, ",\"count\":%d}", p->count); | |
| 1199 | +} | |
| 1200 | + | |
| 1201 | +static void emit_acct_quota_json(buf_t *b, const acct_entry_t *a, const acct_quota_t *q) | |
| 1202 | +{ | |
| 1203 | + int i; | |
| 1204 | + | |
| 1205 | + buf_adds(b, "{\"email\":"); | |
| 1206 | + buf_json(b, a->email); | |
| 1207 | + buf_addf(b, ",\"selected\":%s,\"has_refresh\":%s,\"ok\":%s", | |
| 1208 | + a->selected ? "true" : "false", | |
| 1209 | + a->has_refresh ? "true" : "false", | |
| 1210 | + q->ok ? "true" : "false"); | |
| 1211 | + | |
| 1212 | + if (!q->ok) { | |
| 1213 | + buf_adds(b, ",\"error\":"); | |
| 1214 | + buf_json(b, q->error[0] ? q->error : "quota_fetch_failed"); | |
| 1215 | + if (q->cli_missing) { | |
| 1216 | + buf_adds(b, ",\"detail\":"); | |
| 1217 | + buf_json(b, "scorpiox-google-quota was not found on PATH; install SCORPIOX CODE or set GOOGLE_QUOTA_BIN"); | |
| 1218 | + } | |
| 1219 | + buf_addc(b, '}'); | |
| 1220 | + return; | |
| 1221 | + } | |
| 1222 | + | |
| 1223 | + buf_adds(b, ",\"project\":"); | |
| 1224 | + buf_json(b, q->project); | |
| 1225 | + buf_adds(b, ",\"gemini\":"); | |
| 1226 | + emit_pool_json(b, &q->gemini); | |
| 1227 | + buf_adds(b, ",\"claude\":"); | |
| 1228 | + emit_pool_json(b, &q->claude); | |
| 1229 | + buf_adds(b, ",\"models\":["); | |
| 1230 | + for (i = 0; i < q->model_count; i++) { | |
| 1231 | + const model_quota_t *m = &q->models[i]; | |
| 1232 | + if (i > 0) buf_addc(b, ','); | |
| 1233 | + buf_adds(b, "{\"id\":"); | |
| 1234 | + buf_json(b, m->id); | |
| 1235 | + buf_adds(b, ",\"pool\":"); | |
| 1236 | + buf_json(b, m->pool); | |
| 1237 | + buf_addf(b, ",\"pct\":%.2f,\"exhausted\":%s,\"reset_time\":", | |
| 1238 | + m->pct, m->exhausted ? "true" : "false"); | |
| 1239 | + buf_json(b, m->reset_time); | |
| 1240 | + buf_addc(b, '}'); | |
| 1241 | + } | |
| 1242 | + buf_adds(b, "]}"); | |
| 1243 | +} | |
| 1244 | + | |
| 1245 | +/* ------------------------------------------------------------------ */ | |
| 1246 | +/* Actions */ | |
| 1247 | +/* ------------------------------------------------------------------ */ | |
| 1248 | + | |
| 1249 | +static int action_status(void) | |
| 1250 | +{ | |
| 1251 | + acct_entry_t accts[MAX_ACCOUNTS]; | |
| 1252 | + char selected[EMAIL_SZ]; | |
| 1253 | + char apath[PATH_SZ], spath[PATH_SZ]; | |
| 1254 | + int count, i; | |
| 1255 | + int cli_ok; | |
| 1256 | + buf_t b; | |
| 1257 | + | |
| 1258 | + count = load_accounts(accts, MAX_ACCOUNTS, selected, sizeof(selected)); | |
| 1259 | + accounts_path(apath, sizeof(apath)); | |
| 1260 | + selected_path(spath, sizeof(spath)); | |
| 1261 | + cli_ok = bin_available(quota_bin()); | |
| 1262 | + | |
| 1263 | + buf_init(&b); | |
| 1264 | + buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"selected\":"); | |
| 1265 | + buf_json(&b, selected); | |
| 1266 | + buf_adds(&b, ",\"accounts_path\":"); | |
| 1267 | + buf_json(&b, apath); | |
| 1268 | + buf_adds(&b, ",\"selected_path\":"); | |
| 1269 | + buf_json(&b, spath); | |
| 1270 | + buf_addf(&b, ",\"cli_present\":%s,\"count\":%d,\"accounts\":[", | |
| 1271 | + cli_ok ? "true" : "false", count); | |
| 1272 | + | |
| 1273 | + for (i = 0; i < count; i++) { | |
| 1274 | + if (i > 0) buf_addc(&b, ','); | |
| 1275 | + buf_adds(&b, "{\"email\":"); | |
| 1276 | + buf_json(&b, accts[i].email); | |
| 1277 | + buf_addf(&b, ",\"has_refresh\":%s,\"selected\":%s}", | |
| 1278 | + accts[i].has_refresh ? "true" : "false", | |
| 1279 | + accts[i].selected ? "true" : "false"); | |
| 1280 | + } | |
| 1281 | + buf_adds(&b, "]}\n"); | |
| 1282 | + | |
| 1283 | + json_headers(); | |
| 1284 | + fputs(buf_str(&b), stdout); | |
| 1285 | + buf_free(&b); | |
| 1286 | + return 0; | |
| 1287 | +} | |
| 1288 | + | |
| 1289 | +static int action_quota(const char *target_email) | |
| 1290 | +{ | |
| 1291 | + acct_entry_t accts[MAX_ACCOUNTS]; | |
| 1292 | + char selected[EMAIL_SZ]; | |
| 1293 | + int count, i; | |
| 1294 | + const char *bin = quota_bin(); | |
| 1295 | + buf_t b; | |
| 1296 | + | |
| 1297 | + count = load_accounts(accts, MAX_ACCOUNTS, selected, sizeof(selected)); | |
| 1298 | + prepare_quota_env(); | |
| 1299 | + | |
| 1300 | + if (target_email && target_email[0]) { | |
| 1301 | + int idx = -1; | |
| 1302 | + buf_t raw; | |
| 1303 | + acct_quota_t q; | |
| 1304 | + int rc; | |
| 1305 | + | |
| 1306 | + for (i = 0; i < count; i++) { | |
| 1307 | + if (strcmp(accts[i].email, target_email) == 0) { idx = i; break; } | |
| 1308 | + } | |
| 1309 | + if (idx < 0) { | |
| 1310 | + emit_error(404, "Not Found", "unknown_account", target_email); | |
| 1311 | + return 1; | |
| 1312 | + } | |
| 1313 | + | |
| 1314 | + buf_init(&raw); | |
| 1315 | + rc = run_quota_one(bin, accts[idx].email, &raw); | |
| 1316 | + parse_quota_output(&raw, rc, &q); | |
| 1317 | + buf_free(&raw); | |
| 1318 | + | |
| 1319 | + if (q.cli_missing) { | |
| 1320 | + emit_error(200, "OK", "cli_unavailable", | |
| 1321 | + "scorpiox-google-quota was not found on PATH; install SCORPIOX CODE or set GOOGLE_QUOTA_BIN"); | |
| 1322 | + return 1; | |
| 1323 | + } | |
| 1324 | + | |
| 1325 | + buf_init(&b); | |
| 1326 | + buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"selected\":"); | |
| 1327 | + buf_json(&b, selected); | |
| 1328 | + buf_adds(&b, ",\"account\":"); | |
| 1329 | + emit_acct_quota_json(&b, &accts[idx], &q); | |
| 1330 | + buf_adds(&b, "}\n"); | |
| 1331 | + | |
| 1332 | + json_headers(); | |
| 1333 | + fputs(buf_str(&b), stdout); | |
| 1334 | + buf_free(&b); | |
| 1335 | + return 0; | |
| 1336 | + } | |
| 1337 | + | |
| 1338 | + { | |
| 1339 | + acct_quota_t *qs = NULL; | |
| 1340 | + const char *best_g = ""; | |
| 1341 | + const char *best_c = ""; | |
| 1342 | + double best_gp = -1.0; | |
| 1343 | + double best_cp = -1.0; | |
| 1344 | + | |
| 1345 | + if (count > 0) { | |
| 1346 | + qs = (acct_quota_t *)calloc((size_t)count, sizeof(acct_quota_t)); | |
| 1347 | + if (!qs) { | |
| 1348 | + emit_error(500, "Internal Server Error", "oom", "out of memory"); | |
| 1349 | + return 1; | |
| 1350 | + } | |
| 1351 | + fetch_all_quotas(bin, accts, count, qs); | |
| 1352 | + | |
| 1353 | + if (qs[0].cli_missing) { | |
| 1354 | + free(qs); | |
| 1355 | + emit_error(200, "OK", "cli_unavailable", | |
| 1356 | + "scorpiox-google-quota was not found on PATH; install SCORPIOX CODE or set GOOGLE_QUOTA_BIN"); | |
| 1357 | + return 1; | |
| 1358 | + } | |
| 1359 | + | |
| 1360 | + for (i = 0; i < count; i++) { | |
| 1361 | + if (!qs[i].ok) continue; | |
| 1362 | + if (qs[i].gemini.present && !qs[i].gemini.exhausted && qs[i].gemini.pct > best_gp) { | |
| 1363 | + best_gp = qs[i].gemini.pct; | |
| 1364 | + best_g = accts[i].email; | |
| 1365 | + } | |
| 1366 | + if (qs[i].claude.present && !qs[i].claude.exhausted && qs[i].claude.pct > best_cp) { | |
| 1367 | + best_cp = qs[i].claude.pct; | |
| 1368 | + best_c = accts[i].email; | |
| 1369 | + } | |
| 1370 | + } | |
| 1371 | + } | |
| 1372 | + | |
| 1373 | + buf_init(&b); | |
| 1374 | + buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"selected\":"); | |
| 1375 | + buf_json(&b, selected); | |
| 1376 | + buf_adds(&b, ",\"best_gemini\":"); | |
| 1377 | + buf_json(&b, best_g); | |
| 1378 | + buf_adds(&b, ",\"best_claude\":"); | |
| 1379 | + buf_json(&b, best_c); | |
| 1380 | + buf_addf(&b, ",\"count\":%d,\"accounts\":[", count); | |
| 1381 | + for (i = 0; i < count; i++) { | |
| 1382 | + if (i > 0) buf_addc(&b, ','); | |
| 1383 | + emit_acct_quota_json(&b, &accts[i], &qs[i]); | |
| 1384 | + } | |
| 1385 | + buf_adds(&b, "]}\n"); | |
| 1386 | + | |
| 1387 | + free(qs); | |
| 1388 | + json_headers(); | |
| 1389 | + fputs(buf_str(&b), stdout); | |
| 1390 | + buf_free(&b); | |
| 1391 | + return 0; | |
| 1392 | + } | |
| 1393 | +} | |
| 1394 | + | |
| 1395 | +static int action_switch(const char *target_email) | |
| 1396 | +{ | |
| 1397 | + acct_entry_t accts[MAX_ACCOUNTS]; | |
| 1398 | + char selected[EMAIL_SZ]; | |
| 1399 | + char spath[PATH_SZ]; | |
| 1400 | + int count, i, found = 0; | |
| 1401 | + FILE *f; | |
| 1402 | + buf_t b; | |
| 1403 | + | |
| 1404 | + if (!target_email || !target_email[0]) { | |
| 1405 | + emit_error(400, "Bad Request", "missing_account", "pass ?account=<email>"); | |
| 1406 | + return 1; | |
| 1407 | + } | |
| 1408 | + if (!is_safe_email(target_email)) { | |
| 1409 | + emit_error(400, "Bad Request", "invalid_account", target_email); | |
| 1410 | + return 1; | |
| 1411 | + } | |
| 1412 | + | |
| 1413 | + count = load_accounts(accts, MAX_ACCOUNTS, selected, sizeof(selected)); | |
| 1414 | + for (i = 0; i < count; i++) { | |
| 1415 | + if (strcmp(accts[i].email, target_email) == 0) { found = 1; break; } | |
| 1416 | + } | |
| 1417 | + if (!found) { | |
| 1418 | + emit_error(404, "Not Found", "unknown_account", target_email); | |
| 1419 | + return 1; | |
| 1420 | + } | |
| 1421 | + | |
| 1422 | + selected_path(spath, sizeof(spath)); | |
| 1423 | + f = fopen(spath, "wb"); | |
| 1424 | + if (!f) { | |
| 1425 | + emit_error(500, "Internal Server Error", "write_failed", strerror(errno)); | |
| 1426 | + return 1; | |
| 1427 | + } | |
| 1428 | + fprintf(f, "%s\n", target_email); | |
| 1429 | + fclose(f); | |
| 1430 | + | |
| 1431 | + buf_init(&b); | |
| 1432 | + buf_adds(&b, "{\"ok\":true,\"selected\":"); | |
| 1433 | + buf_json(&b, target_email); | |
| 1434 | + buf_adds(&b, "}\n"); | |
| 1435 | + json_headers(); | |
| 1436 | + fputs(buf_str(&b), stdout); | |
| 1437 | + buf_free(&b); | |
| 1438 | + return 0; | |
| 1439 | +} | |
| 1440 | + | |
| 1441 | +/* ------------------------------------------------------------------ */ | |
| 1442 | +/* HTML emission */ | |
| 1443 | +/* ------------------------------------------------------------------ */ | |
| 1444 | + | |
| 1445 | +static void emit_ui(void) | |
| 1446 | +{ | |
| 1447 | + const char *p = UI_HTML; | |
| 1448 | + | |
| 1449 | + while (*p) { | |
| 1450 | + if (*p == '\001') { | |
| 1451 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout); | |
| 1452 | + p++; | |
| 1453 | + } else if (*p == '\002') { | |
| 1454 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | |
| 1455 | + p++; | |
| 1456 | + } else { | |
| 1457 | + putchar(*p++); | |
| 1458 | + } | |
| 1459 | + } | |
| 1460 | +} | |
| 1461 | + | |
| 1462 | +/* ------------------------------------------------------------------ */ | |
| 1463 | +/* main */ | |
| 1464 | +/* ------------------------------------------------------------------ */ | |
| 1465 | + | |
| 1466 | +static void read_post_account(char *out, size_t outsz) | |
| 1467 | +{ | |
| 1468 | + const char *cl = getenv("CONTENT_LENGTH"); | |
| 1469 | + long n = (cl && *cl) ? atol(cl) : 0; | |
| 1470 | + char body[4096]; | |
| 1471 | + size_t len = 0; | |
| 1472 | + | |
| 1473 | + if (n > 0 && n < (long)sizeof(body)) { | |
| 1474 | + len = fread(body, 1, (size_t)n, stdin); | |
| 1475 | + } else { | |
| 1476 | + const char *pbf = getenv("POST_BODY_FILE"); | |
| 1477 | + if (pbf && *pbf) { | |
| 1478 | + char *fbuf = read_file(pbf); | |
| 1479 | + if (fbuf) { | |
| 1480 | + len = strlen(fbuf); | |
| 1481 | + if (len >= sizeof(body)) len = sizeof(body) - 1; | |
| 1482 | + memcpy(body, fbuf, len); | |
| 1483 | + free(fbuf); | |
| 1484 | + } | |
| 1485 | + } | |
| 1486 | + } | |
| 1487 | + if (len == 0) return; | |
| 1488 | + body[len] = '\0'; | |
| 1489 | + if (!json_str_field(body, body + len, "account", out, outsz)) | |
| 1490 | + json_str_field(body, body + len, "email", out, outsz); | |
| 1491 | +} | |
| 1492 | + | |
| 1493 | +int main(int argc, char **argv) | |
| 1494 | +{ | |
| 1495 | + const char *qs; | |
| 1496 | + char action[64] = {0}; | |
| 1497 | + | |
| 1498 | + /* 1. Discovery metadata. Must stay unauthenticated. */ | |
| 1499 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { | |
| 1500 | + puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}"); | |
| 1501 | + return 0; | |
| 1502 | + } | |
| 1503 | + if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) { | |
| 1504 | + puts(PLUGIN_ID " " PLUGIN_VER); | |
| 1505 | + return 0; | |
| 1506 | + } | |
| 1507 | + | |
| 1508 | + require_node_auth(); | |
| 1509 | + | |
| 1510 | + qs = getenv("QUERY_STRING"); | |
| 1511 | + if (!qs) qs = ""; | |
| 1512 | + | |
| 1513 | + /* 2. JSON API mode. */ | |
| 1514 | + if (query_has(qs, "action") || query_has(qs, "format")) { | |
| 1515 | + char fmt[32] = {0}; | |
| 1516 | + char account[EMAIL_SZ] = {0}; | |
| 1517 | + | |
| 1518 | + get_query_val(qs, "action", action, sizeof(action)); | |
| 1519 | + get_query_val(qs, "format", fmt, sizeof(fmt)); | |
| 1520 | + if (!get_query_val(qs, "account", account, sizeof(account))) | |
| 1521 | + get_query_val(qs, "email", account, sizeof(account)); | |
| 1522 | + | |
| 1523 | + if (!action[0] && strcmp(fmt, "json") == 0) | |
| 1524 | + snprintf(action, sizeof(action), "quota"); | |
| 1525 | + | |
| 1526 | + if (strcmp(action, "status") == 0 || !action[0]) return action_status(); | |
| 1527 | + if (strcmp(action, "quota") == 0) return action_quota(account); | |
| 1528 | + if (strcmp(action, "switch") == 0) { | |
| 1529 | + if (!account[0]) read_post_account(account, sizeof(account)); | |
| 1530 | + return action_switch(account); | |
| 1531 | + } | |
| 1532 | + emit_error(404, "Not Found", "unknown_action", action); | |
| 1533 | + return 1; | |
| 1534 | + } | |
| 1535 | + | |
| 1536 | + /* 3. HTML UI mode. */ | |
| 1537 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 1538 | + "Cache-Control: no-store\r\n" | |
| 1539 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1540 | + emit_ui(); | |
| 1541 | + return 0; | |
| 1542 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..4a15f36 | ||
| --- /dev/null | ||
| +++ b/src/ui.html | ||
| @@ -0,0 +1,462 @@ | ||
| 1 | +<!DOCTYPE html> | |
| 2 | +<html lang="en"><head><meta charset="utf-8"> | |
| 3 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | |
| 4 | +<title>google quota</title> | |
| 5 | +<!--TOKENS--> | |
| 6 | +<style> | |
| 7 | +*{box-sizing:border-box} | |
| 8 | +html,body{margin:0;min-height:100%} | |
| 9 | +body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px; | |
| 10 | + line-height:1.5;-webkit-font-smoothing:antialiased} | |
| 11 | +#app{max-width:880px;margin:0 auto;padding:16px 16px 40px} | |
| 12 | +.hd{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px} | |
| 13 | +.hd .grow{flex:1 1 auto;min-width:0} | |
| 14 | +.hd h1{margin:0;font-size:18px;font-weight:650;letter-spacing:-.01em} | |
| 15 | +.hd .sub{font-size:11.5px;color:var(--text-2);margin-top:2px;white-space:nowrap; | |
| 16 | + overflow:hidden;text-overflow:ellipsis} | |
| 17 | +.pill{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:650; | |
| 18 | + padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-2); | |
| 19 | + border:1px solid var(--line);white-space:nowrap} | |
| 20 | +.pill .dot{width:7px;height:7px;border-radius:50%;background:var(--gray);flex:0 0 auto} | |
| 21 | +.pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)} | |
| 22 | +.pill.ok .dot{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.15)} | |
| 23 | +.pill.warn{color:var(--orange);border-color:rgba(255,159,10,.35)} | |
| 24 | +.pill.warn .dot{background:var(--orange)} | |
| 25 | +.pill.bad{color:var(--red);border-color:rgba(255,69,58,.35)} | |
| 26 | +.pill.bad .dot{background:var(--red)} | |
| 27 | +.pill.off .dot{background:var(--gray)} | |
| 28 | +#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text); | |
| 29 | + border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer; | |
| 30 | + font-family:inherit} | |
| 31 | +.kpis{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin-bottom:12px} | |
| 32 | +.kpi{background:var(--bg-card);border:1px solid var(--line);border-radius:12px;padding:12px 14px;min-width:0} | |
| 33 | +.kpi .lbl{font-size:11px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--text-2)} | |
| 34 | +.kpi .val{margin-top:4px;font-size:15px;font-weight:650;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} | |
| 35 | +.kpi .meta{margin-top:2px;font-size:11.5px;color:var(--text-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} | |
| 36 | +.bar-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:12px} | |
| 37 | +.bar-row .spacer{flex:1 1 auto} | |
| 38 | +.status-txt{font-size:12px;color:var(--text-2)} | |
| 39 | +.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:6px 14px; | |
| 40 | + font-weight:600;font-size:12.5px;cursor:pointer;font-family:inherit; | |
| 41 | + transition:transform .12s var(--ease),opacity .12s} | |
| 42 | +.btn:active{transform:scale(.98)} | |
| 43 | +.btn:disabled{opacity:.5;cursor:default} | |
| 44 | +.btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)} | |
| 45 | +.btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)} | |
| 46 | +.btn.sm{padding:4px 11px;font-size:11.5px} | |
| 47 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px; | |
| 48 | + padding:14px 16px;margin-bottom:10px} | |
| 49 | +.card.selected{border-color:var(--blue)} | |
| 50 | +.card h2{margin:0 0 4px;font-size:12.5px;font-weight:700;letter-spacing:.08em; | |
| 51 | + text-transform:uppercase;color:var(--text-2)} | |
| 52 | +.acct-top{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:10px} | |
| 53 | +.acct-email{font-family:var(--mono);font-size:13px;font-weight:650;word-break:break-all;flex:1 1 auto;min-width:0} | |
| 54 | +.badges{display:flex;align-items:center;gap:6px;flex-wrap:wrap} | |
| 55 | +.tag{font-size:11px;font-weight:650;padding:2px 8px;border-radius:999px; | |
| 56 | + background:var(--surface-2);color:var(--text-2);border:1px solid var(--line)} | |
| 57 | +.tag.sel{color:var(--blue);border-color:rgba(10,132,255,.4)} | |
| 58 | +.tag.best{color:var(--green);border-color:rgba(48,209,88,.35)} | |
| 59 | +.pools{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px} | |
| 60 | +.pool{background:var(--surface-2);border:1px solid var(--line);border-radius:10px;padding:10px 12px} | |
| 61 | +.pool-hd{display:flex;align-items:baseline;justify-content:space-between;gap:8px;margin-bottom:6px} | |
| 62 | +.pool-name{font-size:12px;font-weight:650;color:var(--text)} | |
| 63 | +.pool-pct{font-family:var(--mono);font-size:12.5px;font-weight:700} | |
| 64 | +.pool-pct.ok{color:var(--green)} | |
| 65 | +.pool-pct.warn{color:var(--orange)} | |
| 66 | +.pool-pct.bad{color:var(--red)} | |
| 67 | +.pool-pct.dim{color:var(--text-2)} | |
| 68 | +.meter{height:6px;border-radius:999px;background:var(--line);overflow:hidden} | |
| 69 | +.meter > i{display:block;height:100%;border-radius:999px;background:var(--gray);transition:width .25s var(--ease)} | |
| 70 | +.meter > i.ok{background:var(--green)} | |
| 71 | +.meter > i.warn{background:var(--orange)} | |
| 72 | +.meter > i.bad{background:var(--red)} | |
| 73 | +.pool-reset{margin-top:6px;font-size:11.5px;color:var(--text-2)} | |
| 74 | +.models{display:none;margin-top:10px;padding-top:10px;border-top:1px solid var(--line); | |
| 75 | + grid-template-columns:repeat(2,minmax(0,1fr));gap:4px 14px} | |
| 76 | +.models.show{display:grid} | |
| 77 | +.mrow{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:11.5px;padding:2px 0} | |
| 78 | +.mrow .mid{font-family:var(--mono);color:var(--text-2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | |
| 79 | +.mrow .mpct{font-family:var(--mono);font-weight:650;flex:0 0 auto} | |
| 80 | +.mrow .mpct.ok{color:var(--green)} | |
| 81 | +.mrow .mpct.warn{color:var(--orange)} | |
| 82 | +.mrow .mpct.bad{color:var(--red)} | |
| 83 | +.err-msg{font-size:12px;color:var(--red);padding:4px 0} | |
| 84 | +.empty{padding:18px 16px;text-align:center;color:var(--text-2);font-size:13px} | |
| 85 | +.kv{display:grid;grid-template-columns:120px minmax(0,1fr);gap:5px 12px;font-size:12px} | |
| 86 | +.kv .k{color:var(--text-2)} | |
| 87 | +.kv .v{font-family:var(--mono);word-break:break-all} | |
| 88 | +.note{display:none;margin-bottom:12px;padding:10px 12px;border-radius:10px;font-size:12.5px; | |
| 89 | + border:1px solid var(--line);background:var(--surface-2)} | |
| 90 | +.note.show{display:block} | |
| 91 | +.note.err{color:var(--red);border-color:rgba(255,69,58,.35)} | |
| 92 | +.note.warn{color:var(--orange);border-color:rgba(255,159,10,.35)} | |
| 93 | +.toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0; | |
| 94 | + pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2); | |
| 95 | + color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px; | |
| 96 | + box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease); | |
| 97 | + z-index:9;max-width:calc(100vw - 32px)} | |
| 98 | +.toast.show{opacity:1;transform:translate(-50%,0)} | |
| 99 | +@media (max-width:600px){ | |
| 100 | + #app{padding:12px 12px 32px} | |
| 101 | + .kpis{grid-template-columns:1fr} | |
| 102 | + .pools{grid-template-columns:1fr} | |
| 103 | + .models{grid-template-columns:1fr} | |
| 104 | + .kv{grid-template-columns:1fr;gap:2px 0} | |
| 105 | + .kv .k{margin-top:6px} | |
| 106 | +} | |
| 107 | +</style> | |
| 108 | +</head> | |
| 109 | +<body> | |
| 110 | +<div id="app"> | |
| 111 | + <div class="hd"> | |
| 112 | + <div class="grow"> | |
| 113 | + <h1>Google Quotas</h1> | |
| 114 | + <div class="sub" id="sub">Antigravity account pools on this node</div> | |
| 115 | + </div> | |
| 116 | + <span class="pill off" id="pill"><span class="dot"></span><span id="pillText">Loading</span></span> | |
| 117 | + <button id="themeToggle" class="embed-hide" type="button">Theme</button> | |
| 118 | + </div> | |
| 119 | + | |
| 120 | + <div class="kpis"> | |
| 121 | + <div class="kpi"> | |
| 122 | + <div class="lbl">Active Account</div> | |
| 123 | + <div class="val" id="kpiSelected">-</div> | |
| 124 | + <div class="meta" id="kpiSelectedMeta">selected_account.txt</div> | |
| 125 | + </div> | |
| 126 | + <div class="kpi"> | |
| 127 | + <div class="lbl">Best Gemini</div> | |
| 128 | + <div class="val" id="kpiGemini">-</div> | |
| 129 | + <div class="meta" id="kpiGeminiMeta">Waiting for quota</div> | |
| 130 | + </div> | |
| 131 | + <div class="kpi"> | |
| 132 | + <div class="lbl">Best Claude</div> | |
| 133 | + <div class="val" id="kpiClaude">-</div> | |
| 134 | + <div class="meta" id="kpiClaudeMeta">Waiting for quota</div> | |
| 135 | + </div> | |
| 136 | + </div> | |
| 137 | + | |
| 138 | + <div class="bar-row"> | |
| 139 | + <button class="btn" id="btnRefresh" type="button">Refresh Quotas</button> | |
| 140 | + <button class="btn ghost" id="btnModels" type="button">Show Models</button> | |
| 141 | + <span class="spacer"></span> | |
| 142 | + <span class="status-txt" id="statusTxt"></span> | |
| 143 | + </div> | |
| 144 | + | |
| 145 | + <div class="note" id="banner"></div> | |
| 146 | + <div id="accounts"></div> | |
| 147 | + | |
| 148 | + <div class="card"> | |
| 149 | + <h2>Node Paths</h2> | |
| 150 | + <div class="kv" id="paths"></div> | |
| 151 | + </div> | |
| 152 | +</div> | |
| 153 | + | |
| 154 | +<div class="toast" id="toast"></div> | |
| 155 | + | |
| 156 | +<script> | |
| 157 | +var q=new URLSearchParams(location.search); | |
| 158 | +var node=q.get('node')||''; | |
| 159 | +var sid=q.get('id')||''; | |
| 160 | +var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))|| | |
| 161 | + localStorage.getItem('bot_active_pwd')||''; | |
| 162 | +var HUB=q.get('plugin')||''; | |
| 163 | + | |
| 164 | +function url(action,extra){ | |
| 165 | + return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_google_quota')+ | |
| 166 | + '?action='+encodeURIComponent(action)+ | |
| 167 | + (extra?('&'+extra):'')+ | |
| 168 | + (node?'&node='+encodeURIComponent(node):'')+ | |
| 169 | + (sid?'&id='+encodeURIComponent(sid):'')+ | |
| 170 | + (pwd?'&pwd='+encodeURIComponent(pwd):''); | |
| 171 | +} | |
| 172 | +function hdr(){ | |
| 173 | + var h={}; | |
| 174 | + if(pwd)h['X-Bot-Password']=pwd; | |
| 175 | + return h; | |
| 176 | +} | |
| 177 | +function api(action,extra){ | |
| 178 | + return fetch(url(action,extra),{headers:hdr()}).then(function(r){ | |
| 179 | + return r.json().catch(function(){return {ok:false,error:'bad response'};}); | |
| 180 | + }); | |
| 181 | +} | |
| 182 | + | |
| 183 | +var $=function(id){return document.getElementById(id);}; | |
| 184 | +var state={selected:'',accounts:[],quotas:{},showModels:false,cliPresent:false,loading:false}; | |
| 185 | + | |
| 186 | +function toast(msg){ | |
| 187 | + var t=$('toast');t.textContent=msg;t.classList.add('show'); | |
| 188 | + clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200); | |
| 189 | +} | |
| 190 | +function setBanner(msg,kind){ | |
| 191 | + var el=$('banner'); | |
| 192 | + el.textContent=msg||''; | |
| 193 | + el.className='note'+(msg?' show '+(kind||''):''); | |
| 194 | +} | |
| 195 | +function shortEmail(e){ | |
| 196 | + if(!e)return '-'; | |
| 197 | + var i=e.indexOf('@'); | |
| 198 | + return i>0?e.slice(0,i):e; | |
| 199 | +} | |
| 200 | +function pctClass(pct,exhausted){ | |
| 201 | + if(exhausted||pct===null||pct===undefined||pct<10)return 'bad'; | |
| 202 | + if(pct<50)return 'warn'; | |
| 203 | + return 'ok'; | |
| 204 | +} | |
| 205 | +function fmtPct(pool){ | |
| 206 | + if(!pool)return '...'; | |
| 207 | + if(pool.exhausted||pool.pct===null||pool.pct===undefined)return 'EXHAUSTED'; | |
| 208 | + if(pool.pct<0)return 'N/A'; | |
| 209 | + return pool.pct.toFixed(1)+'%'; | |
| 210 | +} | |
| 211 | +function fmtReset(iso){ | |
| 212 | + if(!iso)return 'Reset: -'; | |
| 213 | + var t=Date.parse(iso); | |
| 214 | + if(isNaN(t))return 'Reset: '+iso; | |
| 215 | + var diff=Math.floor((t-Date.now())/1000); | |
| 216 | + if(diff<=0)return 'Resets soon'; | |
| 217 | + var d=Math.floor(diff/86400); | |
| 218 | + var h=Math.floor((diff%86400)/3600); | |
| 219 | + var m=Math.floor((diff%3600)/60); | |
| 220 | + if(d>0)return 'Resets in '+d+'d '+h+'h'; | |
| 221 | + if(h>0)return 'Resets in '+h+'h '+m+'m'; | |
| 222 | + return 'Resets in '+Math.max(1,m)+'m'; | |
| 223 | +} | |
| 224 | +function el(tag,cls,txt){ | |
| 225 | + var n=document.createElement(tag); | |
| 226 | + if(cls)n.className=cls; | |
| 227 | + if(txt!==undefined&&txt!==null)n.textContent=txt; | |
| 228 | + return n; | |
| 229 | +} | |
| 230 | + | |
| 231 | +function computeBest(){ | |
| 232 | + var bestG=null,bestGP=-1,bestC=null,bestCP=-1; | |
| 233 | + state.accounts.forEach(function(a){ | |
| 234 | + var qd=state.quotas[a.email]; | |
| 235 | + if(!qd||!qd.ok)return; | |
| 236 | + if(qd.gemini&&!qd.gemini.exhausted&&qd.gemini.pct>bestGP){ | |
| 237 | + bestGP=qd.gemini.pct;bestG=a.email; | |
| 238 | + } | |
| 239 | + if(qd.claude&&!qd.claude.exhausted&&qd.claude.pct>bestCP){ | |
| 240 | + bestCP=qd.claude.pct;bestC=a.email; | |
| 241 | + } | |
| 242 | + }); | |
| 243 | + return {gemini:bestG,geminiPct:bestGP,claude:bestC,claudePct:bestCP}; | |
| 244 | +} | |
| 245 | + | |
| 246 | +function renderPool(label,pool,loading){ | |
| 247 | + var box=el('div','pool'); | |
| 248 | + var hd=el('div','pool-hd'); | |
| 249 | + hd.appendChild(el('span','pool-name',label)); | |
| 250 | + var pctEl=el('span','pool-pct'); | |
| 251 | + var bar=el('div','meter'); | |
| 252 | + var fill=el('i'); | |
| 253 | + var rst=el('div','pool-reset'); | |
| 254 | + | |
| 255 | + if(loading&&!pool){ | |
| 256 | + pctEl.className='pool-pct dim'; | |
| 257 | + pctEl.textContent='Checking...'; | |
| 258 | + fill.style.width='0%'; | |
| 259 | + rst.textContent='Querying quota CLI'; | |
| 260 | + }else if(!pool||pool.pct<0){ | |
| 261 | + pctEl.className='pool-pct dim'; | |
| 262 | + pctEl.textContent='N/A'; | |
| 263 | + fill.style.width='0%'; | |
| 264 | + rst.textContent='No buckets reported'; | |
| 265 | + }else{ | |
| 266 | + var cls=pctClass(pool.pct,pool.exhausted); | |
| 267 | + pctEl.className='pool-pct '+cls; | |
| 268 | + pctEl.textContent=fmtPct(pool); | |
| 269 | + var w=pool.exhausted?0:Math.max(0,Math.min(100,pool.pct)); | |
| 270 | + fill.className=cls; | |
| 271 | + fill.style.width=w.toFixed(1)+'%'; | |
| 272 | + rst.textContent=fmtReset(pool.reset_time); | |
| 273 | + } | |
| 274 | + hd.appendChild(pctEl); | |
| 275 | + bar.appendChild(fill); | |
| 276 | + box.appendChild(hd); | |
| 277 | + box.appendChild(bar); | |
| 278 | + box.appendChild(rst); | |
| 279 | + return box; | |
| 280 | +} | |
| 281 | + | |
| 282 | +function render(){ | |
| 283 | + var best=computeBest(); | |
| 284 | + $('kpiSelected').textContent=shortEmail(state.selected); | |
| 285 | + $('kpiSelected').title=state.selected||''; | |
| 286 | + $('kpiSelectedMeta').textContent=state.selected||'None selected'; | |
| 287 | + | |
| 288 | + $('kpiGemini').textContent=best.gemini?shortEmail(best.gemini):'-'; | |
| 289 | + $('kpiGemini').title=best.gemini||''; | |
| 290 | + $('kpiGeminiMeta').textContent=best.gemini?(best.geminiPct.toFixed(1)+'% remaining'):(state.loading?'Checking...':'No quota data'); | |
| 291 | + | |
| 292 | + $('kpiClaude').textContent=best.claude?shortEmail(best.claude):'-'; | |
| 293 | + $('kpiClaude').title=best.claude||''; | |
| 294 | + $('kpiClaudeMeta').textContent=best.claude?(best.claudePct.toFixed(1)+'% remaining'):(state.loading?'Checking...':'No quota data'); | |
| 295 | + | |
| 296 | + var wrap=$('accounts'); | |
| 297 | + wrap.innerHTML=''; | |
| 298 | + if(!state.accounts.length){ | |
| 299 | + var empty=el('div','card empty','No accounts found in antigravity_accounts.json. Sign in with scorpiox-antigravity-login first.'); | |
| 300 | + wrap.appendChild(empty); | |
| 301 | + return; | |
| 302 | + } | |
| 303 | + | |
| 304 | + state.accounts.forEach(function(a){ | |
| 305 | + var isSel=(a.email===state.selected); | |
| 306 | + var qd=state.quotas[a.email]; | |
| 307 | + var card=el('div','card'+(isSel?' selected':'')); | |
| 308 | + | |
| 309 | + var top=el('div','acct-top'); | |
| 310 | + top.appendChild(el('div','acct-email',a.email)); | |
| 311 | + | |
| 312 | + var badges=el('div','badges'); | |
| 313 | + if(isSel)badges.appendChild(el('span','tag sel','Selected')); | |
| 314 | + if(best.gemini===a.email)badges.appendChild(el('span','tag best','Best Gemini')); | |
| 315 | + if(best.claude===a.email)badges.appendChild(el('span','tag best','Best Claude')); | |
| 316 | + if(!a.has_refresh)badges.appendChild(el('span','tag','No refresh token')); | |
| 317 | + top.appendChild(badges); | |
| 318 | + | |
| 319 | + var sw=el('button','btn sm'+(isSel?' ghost':''),isSel?'Active':'Use'); | |
| 320 | + sw.type='button'; | |
| 321 | + sw.disabled=isSel; | |
| 322 | + sw.onclick=function(){switchAccount(a.email,sw);}; | |
| 323 | + top.appendChild(sw); | |
| 324 | + card.appendChild(top); | |
| 325 | + | |
| 326 | + if(qd&&!qd.ok){ | |
| 327 | + card.appendChild(el('div','err-msg','Error: '+(qd.detail||qd.error||'quota fetch failed'))); | |
| 328 | + }else{ | |
| 329 | + var pools=el('div','pools'); | |
| 330 | + pools.appendChild(renderPool('Gemini Pool',qd?qd.gemini:null,state.loading)); | |
| 331 | + pools.appendChild(renderPool('Claude Pool',qd?qd.claude:null,state.loading)); | |
| 332 | + card.appendChild(pools); | |
| 333 | + | |
| 334 | + if(qd&&qd.models&&qd.models.length){ | |
| 335 | + var mgrid=el('div','models'+(state.showModels?' show':'')); | |
| 336 | + qd.models.forEach(function(m){ | |
| 337 | + var row=el('div','mrow'); | |
| 338 | + row.appendChild(el('span','mid',m.id)); | |
| 339 | + var cls=pctClass(m.pct,m.exhausted); | |
| 340 | + row.appendChild(el('span','mpct '+cls,m.exhausted?'EXH':(m.pct.toFixed(1)+'%'))); | |
| 341 | + mgrid.appendChild(row); | |
| 342 | + }); | |
| 343 | + card.appendChild(mgrid); | |
| 344 | + } | |
| 345 | + } | |
| 346 | + wrap.appendChild(card); | |
| 347 | + }); | |
| 348 | +} | |
| 349 | + | |
| 350 | +function switchAccount(email,btn){ | |
| 351 | + btn.disabled=true; | |
| 352 | + btn.textContent='Switching...'; | |
| 353 | + api('switch','account='+encodeURIComponent(email)).then(function(d){ | |
| 354 | + if(!d||!d.ok){ | |
| 355 | + toast((d&&(d.detail||d.error))||'Switch failed'); | |
| 356 | + render(); | |
| 357 | + return; | |
| 358 | + } | |
| 359 | + state.selected=d.selected||email; | |
| 360 | + toast('Selected '+state.selected); | |
| 361 | + render(); | |
| 362 | + }).catch(function(e){ | |
| 363 | + toast('Switch failed: '+e.message); | |
| 364 | + render(); | |
| 365 | + }); | |
| 366 | +} | |
| 367 | + | |
| 368 | +function fetchQuotas(){ | |
| 369 | + if(!state.accounts.length||!state.cliPresent)return; | |
| 370 | + state.loading=true; | |
| 371 | + $('btnRefresh').disabled=true; | |
| 372 | + $('btnRefresh').textContent='Refreshing...'; | |
| 373 | + $('statusTxt').textContent='Querying '+state.accounts.length+' account(s)...'; | |
| 374 | + render(); | |
| 375 | + | |
| 376 | + var queue=state.accounts.slice(); | |
| 377 | + var done=0,total=queue.length; | |
| 378 | + var workers=Math.min(4,total); | |
| 379 | + | |
| 380 | + function next(){ | |
| 381 | + if(!queue.length)return Promise.resolve(); | |
| 382 | + var acct=queue.shift(); | |
| 383 | + return api('quota','account='+encodeURIComponent(acct.email)).then(function(d){ | |
| 384 | + if(d&&d.ok&&d.account){ | |
| 385 | + state.quotas[acct.email]=d.account; | |
| 386 | + }else{ | |
| 387 | + state.quotas[acct.email]={ok:false,error:(d&&d.error)||'failed',detail:d&&d.detail}; | |
| 388 | + } | |
| 389 | + }).catch(function(e){ | |
| 390 | + state.quotas[acct.email]={ok:false,error:e.message}; | |
| 391 | + }).then(function(){ | |
| 392 | + done++; | |
| 393 | + $('statusTxt').textContent='Loaded '+done+'/'+total; | |
| 394 | + render(); | |
| 395 | + return next(); | |
| 396 | + }); | |
| 397 | + } | |
| 398 | + | |
| 399 | + var ps=[]; | |
| 400 | + for(var i=0;i<workers;i++)ps.push(next()); | |
| 401 | + Promise.all(ps).then(function(){ | |
| 402 | + state.loading=false; | |
| 403 | + $('btnRefresh').disabled=false; | |
| 404 | + $('btnRefresh').textContent='Refresh Quotas'; | |
| 405 | + $('statusTxt').textContent='Updated '+new Date().toLocaleTimeString(); | |
| 406 | + render(); | |
| 407 | + }); | |
| 408 | +} | |
| 409 | + | |
| 410 | +function load(){ | |
| 411 | + setBanner(''); | |
| 412 | + api('status').then(function(d){ | |
| 413 | + if(!d||!d.ok){ | |
| 414 | + setBanner((d&&(d.detail||d.error))||'Failed to read accounts','err'); | |
| 415 | + return; | |
| 416 | + } | |
| 417 | + state.selected=d.selected||''; | |
| 418 | + state.accounts=d.accounts||[]; | |
| 419 | + state.cliPresent=!!d.cli_present; | |
| 420 | + | |
| 421 | + var pill=$('pill'),pt=$('pillText'); | |
| 422 | + if(!state.cliPresent){ | |
| 423 | + pill.className='pill bad';pt.textContent='CLI missing'; | |
| 424 | + setBanner('scorpiox-google-quota was not found on PATH. Install SCORPIOX CODE or set GOOGLE_QUOTA_BIN.','warn'); | |
| 425 | + }else if(!state.accounts.length){ | |
| 426 | + pill.className='pill warn';pt.textContent='0 accounts'; | |
| 427 | + }else{ | |
| 428 | + pill.className='pill ok';pt.textContent=state.accounts.length+' account'+(state.accounts.length===1?'':'s'); | |
| 429 | + } | |
| 430 | + | |
| 431 | + var paths=$('paths'); | |
| 432 | + paths.innerHTML=''; | |
| 433 | + [ | |
| 434 | + ['Accounts JSON',d.accounts_path||'-'], | |
| 435 | + ['Selected file',d.selected_path||'-'], | |
| 436 | + ['Quota CLI',d.cli_present?'found':'not found'] | |
| 437 | + ].forEach(function(r){ | |
| 438 | + paths.appendChild(el('div','k',r[0])); | |
| 439 | + paths.appendChild(el('div','v',r[1])); | |
| 440 | + }); | |
| 441 | + | |
| 442 | + render(); | |
| 443 | + if(state.accounts.length&&state.cliPresent)fetchQuotas(); | |
| 444 | + }).catch(function(e){ | |
| 445 | + setBanner('Status failed: '+e.message,'err'); | |
| 446 | + }); | |
| 447 | +} | |
| 448 | + | |
| 449 | +$('btnRefresh').onclick=fetchQuotas; | |
| 450 | +$('btnModels').onclick=function(){ | |
| 451 | + state.showModels=!state.showModels; | |
| 452 | + $('btnModels').textContent=state.showModels?'Hide Models':'Show Models'; | |
| 453 | + render(); | |
| 454 | +}; | |
| 455 | +$('themeToggle').onclick=function(){ | |
| 456 | + if(window.sxApplyTheme&&window.sxTheme){ | |
| 457 | + window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark'); | |
| 458 | + } | |
| 459 | +}; | |
| 460 | +load(); | |
| 461 | +</script> | |
| 462 | +</body></html> |
| 1 | 1 | new file mode 100644 |
| index 0000000..87a7ad6 | ||
| --- /dev/null | ||
| +++ b/src/ui_html.h | ||
| @@ -0,0 +1,470 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | |
| 2 | +#ifndef SX_GQUOTA_UI_HTML_H | |
| 3 | +#define SX_GQUOTA_UI_HTML_H | |
| 4 | + | |
| 5 | +static const char *UI_HTML = | |
| 6 | + "<!DOCTYPE html>\n" | |
| 7 | + "<html lang=\"en\"><head><meta charset=\"utf-8\">\n" | |
| 8 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | |
| 9 | + "<title>google quota</title>\n" | |
| 10 | + "\001\n" | |
| 11 | + "<style>\n" | |
| 12 | + "*{box-sizing:border-box}\n" | |
| 13 | + "html,body{margin:0;min-height:100%}\n" | |
| 14 | + "body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;\n" | |
| 15 | + " line-height:1.5;-webkit-font-smoothing:antialiased}\n" | |
| 16 | + "#app{max-width:880px;margin:0 auto;padding:16px 16px 40px}\n" | |
| 17 | + ".hd{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}\n" | |
| 18 | + ".hd .grow{flex:1 1 auto;min-width:0}\n" | |
| 19 | + ".hd h1{margin:0;font-size:18px;font-weight:650;letter-spacing:-.01em}\n" | |
| 20 | + ".hd .sub{font-size:11.5px;color:var(--text-2);margin-top:2px;white-space:nowrap;\n" | |
| 21 | + " overflow:hidden;text-overflow:ellipsis}\n" | |
| 22 | + ".pill{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:650;\n" | |
| 23 | + " padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-2);\n" | |
| 24 | + " border:1px solid var(--line);white-space:nowrap}\n" | |
| 25 | + ".pill .dot{width:7px;height:7px;border-radius:50%;background:var(--gray);flex:0 0 auto}\n" | |
| 26 | + ".pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n" | |
| 27 | + ".pill.ok .dot{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.15)}\n" | |
| 28 | + ".pill.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}\n" | |
| 29 | + ".pill.warn .dot{background:var(--orange)}\n" | |
| 30 | + ".pill.bad{color:var(--red);border-color:rgba(255,69,58,.35)}\n" | |
| 31 | + ".pill.bad .dot{background:var(--red)}\n" | |
| 32 | + ".pill.off .dot{background:var(--gray)}\n" | |
| 33 | + "#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n" | |
| 34 | + " border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;\n" | |
| 35 | + " font-family:inherit}\n" | |
| 36 | + ".kpis{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin-bottom:12px}\n" | |
| 37 | + ".kpi{background:var(--bg-card);border:1px solid var(--line);border-radius:12px;padding:12px 14px;min-width:0}\n" | |
| 38 | + ".kpi .lbl{font-size:11px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--text-2)}\n" | |
| 39 | + ".kpi .val{margin-top:4px;font-size:15px;font-weight:650;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n" | |
| 40 | + ".kpi .meta{margin-top:2px;font-size:11.5px;color:var(--text-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n" | |
| 41 | + ".bar-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:12px}\n" | |
| 42 | + ".bar-row .spacer{flex:1 1 auto}\n" | |
| 43 | + ".status-txt{font-size:12px;color:var(--text-2)}\n" | |
| 44 | + ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:6px 14px;\n" | |
| 45 | + " font-weight:600;font-size:12.5px;cursor:pointer;font-family:inherit;\n" | |
| 46 | + " transition:transform .12s var(--ease),opacity .12s}\n" | |
| 47 | + ".btn:active{transform:scale(.98)}\n" | |
| 48 | + ".btn:disabled{opacity:.5;cursor:default}\n" | |
| 49 | + ".btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}\n" | |
| 50 | + ".btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | |
| 51 | + ".btn.sm{padding:4px 11px;font-size:11.5px}\n" | |
| 52 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n" | |
| 53 | + " padding:14px 16px;margin-bottom:10px}\n" | |
| 54 | + ".card.selected{border-color:var(--blue)}\n" | |
| 55 | + ".card h2{margin:0 0 4px;font-size:12.5px;font-weight:700;letter-spacing:.08em;\n" | |
| 56 | + " text-transform:uppercase;color:var(--text-2)}\n" | |
| 57 | + ".acct-top{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:10px}\n" | |
| 58 | + ".acct-email{font-family:var(--mono);font-size:13px;font-weight:650;word-break:break-all;flex:1 1 auto;min-width:0}\n" | |
| 59 | + ".badges{display:flex;align-items:center;gap:6px;flex-wrap:wrap}\n" | |
| 60 | + ".tag{font-size:11px;font-weight:650;padding:2px 8px;border-radius:999px;\n" | |
| 61 | + " background:var(--surface-2);color:var(--text-2);border:1px solid var(--line)}\n" | |
| 62 | + ".tag.sel{color:var(--blue);border-color:rgba(10,132,255,.4)}\n" | |
| 63 | + ".tag.best{color:var(--green);border-color:rgba(48,209,88,.35)}\n" | |
| 64 | + ".pools{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}\n" | |
| 65 | + ".pool{background:var(--surface-2);border:1px solid var(--line);border-radius:10px;padding:10px 12px}\n" | |
| 66 | + ".pool-hd{display:flex;align-items:baseline;justify-content:space-between;gap:8px;margin-bottom:6px}\n" | |
| 67 | + ".pool-name{font-size:12px;font-weight:650;color:var(--text)}\n" | |
| 68 | + ".pool-pct{font-family:var(--mono);font-size:12.5px;font-weight:700}\n" | |
| 69 | + ".pool-pct.ok{color:var(--green)}\n" | |
| 70 | + ".pool-pct.warn{color:var(--orange)}\n" | |
| 71 | + ".pool-pct.bad{color:var(--red)}\n" | |
| 72 | + ".pool-pct.dim{color:var(--text-2)}\n" | |
| 73 | + ".meter{height:6px;border-radius:999px;background:var(--line);overflow:hidden}\n" | |
| 74 | + ".meter > i{display:block;height:100%;border-radius:999px;background:var(--gray);transition:width .25s var(--ease)}\n" | |
| 75 | + ".meter > i.ok{background:var(--green)}\n" | |
| 76 | + ".meter > i.warn{background:var(--orange)}\n" | |
| 77 | + ".meter > i.bad{background:var(--red)}\n" | |
| 78 | + ".pool-reset{margin-top:6px;font-size:11.5px;color:var(--text-2)}\n" | |
| 79 | + ".models{display:none;margin-top:10px;padding-top:10px;border-top:1px solid var(--line);\n" | |
| 80 | + " grid-template-columns:repeat(2,minmax(0,1fr));gap:4px 14px}\n" | |
| 81 | + ".models.show{display:grid}\n" | |
| 82 | + ".mrow{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:11.5px;padding:2px 0}\n" | |
| 83 | + ".mrow .mid{font-family:var(--mono);color:var(--text-2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | |
| 84 | + ".mrow .mpct{font-family:var(--mono);font-weight:650;flex:0 0 auto}\n" | |
| 85 | + ".mrow .mpct.ok{color:var(--green)}\n" | |
| 86 | + ".mrow .mpct.warn{color:var(--orange)}\n" | |
| 87 | + ".mrow .mpct.bad{color:var(--red)}\n" | |
| 88 | + ".err-msg{font-size:12px;color:var(--red);padding:4px 0}\n" | |
| 89 | + ".empty{padding:18px 16px;text-align:center;color:var(--text-2);font-size:13px}\n" | |
| 90 | + ".kv{display:grid;grid-template-columns:120px minmax(0,1fr);gap:5px 12px;font-size:12px}\n" | |
| 91 | + ".kv .k{color:var(--text-2)}\n" | |
| 92 | + ".kv .v{font-family:var(--mono);word-break:break-all}\n" | |
| 93 | + ".note{display:none;margin-bottom:12px;padding:10px 12px;border-radius:10px;font-size:12.5px;\n" | |
| 94 | + " border:1px solid var(--line);background:var(--surface-2)}\n" | |
| 95 | + ".note.show{display:block}\n" | |
| 96 | + ".note.err{color:var(--red);border-color:rgba(255,69,58,.35)}\n" | |
| 97 | + ".note.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}\n" | |
| 98 | + ".toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;\n" | |
| 99 | + " pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);\n" | |
| 100 | + " color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;\n" | |
| 101 | + " box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);\n" | |
| 102 | + " z-index:9;max-width:calc(100vw - 32px)}\n" | |
| 103 | + ".toast.show{opacity:1;transform:translate(-50%,0)}\n" | |
| 104 | + "@media (max-width:600px){\n" | |
| 105 | + " #app{padding:12px 12px 32px}\n" | |
| 106 | + " .kpis{grid-template-columns:1fr}\n" | |
| 107 | + " .pools{grid-template-columns:1fr}\n" | |
| 108 | + " .models{grid-template-columns:1fr}\n" | |
| 109 | + " .kv{grid-template-columns:1fr;gap:2px 0}\n" | |
| 110 | + " .kv .k{margin-top:6px}\n" | |
| 111 | + "}\n" | |
| 112 | + "</style>\n" | |
| 113 | + "</head>\n" | |
| 114 | + "<body>\n" | |
| 115 | + "<div id=\"app\">\n" | |
| 116 | + " <div class=\"hd\">\n" | |
| 117 | + " <div class=\"grow\">\n" | |
| 118 | + " <h1>Google Quotas</h1>\n" | |
| 119 | + " <div class=\"sub\" id=\"sub\">Antigravity account pools on this node</div>\n" | |
| 120 | + " </div>\n" | |
| 121 | + " <span class=\"pill off\" id=\"pill\"><span class=\"dot\"></span><span id=\"pillText\">Loading</span></span>\n" | |
| 122 | + " <button id=\"themeToggle\" class=\"embed-hide\" type=\"button\">Theme</button>\n" | |
| 123 | + " </div>\n" | |
| 124 | + "\n" | |
| 125 | + " <div class=\"kpis\">\n" | |
| 126 | + " <div class=\"kpi\">\n" | |
| 127 | + " <div class=\"lbl\">Active Account</div>\n" | |
| 128 | + " <div class=\"val\" id=\"kpiSelected\">-</div>\n" | |
| 129 | + " <div class=\"meta\" id=\"kpiSelectedMeta\">selected_account.txt</div>\n" | |
| 130 | + " </div>\n" | |
| 131 | + " <div class=\"kpi\">\n" | |
| 132 | + " <div class=\"lbl\">Best Gemini</div>\n" | |
| 133 | + " <div class=\"val\" id=\"kpiGemini\">-</div>\n" | |
| 134 | + " <div class=\"meta\" id=\"kpiGeminiMeta\">Waiting for quota</div>\n" | |
| 135 | + " </div>\n" | |
| 136 | + " <div class=\"kpi\">\n" | |
| 137 | + " <div class=\"lbl\">Best Claude</div>\n" | |
| 138 | + " <div class=\"val\" id=\"kpiClaude\">-</div>\n" | |
| 139 | + " <div class=\"meta\" id=\"kpiClaudeMeta\">Waiting for quota</div>\n" | |
| 140 | + " </div>\n" | |
| 141 | + " </div>\n" | |
| 142 | + "\n" | |
| 143 | + " <div class=\"bar-row\">\n" | |
| 144 | + " <button class=\"btn\" id=\"btnRefresh\" type=\"button\">Refresh Quotas</button>\n" | |
| 145 | + " <button class=\"btn ghost\" id=\"btnModels\" type=\"button\">Show Models</button>\n" | |
| 146 | + " <span class=\"spacer\"></span>\n" | |
| 147 | + " <span class=\"status-txt\" id=\"statusTxt\"></span>\n" | |
| 148 | + " </div>\n" | |
| 149 | + "\n" | |
| 150 | + " <div class=\"note\" id=\"banner\"></div>\n" | |
| 151 | + " <div id=\"accounts\"></div>\n" | |
| 152 | + "\n" | |
| 153 | + " <div class=\"card\">\n" | |
| 154 | + " <h2>Node Paths</h2>\n" | |
| 155 | + " <div class=\"kv\" id=\"paths\"></div>\n" | |
| 156 | + " </div>\n" | |
| 157 | + "</div>\n" | |
| 158 | + "\n" | |
| 159 | + "<div class=\"toast\" id=\"toast\"></div>\n" | |
| 160 | + "\n" | |
| 161 | + "<script>\n" | |
| 162 | + "var q=new URLSearchParams(location.search);\n" | |
| 163 | + "var node=q.get('node')||'';\n" | |
| 164 | + "var sid=q.get('id')||'';\n" | |
| 165 | + "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n" | |
| 166 | + " localStorage.getItem('bot_active_pwd')||'';\n" | |
| 167 | + "var HUB=q.get('plugin')||'';\n" | |
| 168 | + "\n" | |
| 169 | + "function url(action,extra){\n" | |
| 170 | + " return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_google_quota')+\n" | |
| 171 | + " '?action='+encodeURIComponent(action)+\n" | |
| 172 | + " (extra?('&'+extra):'')+\n" | |
| 173 | + " (node?'&node='+encodeURIComponent(node):'')+\n" | |
| 174 | + " (sid?'&id='+encodeURIComponent(sid):'')+\n" | |
| 175 | + " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n" | |
| 176 | + "}\n" | |
| 177 | + "function hdr(){\n" | |
| 178 | + " var h={};\n" | |
| 179 | + " if(pwd)h['X-Bot-Password']=pwd;\n" | |
| 180 | + " return h;\n" | |
| 181 | + "}\n" | |
| 182 | + "function api(action,extra){\n" | |
| 183 | + " return fetch(url(action,extra),{headers:hdr()}).then(function(r){\n" | |
| 184 | + " return r.json().catch(function(){return {ok:false,error:'bad response'};});\n" | |
| 185 | + " });\n" | |
| 186 | + "}\n" | |
| 187 | + "\n" | |
| 188 | + "var $=function(id){return document.getElementById(id);};\n" | |
| 189 | + "var state={selected:'',accounts:[],quotas:{},showModels:false,cliPresent:false,loading:false};\n" | |
| 190 | + "\n" | |
| 191 | + "function toast(msg){\n" | |
| 192 | + " var t=$('toast');t.textContent=msg;t.classList.add('show');\n" | |
| 193 | + " clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);\n" | |
| 194 | + "}\n" | |
| 195 | + "function setBanner(msg,kind){\n" | |
| 196 | + " var el=$('banner');\n" | |
| 197 | + " el.textContent=msg||'';\n" | |
| 198 | + " el.className='note'+(msg?' show '+(kind||''):'');\n" | |
| 199 | + "}\n" | |
| 200 | + "function shortEmail(e){\n" | |
| 201 | + " if(!e)return '-';\n" | |
| 202 | + " var i=e.indexOf('@');\n" | |
| 203 | + " return i>0?e.slice(0,i):e;\n" | |
| 204 | + "}\n" | |
| 205 | + "function pctClass(pct,exhausted){\n" | |
| 206 | + " if(exhausted||pct===null||pct===undefined||pct<10)return 'bad';\n" | |
| 207 | + " if(pct<50)return 'warn';\n" | |
| 208 | + " return 'ok';\n" | |
| 209 | + "}\n" | |
| 210 | + "function fmtPct(pool){\n" | |
| 211 | + " if(!pool)return '...';\n" | |
| 212 | + " if(pool.exhausted||pool.pct===null||pool.pct===undefined)return 'EXHAUSTED';\n" | |
| 213 | + " if(pool.pct<0)return 'N/A';\n" | |
| 214 | + " return pool.pct.toFixed(1)+'%';\n" | |
| 215 | + "}\n" | |
| 216 | + "function fmtReset(iso){\n" | |
| 217 | + " if(!iso)return 'Reset: -';\n" | |
| 218 | + " var t=Date.parse(iso);\n" | |
| 219 | + " if(isNaN(t))return 'Reset: '+iso;\n" | |
| 220 | + " var diff=Math.floor((t-Date.now())/1000);\n" | |
| 221 | + " if(diff<=0)return 'Resets soon';\n" | |
| 222 | + " var d=Math.floor(diff/86400);\n" | |
| 223 | + " var h=Math.floor((diff%86400)/3600);\n" | |
| 224 | + " var m=Math.floor((diff%3600)/60);\n" | |
| 225 | + " if(d>0)return 'Resets in '+d+'d '+h+'h';\n" | |
| 226 | + " if(h>0)return 'Resets in '+h+'h '+m+'m';\n" | |
| 227 | + " return 'Resets in '+Math.max(1,m)+'m';\n" | |
| 228 | + "}\n" | |
| 229 | + "function el(tag,cls,txt){\n" | |
| 230 | + " var n=document.createElement(tag);\n" | |
| 231 | + " if(cls)n.className=cls;\n" | |
| 232 | + " if(txt!==undefined&&txt!==null)n.textContent=txt;\n" | |
| 233 | + " return n;\n" | |
| 234 | + "}\n" | |
| 235 | + "\n" | |
| 236 | + "function computeBest(){\n" | |
| 237 | + " var bestG=null,bestGP=-1,bestC=null,bestCP=-1;\n" | |
| 238 | + " state.accounts.forEach(function(a){\n" | |
| 239 | + " var qd=state.quotas[a.email];\n" | |
| 240 | + " if(!qd||!qd.ok)return;\n" | |
| 241 | + " if(qd.gemini&&!qd.gemini.exhausted&&qd.gemini.pct>bestGP){\n" | |
| 242 | + " bestGP=qd.gemini.pct;bestG=a.email;\n" | |
| 243 | + " }\n" | |
| 244 | + " if(qd.claude&&!qd.claude.exhausted&&qd.claude.pct>bestCP){\n" | |
| 245 | + " bestCP=qd.claude.pct;bestC=a.email;\n" | |
| 246 | + " }\n" | |
| 247 | + " });\n" | |
| 248 | + " return {gemini:bestG,geminiPct:bestGP,claude:bestC,claudePct:bestCP};\n" | |
| 249 | + "}\n" | |
| 250 | + "\n" | |
| 251 | + "function renderPool(label,pool,loading){\n" | |
| 252 | + " var box=el('div','pool');\n" | |
| 253 | + " var hd=el('div','pool-hd');\n" | |
| 254 | + " hd.appendChild(el('span','pool-name',label));\n" | |
| 255 | + " var pctEl=el('span','pool-pct');\n" | |
| 256 | + " var bar=el('div','meter');\n" | |
| 257 | + " var fill=el('i');\n" | |
| 258 | + " var rst=el('div','pool-reset');\n" | |
| 259 | + "\n" | |
| 260 | + " if(loading&&!pool){\n" | |
| 261 | + " pctEl.className='pool-pct dim';\n" | |
| 262 | + " pctEl.textContent='Checking...';\n" | |
| 263 | + " fill.style.width='0%';\n" | |
| 264 | + " rst.textContent='Querying quota CLI';\n" | |
| 265 | + " }else if(!pool||pool.pct<0){\n" | |
| 266 | + " pctEl.className='pool-pct dim';\n" | |
| 267 | + " pctEl.textContent='N/A';\n" | |
| 268 | + " fill.style.width='0%';\n" | |
| 269 | + " rst.textContent='No buckets reported';\n" | |
| 270 | + " }else{\n" | |
| 271 | + " var cls=pctClass(pool.pct,pool.exhausted);\n" | |
| 272 | + " pctEl.className='pool-pct '+cls;\n" | |
| 273 | + " pctEl.textContent=fmtPct(pool);\n" | |
| 274 | + " var w=pool.exhausted?0:Math.max(0,Math.min(100,pool.pct));\n" | |
| 275 | + " fill.className=cls;\n" | |
| 276 | + " fill.style.width=w.toFixed(1)+'%';\n" | |
| 277 | + " rst.textContent=fmtReset(pool.reset_time);\n" | |
| 278 | + " }\n" | |
| 279 | + " hd.appendChild(pctEl);\n" | |
| 280 | + " bar.appendChild(fill);\n" | |
| 281 | + " box.appendChild(hd);\n" | |
| 282 | + " box.appendChild(bar);\n" | |
| 283 | + " box.appendChild(rst);\n" | |
| 284 | + " return box;\n" | |
| 285 | + "}\n" | |
| 286 | + "\n" | |
| 287 | + "function render(){\n" | |
| 288 | + " var best=computeBest();\n" | |
| 289 | + " $('kpiSelected').textContent=shortEmail(state.selected);\n" | |
| 290 | + " $('kpiSelected').title=state.selected||'';\n" | |
| 291 | + " $('kpiSelectedMeta').textContent=state.selected||'None selected';\n" | |
| 292 | + "\n" | |
| 293 | + " $('kpiGemini').textContent=best.gemini?shortEmail(best.gemini):'-';\n" | |
| 294 | + " $('kpiGemini').title=best.gemini||'';\n" | |
| 295 | + " $('kpiGeminiMeta').textContent=best.gemini?(best.geminiPct.toFixed(1)+'% remaining'):(state.loading?'Checking...':'No quota data');\n" | |
| 296 | + "\n" | |
| 297 | + " $('kpiClaude').textContent=best.claude?shortEmail(best.claude):'-';\n" | |
| 298 | + " $('kpiClaude').title=best.claude||'';\n" | |
| 299 | + " $('kpiClaudeMeta').textContent=best.claude?(best.claudePct.toFixed(1)+'% remaining'):(state.loading?'Checking...':'No quota data');\n" | |
| 300 | + "\n" | |
| 301 | + " var wrap=$('accounts');\n" | |
| 302 | + " wrap.innerHTML='';\n" | |
| 303 | + " if(!state.accounts.length){\n" | |
| 304 | + " var empty=el('div','card empty','No accounts found in antigravity_accounts.json. Sign in with scorpiox-antigravity-login first.');\n" | |
| 305 | + " wrap.appendChild(empty);\n" | |
| 306 | + " return;\n" | |
| 307 | + " }\n" | |
| 308 | + "\n" | |
| 309 | + " state.accounts.forEach(function(a){\n" | |
| 310 | + " var isSel=(a.email===state.selected);\n" | |
| 311 | + " var qd=state.quotas[a.email];\n" | |
| 312 | + " var card=el('div','card'+(isSel?' selected':''));\n" | |
| 313 | + "\n" | |
| 314 | + " var top=el('div','acct-top');\n" | |
| 315 | + " top.appendChild(el('div','acct-email',a.email));\n" | |
| 316 | + "\n" | |
| 317 | + " var badges=el('div','badges');\n" | |
| 318 | + " if(isSel)badges.appendChild(el('span','tag sel','Selected'));\n" | |
| 319 | + " if(best.gemini===a.email)badges.appendChild(el('span','tag best','Best Gemini'));\n" | |
| 320 | + " if(best.claude===a.email)badges.appendChild(el('span','tag best','Best Claude'));\n" | |
| 321 | + " if(!a.has_refresh)badges.appendChild(el('span','tag','No refresh token'));\n" | |
| 322 | + " top.appendChild(badges);\n" | |
| 323 | + "\n" | |
| 324 | + " var sw=el('button','btn sm'+(isSel?' ghost':''),isSel?'Active':'Use');\n" | |
| 325 | + " sw.type='button';\n" | |
| 326 | + " sw.disabled=isSel;\n" | |
| 327 | + " sw.onclick=function(){switchAccount(a.email,sw);};\n" | |
| 328 | + " top.appendChild(sw);\n" | |
| 329 | + " card.appendChild(top);\n" | |
| 330 | + "\n" | |
| 331 | + " if(qd&&!qd.ok){\n" | |
| 332 | + " card.appendChild(el('div','err-msg','Error: '+(qd.detail||qd.error||'quota fetch failed')));\n" | |
| 333 | + " }else{\n" | |
| 334 | + " var pools=el('div','pools');\n" | |
| 335 | + " pools.appendChild(renderPool('Gemini Pool',qd?qd.gemini:null,state.loading));\n" | |
| 336 | + " pools.appendChild(renderPool('Claude Pool',qd?qd.claude:null,state.loading));\n" | |
| 337 | + " card.appendChild(pools);\n" | |
| 338 | + "\n" | |
| 339 | + " if(qd&&qd.models&&qd.models.length){\n" | |
| 340 | + " var mgrid=el('div','models'+(state.showModels?' show':''));\n" | |
| 341 | + " qd.models.forEach(function(m){\n" | |
| 342 | + " var row=el('div','mrow');\n" | |
| 343 | + " row.appendChild(el('span','mid',m.id));\n" | |
| 344 | + " var cls=pctClass(m.pct,m.exhausted);\n" | |
| 345 | + " row.appendChild(el('span','mpct '+cls,m.exhausted?'EXH':(m.pct.toFixed(1)+'%')));\n" | |
| 346 | + " mgrid.appendChild(row);\n" | |
| 347 | + " });\n" | |
| 348 | + " card.appendChild(mgrid);\n" | |
| 349 | + " }\n" | |
| 350 | + " }\n" | |
| 351 | + " wrap.appendChild(card);\n" | |
| 352 | + " });\n" | |
| 353 | + "}\n" | |
| 354 | + "\n" | |
| 355 | + "function switchAccount(email,btn){\n" | |
| 356 | + " btn.disabled=true;\n" | |
| 357 | + " btn.textContent='Switching...';\n" | |
| 358 | + " api('switch','account='+encodeURIComponent(email)).then(function(d){\n" | |
| 359 | + " if(!d||!d.ok){\n" | |
| 360 | + " toast((d&&(d.detail||d.error))||'Switch failed');\n" | |
| 361 | + " render();\n" | |
| 362 | + " return;\n" | |
| 363 | + " }\n" | |
| 364 | + " state.selected=d.selected||email;\n" | |
| 365 | + " toast('Selected '+state.selected);\n" | |
| 366 | + " render();\n" | |
| 367 | + " }).catch(function(e){\n" | |
| 368 | + " toast('Switch failed: '+e.message);\n" | |
| 369 | + " render();\n" | |
| 370 | + " });\n" | |
| 371 | + "}\n" | |
| 372 | + "\n" | |
| 373 | + "function fetchQuotas(){\n" | |
| 374 | + " if(!state.accounts.length||!state.cliPresent)return;\n" | |
| 375 | + " state.loading=true;\n" | |
| 376 | + " $('btnRefresh').disabled=true;\n" | |
| 377 | + " $('btnRefresh').textContent='Refreshing...';\n" | |
| 378 | + " $('statusTxt').textContent='Querying '+state.accounts.length+' account(s)...';\n" | |
| 379 | + " render();\n" | |
| 380 | + "\n" | |
| 381 | + " var queue=state.accounts.slice();\n" | |
| 382 | + " var done=0,total=queue.length;\n" | |
| 383 | + " var workers=Math.min(4,total);\n" | |
| 384 | + "\n" | |
| 385 | + " function next(){\n" | |
| 386 | + " if(!queue.length)return Promise.resolve();\n" | |
| 387 | + " var acct=queue.shift();\n" | |
| 388 | + " return api('quota','account='+encodeURIComponent(acct.email)).then(function(d){\n" | |
| 389 | + " if(d&&d.ok&&d.account){\n" | |
| 390 | + " state.quotas[acct.email]=d.account;\n" | |
| 391 | + " }else{\n" | |
| 392 | + " state.quotas[acct.email]={ok:false,error:(d&&d.error)||'failed',detail:d&&d.detail};\n" | |
| 393 | + " }\n" | |
| 394 | + " }).catch(function(e){\n" | |
| 395 | + " state.quotas[acct.email]={ok:false,error:e.message};\n" | |
| 396 | + " }).then(function(){\n" | |
| 397 | + " done++;\n" | |
| 398 | + " $('statusTxt').textContent='Loaded '+done+'/'+total;\n" | |
| 399 | + " render();\n" | |
| 400 | + " return next();\n" | |
| 401 | + " });\n" | |
| 402 | + " }\n" | |
| 403 | + "\n" | |
| 404 | + " var ps=[];\n" | |
| 405 | + " for(var i=0;i<workers;i++)ps.push(next());\n" | |
| 406 | + " Promise.all(ps).then(function(){\n" | |
| 407 | + " state.loading=false;\n" | |
| 408 | + " $('btnRefresh').disabled=false;\n" | |
| 409 | + " $('btnRefresh').textContent='Refresh Quotas';\n" | |
| 410 | + " $('statusTxt').textContent='Updated '+new Date().toLocaleTimeString();\n" | |
| 411 | + " render();\n" | |
| 412 | + " });\n" | |
| 413 | + "}\n" | |
| 414 | + "\n" | |
| 415 | + "function load(){\n" | |
| 416 | + " setBanner('');\n" | |
| 417 | + " api('status').then(function(d){\n" | |
| 418 | + " if(!d||!d.ok){\n" | |
| 419 | + " setBanner((d&&(d.detail||d.error))||'Failed to read accounts','err');\n" | |
| 420 | + " return;\n" | |
| 421 | + " }\n" | |
| 422 | + " state.selected=d.selected||'';\n" | |
| 423 | + " state.accounts=d.accounts||[];\n" | |
| 424 | + " state.cliPresent=!!d.cli_present;\n" | |
| 425 | + "\n" | |
| 426 | + " var pill=$('pill'),pt=$('pillText');\n" | |
| 427 | + " if(!state.cliPresent){\n" | |
| 428 | + " pill.className='pill bad';pt.textContent='CLI missing';\n" | |
| 429 | + " setBanner('scorpiox-google-quota was not found on PATH. Install SCORPIOX CODE or set GOOGLE_QUOTA_BIN.','warn');\n" | |
| 430 | + " }else if(!state.accounts.length){\n" | |
| 431 | + " pill.className='pill warn';pt.textContent='0 accounts';\n" | |
| 432 | + " }else{\n" | |
| 433 | + " pill.className='pill ok';pt.textContent=state.accounts.length+' account'+(state.accounts.length===1?'':'s');\n" | |
| 434 | + " }\n" | |
| 435 | + "\n" | |
| 436 | + " var paths=$('paths');\n" | |
| 437 | + " paths.innerHTML='';\n" | |
| 438 | + " [\n" | |
| 439 | + " ['Accounts JSON',d.accounts_path||'-'],\n" | |
| 440 | + " ['Selected file',d.selected_path||'-'],\n" | |
| 441 | + " ['Quota CLI',d.cli_present?'found':'not found']\n" | |
| 442 | + " ].forEach(function(r){\n" | |
| 443 | + " paths.appendChild(el('div','k',r[0]));\n" | |
| 444 | + " paths.appendChild(el('div','v',r[1]));\n" | |
| 445 | + " });\n" | |
| 446 | + "\n" | |
| 447 | + " render();\n" | |
| 448 | + " if(state.accounts.length&&state.cliPresent)fetchQuotas();\n" | |
| 449 | + " }).catch(function(e){\n" | |
| 450 | + " setBanner('Status failed: '+e.message,'err');\n" | |
| 451 | + " });\n" | |
| 452 | + "}\n" | |
| 453 | + "\n" | |
| 454 | + "$('btnRefresh').onclick=fetchQuotas;\n" | |
| 455 | + "$('btnModels').onclick=function(){\n" | |
| 456 | + " state.showModels=!state.showModels;\n" | |
| 457 | + " $('btnModels').textContent=state.showModels?'Hide Models':'Show Models';\n" | |
| 458 | + " render();\n" | |
| 459 | + "};\n" | |
| 460 | + "$('themeToggle').onclick=function(){\n" | |
| 461 | + " if(window.sxApplyTheme&&window.sxTheme){\n" | |
| 462 | + " window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');\n" | |
| 463 | + " }\n" | |
| 464 | + "};\n" | |
| 465 | + "load();\n" | |
| 466 | + "</script>\n" | |
| 467 | + "\002</body></html>\n" | |
| 468 | + ; | |
| 469 | + | |
| 470 | +#endif /* SX_GQUOTA_UI_HTML_H */ |
| 1 | 1 | new file mode 100755 |
| index 0000000..1169c80 | ||
| --- /dev/null | ||
| +++ b/tests/mock_quota.sh | ||
| @@ -0,0 +1,68 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# Deterministic mock for scorpiox-google-quota used by tests/run.sh. | |
| 3 | +acct="" | |
| 4 | +while [ $# -gt 0 ]; do | |
| 5 | + case "$1" in | |
| 6 | + --account) acct="$2"; shift 2 ;; | |
| 7 | + --json) shift ;; | |
| 8 | + *) shift ;; | |
| 9 | + esac | |
| 10 | +done | |
| 11 | + | |
| 12 | +# Verify the plugin sanitized inherited token/profile overrides. | |
| 13 | +if [ -n "${GOOGLE_ACCESS_TOKEN:-}" ]; then | |
| 14 | + echo "error: GOOGLE_ACCESS_TOKEN leaked into child env" >&2 | |
| 15 | + exit 1 | |
| 16 | +fi | |
| 17 | +if [ "${GOOGLE_TOKEN_SOURCE:-}" != "local" ]; then | |
| 18 | + echo "error: expected GOOGLE_TOKEN_SOURCE=local" >&2 | |
| 19 | + exit 1 | |
| 20 | +fi | |
| 21 | + | |
| 22 | +echo "INFO : ya29.MOCK-TOKEN-MUST-NOT-LEAK" >&2 | |
| 23 | + | |
| 24 | +case "$acct" in | |
| 25 | + alpha@example.com) | |
| 26 | + cat <<'EOF' | |
| 27 | +{ | |
| 28 | + "ok": true, | |
| 29 | + "email": "alpha@example.com", | |
| 30 | + "project": "proj-alpha", | |
| 31 | + "endpoint": "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota", | |
| 32 | + "buckets": [ | |
| 33 | + {"tokenType": "WTUS", "modelId": "chat_20706", "remainingFraction": 1}, | |
| 34 | + {"resetTime": "2026-11-25T06:00:00Z", "tokenType": "WTUS", "modelId": "claude-opus-4-6-thinking", "remainingFraction": 1}, | |
| 35 | + {"resetTime": "2026-11-25T06:00:00Z", "tokenType": "WTUS", "modelId": "claude-sonnet-4-6", "remainingFraction": 1}, | |
| 36 | + {"resetTime": "2026-11-25T03:00:00Z", "tokenType": "WTUS", "modelId": "gemini-3.8-flash-tiered", "remainingFraction": 0.855}, | |
| 37 | + {"resetTime": "2026-11-25T03:00:00Z", "tokenType": "WTUS", "modelId": "gemini-4-hydrogen-sonar", "remainingFraction": 0.855}, | |
| 38 | + {"tokenType": "WTUS", "modelId": "tab_flash_lite_preview", "remainingFraction": 1} | |
| 39 | + ] | |
| 40 | +} | |
| 41 | +EOF | |
| 42 | + exit 0 | |
| 43 | + ;; | |
| 44 | + beta@example.com) | |
| 45 | + cat <<'EOF' | |
| 46 | +{ | |
| 47 | + "ok": true, | |
| 48 | + "email": "beta@example.com", | |
| 49 | + "project": "aicode-consumers", | |
| 50 | + "endpoint": "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota", | |
| 51 | + "buckets": [ | |
| 52 | + {"resetTime": "2026-11-25T08:00:00Z", "tokenType": "WTUS", "modelId": "claude-sonnet-4-6", "remainingFraction": 0.42}, | |
| 53 | + {"resetTime": "2026-11-25T04:00:00Z", "tokenType": "WTUS", "modelId": "gemini-3.8-flash-tiered", "remainingFraction": null}, | |
| 54 | + {"resetTime": "2026-11-25T04:00:00Z", "tokenType": "WTUS", "modelId": "gemini-4-hydrogen-sonar"} | |
| 55 | + ] | |
| 56 | +} | |
| 57 | +EOF | |
| 58 | + exit 0 | |
| 59 | + ;; | |
| 60 | + broken@example.com) | |
| 61 | + echo "error: invalid_grant" >&2 | |
| 62 | + exit 1 | |
| 63 | + ;; | |
| 64 | + *) | |
| 65 | + echo "error: unknown mock account $acct" >&2 | |
| 66 | + exit 1 | |
| 67 | + ;; | |
| 68 | +esac |
| 1 | 1 | new file mode 100755 |
| index 0000000..6de407f | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,268 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh - offline checks for plugin_google_quota across all 3 modes. | |
| 3 | +# | |
| 4 | +# Runs against ./plugin_google_quota with credential paths and the quota CLI | |
| 5 | +# redirected at throwaway fixtures, proving the contract without network access. | |
| 6 | + | |
| 7 | +set -u | |
| 8 | + | |
| 9 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | |
| 10 | +cd "$ROOT" || exit 1 | |
| 11 | + | |
| 12 | +BIN=./plugin_google_quota | |
| 13 | +PASS=0 | |
| 14 | +FAIL=0 | |
| 15 | + | |
| 16 | +if [ -t 1 ]; then | |
| 17 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 18 | +else | |
| 19 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 20 | +fi | |
| 21 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 22 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 23 | + | |
| 24 | +check() { | |
| 25 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 26 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | |
| 27 | + fi | |
| 28 | +} | |
| 29 | + | |
| 30 | +check_not() { | |
| 31 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 32 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | |
| 33 | + fi | |
| 34 | +} | |
| 35 | + | |
| 36 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 37 | + | |
| 38 | +body() { | |
| 39 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | |
| 40 | + BEGIN { inhdr = 0 } | |
| 41 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options):/) { inhdr = 1; next } | |
| 42 | + inhdr && $0 == "" { inhdr = 0; next } | |
| 43 | + inhdr { next } | |
| 44 | + { print } | |
| 45 | + ' | |
| 46 | +} | |
| 47 | + | |
| 48 | +json_ok() { | |
| 49 | + expr=${3:-True} | |
| 50 | + if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then | |
| 51 | + pass "$1" | |
| 52 | + else | |
| 53 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | |
| 54 | + fi | |
| 55 | +} | |
| 56 | + | |
| 57 | +api() { body "$(QUERY_STRING="$1" $BIN)"; } | |
| 58 | +apiraw() { QUERY_STRING="$1" $BIN; } | |
| 59 | + | |
| 60 | +# ---------------------------------------------------------------- build | |
| 61 | +section "build" | |
| 62 | +if [ ! -x "$BIN" ]; then | |
| 63 | + gcc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -Wno-format-truncation -I src -o "$BIN" src/plugin_google_quota.c || { | |
| 64 | + fail "native build"; exit 1; } | |
| 65 | +fi | |
| 66 | +pass "native binary present" | |
| 67 | + | |
| 68 | +if python3 tools/gen_ui.py --check >/dev/null 2>&1; then | |
| 69 | + pass "src/ui_html.h is in sync with src/ui.html" | |
| 70 | +else | |
| 71 | + fail "src/ui_html.h is stale - run tools/gen_ui.py" | |
| 72 | +fi | |
| 73 | + | |
| 74 | +check "ui header is marked generated" "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)" | |
| 75 | + | |
| 76 | +# ---------------------------------------------------------------- fixtures | |
| 77 | +FIX=$(mktemp -d 2>/dev/null || mktemp -d -t gqfix) | |
| 78 | +trap 'rm -rf "$FIX"' EXIT | |
| 79 | + | |
| 80 | +mkdir -p "$FIX/none" "$FIX/empty" "$FIX/full" | |
| 81 | +chmod +x "$ROOT/tests/mock_quota.sh" | |
| 82 | +export GOOGLE_QUOTA_BIN="$ROOT/tests/mock_quota.sh" | |
| 83 | +export GOOGLE_ACCESS_TOKEN="ya29.INHERITED-TOKEN-MUST-BE-CLEARED" | |
| 84 | + | |
| 85 | +: > "$FIX/empty/antigravity_accounts.json" | |
| 86 | + | |
| 87 | +cat > "$FIX/full/antigravity_accounts.json" <<'EOF' | |
| 88 | +[ | |
| 89 | + {"email": "alpha@example.com", "refresh_token": "1//MOCK-REFRESH-TOKEN-MUST-NOT-LEAK-A"}, | |
| 90 | + {"email": "beta@example.com", "refresh_token": "1//MOCK-REFRESH-TOKEN-MUST-NOT-LEAK-B"}, | |
| 91 | + {"email": "broken@example.com", "refresh_token": "1//MOCK-REFRESH-TOKEN-MUST-NOT-LEAK-C"} | |
| 92 | +] | |
| 93 | +EOF | |
| 94 | +printf 'beta@example.com\n' > "$FIX/full/selected_account.txt" | |
| 95 | + | |
| 96 | +# ---------------------------------------------------------------- meta & auth | |
| 97 | +section "meta & auth" | |
| 98 | +META=$(BOT_PASSWORD=secret-pass $BIN --meta) | |
| 99 | +check "--meta returns short name and desc without auth" '{"name":"google quota","desc":"Account quotas"}' "$META" | |
| 100 | + | |
| 101 | +META_ENV=$(BOT_PASSWORD=secret-pass SX_PLUGIN_META=1 $BIN) | |
| 102 | +check "SX_PLUGIN_META=1 works without auth" '{"name":"google quota","desc":"Account quotas"}' "$META_ENV" | |
| 103 | + | |
| 104 | +VER=$($BIN --version) | |
| 105 | +check "--version prints plugin id and version" "plugin_google_quota 1.0.0" "$VER" | |
| 106 | + | |
| 107 | +UNAUTH=$(BOT_PASSWORD=secret-pass QUERY_STRING="action=status" $BIN) | |
| 108 | +check "missing password returns 401" "Status: 401 Unauthorized" "$UNAUTH" | |
| 109 | + | |
| 110 | +AUTH_HDR=$(BOT_PASSWORD=secret-pass HTTP_X_BOT_PASSWORD=secret-pass GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status") | |
| 111 | +json_ok "X-Bot-Password header authorizes request" "$AUTH_HDR" "d['ok'] is True" | |
| 112 | + | |
| 113 | +AUTH_BEARER=$(BOT_PASSWORD=secret-pass HTTP_AUTHORIZATION="Bearer secret-pass" GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status") | |
| 114 | +json_ok "Bearer header authorizes request" "$AUTH_BEARER" "d['ok'] is True" | |
| 115 | + | |
| 116 | +AUTH_QS=$(BOT_PASSWORD=secret-pass GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status&pwd=secret-pass") | |
| 117 | +json_ok "?pwd= query param authorizes request" "$AUTH_QS" "d['ok'] is True" | |
| 118 | + | |
| 119 | +# ---------------------------------------------------------------- status | |
| 120 | +section "status" | |
| 121 | +ST_NONE=$(GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status") | |
| 122 | +json_ok "missing accounts file returns count 0" "$ST_NONE" "d['ok'] is True and d['count'] == 0 and d['cli_present'] is True" | |
| 123 | + | |
| 124 | +ST_EMPTY=$(GOOGLE_ACCOUNTS_FILE="$FIX/empty/antigravity_accounts.json" api "action=status") | |
| 125 | +json_ok "empty accounts file returns count 0" "$ST_EMPTY" "d['ok'] is True and d['count'] == 0" | |
| 126 | + | |
| 127 | +ST_FULL=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=status") | |
| 128 | +json_ok "full accounts status lists 3 accounts and selected" "$ST_FULL" \ | |
| 129 | + "d['ok'] is True and d['count'] == 3 and d['selected'] == 'beta@example.com' and d['accounts'][1]['selected'] is True and all(a['has_refresh'] for a in d['accounts'])" | |
| 130 | +check_not "status never leaks refresh_token" "MOCK-REFRESH-TOKEN" "$ST_FULL" | |
| 131 | + | |
| 132 | +ST_NOCLI=$(GOOGLE_QUOTA_BIN="/nonexistent/scorpiox-google-quota" GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=status") | |
| 133 | +json_ok "missing CLI sets cli_present false" "$ST_NOCLI" "d['ok'] is True and d['cli_present'] is False" | |
| 134 | + | |
| 135 | +# ---------------------------------------------------------------- quota | |
| 136 | +section "quota" | |
| 137 | +Q_ONE=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota&account=alpha@example.com") | |
| 138 | +json_ok "single account quota parses gemini and claude pools" "$Q_ONE" \ | |
| 139 | + "d['ok'] is True and d['account']['ok'] is True and abs(d['account']['gemini']['pct'] - 85.5) < 0.01 and abs(d['account']['claude']['pct'] - 100.0) < 0.01 and len(d['account']['models']) == 4" | |
| 140 | +check_not "single quota never leaks token" "MOCK-TOKEN" "$Q_ONE" | |
| 141 | +check_not "single quota never leaks refresh token" "MOCK-REFRESH-TOKEN" "$Q_ONE" | |
| 142 | + | |
| 143 | +Q_EXH=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota&account=beta@example.com") | |
| 144 | +json_ok "null/missing remainingFraction marks gemini pool exhausted" "$Q_EXH" \ | |
| 145 | + "d['ok'] is True and d['account']['gemini']['exhausted'] is True and d['account']['gemini']['pct'] == 0.0 and abs(d['account']['claude']['pct'] - 42.0) < 0.01" | |
| 146 | + | |
| 147 | +Q_ALL=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota") | |
| 148 | +json_ok "all-accounts quota aggregates best_gemini, best_claude, and broken account" "$Q_ALL" \ | |
| 149 | + "d['ok'] is True and d['count'] == 3 and d['best_gemini'] == 'alpha@example.com' and d['best_claude'] == 'alpha@example.com' and d['accounts'][2]['ok'] is False" | |
| 150 | +check_not "all-accounts quota never leaks token" "MOCK-TOKEN" "$Q_ALL" | |
| 151 | + | |
| 152 | +Q_FMT=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "format=json") | |
| 153 | +json_ok "?format=json returns full quota JSON" "$Q_FMT" "d['ok'] is True and d['count'] == 3 and 'best_gemini' in d" | |
| 154 | + | |
| 155 | +Q_UNK=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" apiraw "action=quota&account=nobody@example.com") | |
| 156 | +check "unknown account returns 404" "Status: 404 Not Found" "$Q_UNK" | |
| 157 | + | |
| 158 | +Q_NOCLI=$(GOOGLE_QUOTA_BIN="/nonexistent/scorpiox-google-quota" GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota") | |
| 159 | +json_ok "missing CLI returns cli_unavailable" "$Q_NOCLI" "d['ok'] is False and d['error'] == 'cli_unavailable'" | |
| 160 | + | |
| 161 | +# ---------------------------------------------------------------- switch | |
| 162 | +section "switch" | |
| 163 | +SW_OK=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=switch&account=alpha@example.com") | |
| 164 | +json_ok "switch updates selected account" "$SW_OK" "d['ok'] is True and d['selected'] == 'alpha@example.com'" | |
| 165 | +check "selected_account.txt persisted" "alpha@example.com" "$(cat "$FIX/full/selected_account.txt")" | |
| 166 | + | |
| 167 | +printf '{"account":"beta@example.com"}' > "$FIX/post.json" | |
| 168 | +SW_PBF=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" POST_BODY_FILE="$FIX/post.json" api "action=switch") | |
| 169 | +json_ok "switch accepts POST_BODY_FILE JSON" "$SW_PBF" "d['ok'] is True and d['selected'] == 'beta@example.com'" | |
| 170 | + | |
| 171 | +SW_BAD=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" apiraw "action=switch&account=bad;rm") | |
| 172 | +check "invalid email rejected with 400" "Status: 400 Bad Request" "$SW_BAD" | |
| 173 | + | |
| 174 | +SW_UNK=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" apiraw "action=switch&account=nobody@example.com") | |
| 175 | +check "unknown email rejected with 404" "Status: 404 Not Found" "$SW_UNK" | |
| 176 | + | |
| 177 | +# ---------------------------------------------------------------- HTML UI | |
| 178 | +section "HTML UI" | |
| 179 | +HTML=$(apiraw "") | |
| 180 | +check "HTML emits Content-Type text/html" "Content-Type: text/html" "$HTML" | |
| 181 | +check "HTML includes bot theme prepaint" "bot_theme" "$HTML" | |
| 182 | +check "HTML includes theme handoff" "sx-theme-request" "$HTML" | |
| 183 | +check "HTML uses two-route API helper" "plugin_google_quota" "$HTML" | |
| 184 | +check "HTML hides theme toggle in embed mode" "embed-hide" "$HTML" | |
| 185 | +check_not "HTML loads no CDN script" "<script src=" "$HTML" | |
| 186 | +check_not "HTML references no external host script" "cdnjs" "$HTML" | |
| 187 | +check_not "HTML makes no outbound fetch to googleapis" "googleapis.com" "$HTML" | |
| 188 | + | |
| 189 | +printf '%s' "$HTML" > "$FIX/page.html" | |
| 190 | +if python3 - "$FIX/page.html" <<'PY' | |
| 191 | +import re, sys | |
| 192 | +html = open(sys.argv[1], encoding='utf-8').read() | |
| 193 | +ids = set(re.findall(r'id="([^"]+)"', html)) | |
| 194 | +missing = [i for i in re.findall(r"\$\('([^']+)'\)", html) if i not in ids] | |
| 195 | +if missing: | |
| 196 | + print("missing ids:", missing) | |
| 197 | + sys.exit(1) | |
| 198 | +PY | |
| 199 | +then pass "every JS element id exists in the markup" | |
| 200 | +else fail "JS references missing element id"; fi | |
| 201 | + | |
| 202 | +# ---------------------------------------------------------------- source hygiene | |
| 203 | +section "source hygiene" | |
| 204 | +check_not "source has no OAuth client secret" "GOCSPX" "$(cat src/plugin_google_quota.c)" | |
| 205 | +check_not "source has no Google API key" "AIza" "$(cat src/plugin_google_quota.c)" | |
| 206 | +check_not "source has no GitHub token" "ghp_" "$(cat src/plugin_google_quota.c)" | |
| 207 | +check_not "source has no internal 192.168 address" "192.168." "$(cat src/plugin_google_quota.c src/ui.html)" | |
| 208 | +check_not "source has no internal 10.0 address" "10.0." "$(cat src/plugin_google_quota.c src/ui.html)" | |
| 209 | +check_not "source has no internal 172.16 address" "172.16" "$(cat src/plugin_google_quota.c src/ui.html)" | |
| 210 | + | |
| 211 | +if python3 - src/plugin_google_quota.c src/ui.html src/bot_theme_plugin.h <<'PY' | |
| 212 | +import sys, unicodedata | |
| 213 | +bad = [] | |
| 214 | +for path in sys.argv[1:]: | |
| 215 | + for n, line in enumerate(open(path, encoding='utf-8'), 1): | |
| 216 | + for ch in line: | |
| 217 | + o = ord(ch) | |
| 218 | + if o < 0x2000: | |
| 219 | + continue | |
| 220 | + if 0x2190 <= o <= 0x21FF: | |
| 221 | + continue | |
| 222 | + if unicodedata.category(ch) in ('So', 'Sk') or 0x1F000 <= o <= 0x1FAFF: | |
| 223 | + bad.append('%s:%d %r' % (path, n, ch)) | |
| 224 | +if bad: | |
| 225 | + print('\n'.join(bad[:10])) | |
| 226 | + sys.exit(1) | |
| 227 | +PY | |
| 228 | +then pass "no emoji in source, page or theme header" | |
| 229 | +else fail "emoji found in shipped sources"; fi | |
| 230 | + | |
| 231 | +# ---------------------------------------------------------------- cross-target builds | |
| 232 | +section "cross-target builds" | |
| 233 | +if command -v musl-gcc >/dev/null 2>&1; then | |
| 234 | + if musl-gcc -O2 -std=c99 -static -I src -o "$FIX/musl-bin" src/plugin_google_quota.c 2>/dev/null; then | |
| 235 | + pass "static musl build" | |
| 236 | + check "musl binary reports --meta" '"name":"google quota"' "$("$FIX/musl-bin" --meta)" | |
| 237 | + else fail "static musl build"; fi | |
| 238 | +else | |
| 239 | + echo " skip musl-gcc not installed" | |
| 240 | +fi | |
| 241 | + | |
| 242 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | |
| 243 | + if x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -o "$FIX/win-bin.exe" src/plugin_google_quota.c 2>/dev/null; then | |
| 244 | + pass "MinGW-w64 build" | |
| 245 | + if [ "$(head -c 2 "$FIX/win-bin.exe")" = "MZ" ]; then | |
| 246 | + pass "Windows build has PE header" | |
| 247 | + else fail "Windows build missing MZ header"; fi | |
| 248 | + else fail "MinGW-w64 build"; fi | |
| 249 | +else | |
| 250 | + echo " skip x86_64-w64-mingw32-gcc not installed" | |
| 251 | +fi | |
| 252 | + | |
| 253 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | |
| 254 | + if aarch64-linux-gnu-gcc -O2 -std=c99 -static -I src -o "$FIX/arm-bin" src/plugin_google_quota.c 2>/dev/null; then | |
| 255 | + pass "static arm64 build" | |
| 256 | + else fail "static arm64 build"; fi | |
| 257 | +else | |
| 258 | + echo " skip aarch64-linux-gnu-gcc not installed" | |
| 259 | +fi | |
| 260 | + | |
| 261 | +if gcc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$FIX/fortify-bin" src/plugin_google_quota.c 2>/dev/null; then | |
| 262 | + pass "_FORTIFY_SOURCE=2 build" | |
| 263 | +else | |
| 264 | + fail "_FORTIFY_SOURCE=2 build" | |
| 265 | +fi | |
| 266 | + | |
| 267 | +printf '\n%sSummary:%s %d passed, %d failed\n' "$C_B" "$C_0" "$PASS" "$FAIL" | |
| 268 | +[ "$FAIL" -eq 0 ] |
| 1 | 1 | new file mode 100755 |
| index 0000000..ab1822e | ||
| --- /dev/null | ||
| +++ b/tools/gen_ui.py | ||
| @@ -0,0 +1,105 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tools/gen_ui.py - compile src/ui.html into src/ui_html.h. | |
| 3 | + | |
| 4 | +The page lives in one readable file (src/ui.html) so it can be diffed and | |
| 5 | +reviewed like any other source. This script turns it into a single C string | |
| 6 | +constant with two control-character placeholders: | |
| 7 | + | |
| 8 | + 0x01 -> the bot theme prepaint script + <style> + theme tokens | |
| 9 | + 0x02 -> the bot theme handoff script (just before </body>) | |
| 10 | + | |
| 11 | +main() splits the constant on those bytes and emits the macros from | |
| 12 | +src/bot_theme_plugin.h in their place, so the theme can never drift out of | |
| 13 | +sync with the rest of the bot. | |
| 14 | + | |
| 15 | + python3 tools/gen_ui.py # write src/ui_html.h | |
| 16 | + python3 tools/gen_ui.py --check # exit 1 when the header is stale | |
| 17 | +""" | |
| 18 | + | |
| 19 | +import os | |
| 20 | +import sys | |
| 21 | + | |
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 23 | +SRC = os.path.join(ROOT, "src", "ui.html") | |
| 24 | +OUT = os.path.join(ROOT, "src", "ui_html.h") | |
| 25 | + | |
| 26 | +TOKENS = "<!--TOKENS-->" | |
| 27 | +MARK_TOKENS = "\u0001" | |
| 28 | +MARK_HANDOFF = "\u0002" | |
| 29 | + | |
| 30 | + | |
| 31 | +def c_literal(text): | |
| 32 | + """Escape text for a C string literal, one line per source line.""" | |
| 33 | + out = [] | |
| 34 | + for line in text.splitlines(True): | |
| 35 | + piece = [] | |
| 36 | + for ch in line: | |
| 37 | + if ch == "\\": | |
| 38 | + piece.append("\\\\") | |
| 39 | + elif ch == '"': | |
| 40 | + piece.append('\\"') | |
| 41 | + elif ch == "\n": | |
| 42 | + piece.append("\\n") | |
| 43 | + elif ch == "\r": | |
| 44 | + piece.append("\\r") | |
| 45 | + elif ch == "\t": | |
| 46 | + piece.append("\\t") | |
| 47 | + elif MARK_TOKENS: | |
| 48 | + if ch == MARK_TOKENS: | |
| 49 | + piece.append("\\001") | |
| 50 | + elif ch == MARK_HANDOFF: | |
| 51 | + piece.append("\\002") | |
| 52 | + elif ord(ch) < 0x20: | |
| 53 | + piece.append("\\%03o" % ord(ch)) | |
| 54 | + else: | |
| 55 | + piece.append(ch) | |
| 56 | + out.append(' "%s"\n' % "".join(piece)) | |
| 57 | + return "".join(out) | |
| 58 | + | |
| 59 | + | |
| 60 | +def render(): | |
| 61 | + with open(SRC, "r", encoding="utf-8") as f: | |
| 62 | + html = f.read() | |
| 63 | + | |
| 64 | + if TOKENS not in html: | |
| 65 | + raise SystemExit("src/ui.html has no %s placeholder" % TOKENS) | |
| 66 | + html = html.replace(TOKENS, MARK_TOKENS) | |
| 67 | + | |
| 68 | + if "</body>" not in html: | |
| 69 | + raise SystemExit("src/ui.html has no </body>") | |
| 70 | + html = html.replace("</body>", MARK_HANDOFF + "</body>", 1) | |
| 71 | + | |
| 72 | + header = ( | |
| 73 | + "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n" | |
| 74 | + "#ifndef SX_GQUOTA_UI_HTML_H\n" | |
| 75 | + "#define SX_GQUOTA_UI_HTML_H\n" | |
| 76 | + "\n" | |
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | |
| 78 | + "\n" | |
| 79 | + "#endif /* SX_GQUOTA_UI_HTML_H */\n" | |
| 80 | + ) | |
| 81 | + return header | |
| 82 | + | |
| 83 | + | |
| 84 | +def main(): | |
| 85 | + header = render() | |
| 86 | + check = "--check" in sys.argv[1:] | |
| 87 | + if check: | |
| 88 | + try: | |
| 89 | + with open(OUT, "r", encoding="utf-8") as f: | |
| 90 | + cur = f.read() | |
| 91 | + except OSError: | |
| 92 | + cur = "" | |
| 93 | + if cur != header: | |
| 94 | + sys.stderr.write("src/ui_html.h is stale - run tools/gen_ui.py\n") | |
| 95 | + return 1 | |
| 96 | + print("src/ui_html.h is up to date") | |
| 97 | + return 0 | |
| 98 | + with open(OUT, "w", encoding="utf-8") as f: | |
| 99 | + f.write(header) | |
| 100 | + print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header))) | |
| 101 | + return 0 | |
| 102 | + | |
| 103 | + | |
| 104 | +if __name__ == "__main__": | |
| 105 | + sys.exit(main()) | |
| 0 | 106 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..f6b013a | index 0000000..f6b013a | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,16 @@ | @@ -0,0 +1,16 @@ | ||
| 1 | +# build artifacts | ||
| 2 | +/plugin_google_quota | ||
| 3 | +/plugin_google_quota.exe | ||
| 4 | +/plugin_google_quota.musl | ||
| 5 | +/plugin_google_quota.arm64 | ||
| 6 | +/plugin_google_quota.macos-arm64 | ||
| 7 | +/plugin_google_quota.macos-x86_64 | ||
| 8 | +bin/ | ||
| 9 | + | ||
| 10 | +# test scratch | ||
| 11 | +*.tmp | ||
| 12 | +/tests/fixtures-out/ | ||
| 13 | + | ||
| 14 | +# python tooling | ||
| 15 | +__pycache__/ | ||
| 16 | +*.pyc |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..ef80120 | index 0000000..ef80120 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/LICENSE | +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2026 SCORPIOX INC | ||
| 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. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..bf29f83 | index 0000000..bf29f83 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,78 @@ | @@ -0,0 +1,78 @@ | ||
| 1 | +# plugin_google_quota - SCORPIOX BOT open-source Google Antigravity quota monitor | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_google_quota | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_google_quota.musl | ||
| 6 | +# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_google_quota.arm64 | ||
| 7 | +# make win64 MinGW-w64 static -> ./plugin_google_quota.exe | ||
| 8 | +# make macos Apple clang -> ./plugin_google_quota (run this on macOS) | ||
| 9 | +# make ui regenerate src/ui_html.h from src/ui.html | ||
| 10 | +# make install copy the binary into this node's plugin directory | ||
| 11 | +# make test build + run tests/run.sh | ||
| 12 | +# make clean | ||
| 13 | + | ||
| 14 | +CC ?= cc | ||
| 15 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -Wno-format-truncation -I src | ||
| 16 | +MUSL_CC ?= musl-gcc | ||
| 17 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static | ||
| 18 | +ARM_CC ?= aarch64-linux-gnu-gcc | ||
| 19 | +ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static | ||
| 20 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 21 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static | ||
| 22 | +SRC := src/plugin_google_quota.c | ||
| 23 | +UI_SRC := src/ui.html | ||
| 24 | +UI_HDR := src/ui_html.h | ||
| 25 | +BIN := plugin_google_quota | ||
| 26 | +EXE := plugin_google_quota.exe | ||
| 27 | + | ||
| 28 | +.PHONY: all native musl arm64 win64 macos ui install test clean help | ||
| 29 | + | ||
| 30 | +all: native | ||
| 31 | + | ||
| 32 | +$(UI_HDR): $(UI_SRC) tools/gen_ui.py | ||
| 33 | + @echo "==> regenerating $(UI_HDR)" | ||
| 34 | + python3 tools/gen_ui.py | ||
| 35 | + | ||
| 36 | +ui: $(UI_HDR) | ||
| 37 | + | ||
| 38 | +native: $(BIN) | ||
| 39 | + | ||
| 40 | +$(BIN): $(SRC) $(UI_HDR) | ||
| 41 | + @echo "==> native build ($(CC))" | ||
| 42 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 43 | + | ||
| 44 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | ||
| 45 | +musl: $(SRC) $(UI_HDR) | ||
| 46 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 47 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC) | ||
| 48 | + | ||
| 49 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | ||
| 50 | +arm64: $(SRC) $(UI_HDR) | ||
| 51 | + @echo "==> static arm64 build ($(ARM_CC))" | ||
| 52 | + $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC) | ||
| 53 | + | ||
| 54 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | ||
| 55 | +win64: $(SRC) $(UI_HDR) | ||
| 56 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 57 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) | ||
| 58 | + | ||
| 59 | +# Apple clang build (run this on macOS) | ||
| 60 | +macos: $(SRC) $(UI_HDR) | ||
| 61 | + @echo "==> Apple clang build" | ||
| 62 | + clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o $(BIN) $(SRC) | ||
| 63 | + | ||
| 64 | +install: $(BIN) | ||
| 65 | + @dest="$${HOME}/.scorpiox/plugins"; [ -d /workspace ] && dest="/workspace/.scorpiox/plugins"; \ | ||
| 66 | + mkdir -p "$$dest" && cp $(BIN) "$$dest/$(BIN)" && chmod 0755 "$$dest/$(BIN)" && \ | ||
| 67 | + echo "==> installed $$dest/$(BIN)" | ||
| 68 | + | ||
| 69 | +test: $(BIN) | ||
| 70 | + sh tests/run.sh | ||
| 71 | + | ||
| 72 | +clean: | ||
| 73 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 \ | ||
| 74 | + $(BIN).macos-arm64 $(BIN).macos-x86_64 | ||
| 75 | + rm -rf bin tests/__pycache__ | ||
| 76 | + | ||
| 77 | +help: | ||
| 78 | + @sed -n '2,14p' $(MAKEFILE_LIST) |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..209efcb | index 0000000..209efcb | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,77 @@ | @@ -0,0 +1,77 @@ | ||
| 1 | +# plugin_google_quota — Google Antigravity Quotas for SCORPIOX BOT | ||
| 2 | + | ||
| 3 | +`plugin_google_quota` is a **zero-dependency C99 node plugin** for | ||
| 4 | +[SCORPIOX BOT](https://bot.scorpiox.net). It reads the local Google Antigravity | ||
| 5 | +account list (`antigravity_accounts.json`) and active selection | ||
| 6 | +(`selected_account.txt`), queries per-model quota pools through the node's | ||
| 7 | +`scorpiox-google-quota` CLI, and lets you switch the active account in one | ||
| 8 | +click. | ||
| 9 | + | ||
| 10 | +* `--meta` -> `{"name":"google quota","desc":"Account quotas"}` | ||
| 11 | +* `--version` -> `plugin_google_quota 1.0.0` | ||
| 12 | +* Catalog slug `google-quota`, category `devtools` | ||
| 13 | +* Public source: <https://plugingit.scorpiox.net/scorpiox-bot-plugin-google-quota.git> | ||
| 14 | +* Prebuilt binaries: <https://dist.scorpiox.net/bot-plugins/google-quota/> | ||
| 15 | + | ||
| 16 | +--- | ||
| 17 | + | ||
| 18 | +## Why this plugin has no TLS code and no client secret | ||
| 19 | + | ||
| 20 | +Refreshing Google OAuth tokens and calling `cloudcode-pa` requires an OAuth | ||
| 21 | +client identity and TLS. A public, clean-room repository must not carry an | ||
| 22 | +OAuth client secret, so this plugin does not speak TLS at all. It drives the | ||
| 23 | +node's own `scorpiox-google-quota` CLI (which ships with SCORPIOX CODE) and | ||
| 24 | +reads the same credential files written by `scorpiox-antigravity-login`: | ||
| 25 | + | ||
| 26 | +| Path | Access | Purpose | | ||
| 27 | +|---|---|---| | ||
| 28 | +| `~/.config/google-accounts/antigravity_accounts.json` | Read-only | Account emails + `refresh_token` presence | | ||
| 29 | +| `~/.config/google-accounts/selected_account.txt` | Read / Write | Active account email (updated on `switch`) | | ||
| 30 | + | ||
| 31 | +**No token is ever printed, logged or returned.** When reading | ||
| 32 | +`antigravity_accounts.json`, only `email` and a boolean `has_refresh` flag are | ||
| 33 | +extracted; token strings are never copied or emitted. | ||
| 34 | + | ||
| 35 | +--- | ||
| 36 | + | ||
| 37 | +## Requirements on the node | ||
| 38 | + | ||
| 39 | +| Platform | Needs | | ||
| 40 | +|---|---| | ||
| 41 | +| Linux / macOS / Windows | `scorpiox-google-quota` on `PATH` (ships with SCORPIOX CODE) | | ||
| 42 | +| Build / runtime | Zero external library dependencies (pure C99 stdlib) | | ||
| 43 | + | ||
| 44 | +--- | ||
| 45 | + | ||
| 46 | +## Environment overrides | ||
| 47 | + | ||
| 48 | +| Variable | Effect | | ||
| 49 | +|---|---| | ||
| 50 | +| `GOOGLE_ACCOUNTS_FILE` | Path to `antigravity_accounts.json` (also accepts `ANTIGRAVITY_CREDS_PATH`) | | ||
| 51 | +| `GOOGLE_SELECTED_FILE` | Path to `selected_account.txt` (default: sibling of `GOOGLE_ACCOUNTS_FILE`) | | ||
| 52 | +| `GOOGLE_QUOTA_BIN` | Quota CLI binary (default: `scorpiox-google-quota`) | | ||
| 53 | +| `BOT_PASSWORD` | When set, every route except `--meta` and `--version` requires it | | ||
| 54 | + | ||
| 55 | +--- | ||
| 56 | + | ||
| 57 | +## API | ||
| 58 | + | ||
| 59 | +All actions accept `X-Bot-Password`, `Authorization: Bearer`, or `?pwd=`. | ||
| 60 | + | ||
| 61 | +* `GET ?action=status` — fast local read of configured accounts, `selected`, paths, and `cli_present` | ||
| 62 | +* `GET ?action=quota` (or `?format=json`) — queries all accounts concurrently and returns Gemini/Claude pool summaries, reset times, per-model buckets, `best_gemini`, and `best_claude` | ||
| 63 | +* `GET ?action=quota&account=<email>` — queries a single account | ||
| 64 | +* `GET/POST ?action=switch&account=<email>` (or JSON body `{"account":"..."}`) — validates the email against `antigravity_accounts.json` and writes `selected_account.txt` | ||
| 65 | + | ||
| 66 | +--- | ||
| 67 | + | ||
| 68 | +## Build, test & install | ||
| 69 | + | ||
| 70 | +```sh | ||
| 71 | +make # build ./plugin_google_quota | ||
| 72 | +make test # run offline test suite (tests/run.sh) | ||
| 73 | +make install # install to ~/.scorpiox/plugins/ (or /workspace/.scorpiox/plugins/) | ||
| 74 | +``` | ||
| 75 | + | ||
| 76 | +Cross-compile targets: `make musl`, `make arm64`, `make win64`, `make macos`, or | ||
| 77 | +`powershell -ExecutionPolicy Bypass -File build.ps1` on Windows. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..bdc0406 | index 0000000..bdc0406 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/build.ps1 | +++ b/build.ps1 | ||
| @@ -0,0 +1,48 @@ | @@ -0,0 +1,48 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_google_quota | ||
| 2 | +# | ||
| 3 | +# Usage (from the repo root, PowerShell): | ||
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 5 | +# | ||
| 6 | +# Produces .\plugin_google_quota.exe (static PE, runs on any Windows 10/11 x64 node). | ||
| 7 | +# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin). | ||
| 8 | + | ||
| 9 | +$ErrorActionPreference = "Stop" | ||
| 10 | +$ScriptDir = $PSScriptRoot | ||
| 11 | +Push-Location $ScriptDir | ||
| 12 | +try { | ||
| 13 | + $Src = Join-Path $ScriptDir "src\plugin_google_quota.c" | ||
| 14 | + $Out = Join-Path $ScriptDir "plugin_google_quota.exe" | ||
| 15 | + $Cc = "x86_64-w64-mingw32-gcc" | ||
| 16 | + | ||
| 17 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | ||
| 18 | + | ||
| 19 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | ||
| 20 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | ||
| 21 | + $Cc = "C:\gcc16\bin\gcc.exe" | ||
| 22 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | ||
| 23 | + $Cc = "gcc" | ||
| 24 | + } else { | ||
| 25 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | ||
| 26 | + } | ||
| 27 | + } | ||
| 28 | + | ||
| 29 | + if (Get-Command python -ErrorAction SilentlyContinue) { | ||
| 30 | + python tools\gen_ui.py | ||
| 31 | + } | ||
| 32 | + | ||
| 33 | + Write-Host "==> building plugin_google_quota.exe with $Cc" | ||
| 34 | + & $Cc -O2 -std=c99 -Wall -Wextra -I src -static -o $Out $Src | ||
| 35 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | ||
| 36 | + | ||
| 37 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | ||
| 38 | + | ||
| 39 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | ||
| 40 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | ||
| 41 | + throw "output is not a PE executable (missing MZ header)" | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | + Write-Host "==> ok: $Out ($($bytes.Length) bytes)" | ||
| 45 | + Write-Host " smoke test: .\plugin_google_quota.exe --meta" | ||
| 46 | +} finally { | ||
| 47 | + Pop-Location | ||
| 48 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..58d102f | index 0000000..58d102f | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,17 @@ | @@ -0,0 +1,17 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "google-quota", | ||
| 3 | + "id": "plugin_google_quota", | ||
| 4 | + "title": "Google Account Quotas", | ||
| 5 | + "summary": "Zero-dependency Google Antigravity multi-account quota monitor and active-account switcher for your node. Reads the local antigravity_accounts.json and selected_account.txt files, queries per-model quota pools through the node's scorpiox-google-quota CLI, and lets you switch the active account in one click. Holds no OAuth client secret and never prints, logs or returns any refresh or access token.", | ||
| 6 | + "category": "devtools", | ||
| 7 | + "license": "MIT", | ||
| 8 | + "capabilities": [ | ||
| 9 | + "spawn_quota_cli", | ||
| 10 | + "read_credentials_metadata", | ||
| 11 | + "write_selected_account", | ||
| 12 | + "network_via_quota_cli" | ||
| 13 | + ], | ||
| 14 | + "trust_notice": "Executes native C code on your node. It runs scorpiox-google-quota (from SCORPIOX CODE) as a child process; that binary is what talks to Google over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only ~/.config/google-accounts/antigravity_accounts.json (email and token presence only) and selected_account.txt, writes only selected_account.txt on switch, and never prints or returns any token value.", | ||
| 15 | + "author": "SCORPIOX INC", | ||
| 16 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-google-quota" | ||
| 17 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..0bdcbd5 | index 0000000..0bdcbd5 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/release-dist.sh | +++ b/release-dist.sh | ||
| @@ -0,0 +1,13 @@ | @@ -0,0 +1,13 @@ | ||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# release-dist.sh - audit, build and publish plugin_google_quota via scorpiox-cli-botplugin. | ||
| 3 | +set -euo pipefail | ||
| 4 | + | ||
| 5 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | ||
| 6 | +cd "$ROOT" | ||
| 7 | + | ||
| 8 | +if ! command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 9 | + echo "error: scorpiox-cli-botplugin is required to publish" >&2 | ||
| 10 | + exit 1 | ||
| 11 | +fi | ||
| 12 | + | ||
| 13 | +exec scorpiox-cli-botplugin publish "$ROOT" "$@" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0dd243b | index 0000000..0dd243b | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | @@ -0,0 +1,129 @@ | ||
| 1 | +/* | ||
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | ||
| 3 | + * | ||
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | ||
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | ||
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | ||
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | ||
| 8 | + * localStorage key, same prepaint order. | ||
| 9 | + * | ||
| 10 | + * Three rules, and nothing else: | ||
| 11 | + * | ||
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | ||
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | ||
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | ||
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | ||
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | ||
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | ||
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | ||
| 19 | + * it was already open when the bot changed theme. | ||
| 20 | + * | ||
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | ||
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | ||
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | ||
| 24 | + * are var() references, one definition covers both themes. | ||
| 25 | + * | ||
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 27 | + */ | ||
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | ||
| 29 | +#define SX_BOT_THEME_PLUGIN_H | ||
| 30 | + | ||
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | ||
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | ||
| 33 | +#define SX_BOT_THEME_TOKENS \ | ||
| 34 | +":root{color-scheme:dark;" \ | ||
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | ||
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | ||
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | ||
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | ||
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | ||
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | ||
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | ||
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | ||
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | ||
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | ||
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | ||
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | ||
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | ||
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | ||
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | ||
| 50 | +"}" \ | ||
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | ||
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 58 | + "--accent-dim:#0066d6;" \ | ||
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 62 | + "color-scheme:light}}" \ | ||
| 63 | +"html[data-theme=light]{" \ | ||
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 70 | + "--accent-dim:#0066d6;" \ | ||
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 74 | + "color-scheme:light}" \ | ||
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | ||
| 76 | +"*{box-sizing:border-box}" \ | ||
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | ||
| 78 | + "-webkit-font-smoothing:antialiased}" \ | ||
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | ||
| 80 | +"button:active{transform:scale(.98)}" \ | ||
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | ||
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | ||
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | ||
| 84 | +" * hides its own back link and its own toggle. */" \ | ||
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | ||
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | ||
| 87 | + | ||
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | ||
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | ||
| 90 | + * html.embedded so the embed rules apply before first paint. */ | ||
| 91 | +#define SX_BOT_THEME_PREPAINT \ | ||
| 92 | +"<script>(function(){var t='';" \ | ||
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | ||
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | ||
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | ||
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | ||
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 99 | +"})();</script>\n" | ||
| 100 | + | ||
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | ||
| 102 | + * at startup in case it changed while this page was already open. Fires the | ||
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | ||
| 104 | + * re-skin themselves from one listener. */ | ||
| 105 | +#define SX_BOT_THEME_HANDOFF \ | ||
| 106 | +"<script>(function(){" \ | ||
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | ||
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | ||
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | ||
| 112 | +"window.sxApplyTheme=apply;" \ | ||
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | ||
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | ||
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | ||
| 116 | +"})();</script>\n" | ||
| 117 | + | ||
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | ||
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | ||
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | ||
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | ||
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | ||
| 123 | + | ||
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | ||
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | ||
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | ||
| 127 | +"})();</script>\n" | ||
| 128 | + | ||
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..97e4490 | index 0000000..97e4490 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_google_quota.c | +++ b/src/plugin_google_quota.c | ||
| @@ -0,0 +1,1542 @@ | @@ -0,0 +1,1542 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_google_quota - SCORPIOX BOT open-source Google Antigravity | ||
| 3 | + * multi-account quota monitor and active-account switcher for your node. | ||
| 4 | + * | ||
| 5 | + * A single clean-room C99 binary that serves THREE modes: | ||
| 6 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata | ||
| 7 | + * 2. ?action=... / ?format=json -> JSON node API | ||
| 8 | + * 3. GET (default) -> responsive HTML UI | ||
| 9 | + * | ||
| 10 | + * DESIGN NOTE (why there is no TLS and no OAuth client secret here): | ||
| 11 | + * Refreshing Google OAuth tokens and calling cloudcode-pa requires an OAuth | ||
| 12 | + * client identity and TLS. A public clean-room repository must never carry an | ||
| 13 | + * OAuth client secret, so this plugin does not speak TLS at all. It reads the | ||
| 14 | + * local account list and active selection files written by | ||
| 15 | + * scorpiox-antigravity-login and invokes the node's scorpiox-google-quota CLI: | ||
| 16 | + * | ||
| 17 | + * ~/.config/google-accounts/antigravity_accounts.json (emails + presence) | ||
| 18 | + * ~/.config/google-accounts/selected_account.txt (active email) | ||
| 19 | + * | ||
| 20 | + * Every path and the quota CLI can be overridden for testing or relocation: | ||
| 21 | + * | ||
| 22 | + * GOOGLE_ACCOUNTS_FILE accounts JSON (also accepts ANTIGRAVITY_CREDS_PATH) | ||
| 23 | + * GOOGLE_SELECTED_FILE selected account file (default: sibling selected_account.txt) | ||
| 24 | + * GOOGLE_QUOTA_BIN quota CLI binary (default: scorpiox-google-quota) | ||
| 25 | + * | ||
| 26 | + * NO TOKEN IS EVER PRINTED, LOGGED OR RETURNED. When reading | ||
| 27 | + * antigravity_accounts.json, only email and refresh_token presence (boolean) | ||
| 28 | + * are recorded; token strings are never copied or emitted. | ||
| 29 | + * | ||
| 30 | + * Zero external dependencies. Builds with gcc, musl-gcc -static, Apple clang | ||
| 31 | + * and x86_64-w64-mingw32-gcc -static. | ||
| 32 | + * | ||
| 33 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 34 | + */ | ||
| 35 | + | ||
| 36 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 37 | +# define _WIN32_WINNT 0x0601 | ||
| 38 | +#endif | ||
| 39 | + | ||
| 40 | +#if !defined(_WIN32) | ||
| 41 | +# define _POSIX_C_SOURCE 200809L | ||
| 42 | +# define _DEFAULT_SOURCE 1 | ||
| 43 | +# if defined(__APPLE__) | ||
| 44 | +# define _DARWIN_C_SOURCE 1 | ||
| 45 | +# endif | ||
| 46 | +#endif | ||
| 47 | + | ||
| 48 | +#include <stdio.h> | ||
| 49 | +#include <stdlib.h> | ||
| 50 | +#include <string.h> | ||
| 51 | +#include <ctype.h> | ||
| 52 | +#include <errno.h> | ||
| 53 | +#include <stdarg.h> | ||
| 54 | + | ||
| 55 | +#if defined(_WIN32) | ||
| 56 | +# define WIN32_LEAN_AND_MEAN | ||
| 57 | +# include <windows.h> | ||
| 58 | +# include <direct.h> | ||
| 59 | +# include <io.h> | ||
| 60 | +# define popen _popen | ||
| 61 | +# define pclose _pclose | ||
| 62 | +# define PATH_SEP '\\' | ||
| 63 | +#else | ||
| 64 | +# include <unistd.h> | ||
| 65 | +# include <fcntl.h> | ||
| 66 | +# include <poll.h> | ||
| 67 | +# include <sys/stat.h> | ||
| 68 | +# include <sys/types.h> | ||
| 69 | +# include <sys/wait.h> | ||
| 70 | +# define PATH_SEP '/' | ||
| 71 | +#endif | ||
| 72 | + | ||
| 73 | +#include "bot_theme_plugin.h" | ||
| 74 | +#include "ui_html.h" | ||
| 75 | + | ||
| 76 | +#define PLUGIN_SLUG "google-quota" | ||
| 77 | +#define PLUGIN_ID "plugin_google_quota" | ||
| 78 | +#define PLUGIN_VER "1.0.0" | ||
| 79 | +#define PLUGIN_NAME "google quota" | ||
| 80 | +#define PLUGIN_DESC "Account quotas" | ||
| 81 | + | ||
| 82 | +#define DEFAULT_QUOTA_BIN "scorpiox-google-quota" | ||
| 83 | + | ||
| 84 | +#define PATH_SZ 1024 | ||
| 85 | +#define EMAIL_SZ 256 | ||
| 86 | +#define PROJ_SZ 256 | ||
| 87 | +#define MODEL_SZ 128 | ||
| 88 | +#define RESET_SZ 64 | ||
| 89 | +#define CMD_SZ 4096 | ||
| 90 | +#define FIELD_SZ 512 | ||
| 91 | +#define OUT_MAX (512 * 1024) | ||
| 92 | +#define MAX_ACCOUNTS 64 | ||
| 93 | +#define MAX_MODELS 64 | ||
| 94 | +#define MAX_WORKERS 8 | ||
| 95 | + | ||
| 96 | +/* ------------------------------------------------------------------ */ | ||
| 97 | +/* Growable byte buffer */ | ||
| 98 | +/* ------------------------------------------------------------------ */ | ||
| 99 | + | ||
| 100 | +typedef struct { | ||
| 101 | + char *p; | ||
| 102 | + size_t n; | ||
| 103 | + size_t cap; | ||
| 104 | +} buf_t; | ||
| 105 | + | ||
| 106 | +static void buf_init(buf_t *b) | ||
| 107 | +{ | ||
| 108 | + b->p = NULL; | ||
| 109 | + b->n = 0; | ||
| 110 | + b->cap = 0; | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +static int buf_need(buf_t *b, size_t extra) | ||
| 114 | +{ | ||
| 115 | + size_t want = b->n + extra + 1; | ||
| 116 | + char *np; | ||
| 117 | + | ||
| 118 | + if (want <= b->cap) return 1; | ||
| 119 | + if (b->cap == 0) b->cap = 1024; | ||
| 120 | + while (b->cap < want) { | ||
| 121 | + if (b->cap > (size_t)32 * 1024 * 1024) return 0; | ||
| 122 | + b->cap *= 2; | ||
| 123 | + } | ||
| 124 | + np = (char *)realloc(b->p, b->cap); | ||
| 125 | + if (!np) return 0; | ||
| 126 | + b->p = np; | ||
| 127 | + return 1; | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +static int buf_add(buf_t *b, const char *s, size_t len) | ||
| 131 | +{ | ||
| 132 | + if (!s || len == 0) return 1; | ||
| 133 | + if (!buf_need(b, len)) return 0; | ||
| 134 | + memcpy(b->p + b->n, s, len); | ||
| 135 | + b->n += len; | ||
| 136 | + b->p[b->n] = '\0'; | ||
| 137 | + return 1; | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +static int buf_adds(buf_t *b, const char *s) | ||
| 141 | +{ | ||
| 142 | + return s ? buf_add(b, s, strlen(s)) : 1; | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +static int buf_addc(buf_t *b, char c) | ||
| 146 | +{ | ||
| 147 | + return buf_add(b, &c, 1); | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +static int buf_addf(buf_t *b, const char *fmt, ...) | ||
| 151 | +{ | ||
| 152 | + char tmp[2048]; | ||
| 153 | + int n; | ||
| 154 | + va_list ap; | ||
| 155 | + | ||
| 156 | + va_start(ap, fmt); | ||
| 157 | + n = vsnprintf(tmp, sizeof(tmp), fmt, ap); | ||
| 158 | + va_end(ap); | ||
| 159 | + if (n < 0) return 0; | ||
| 160 | + if ((size_t)n < sizeof(tmp)) return buf_add(b, tmp, (size_t)n); | ||
| 161 | + | ||
| 162 | + { | ||
| 163 | + char *big = (char *)malloc((size_t)n + 1); | ||
| 164 | + int ok; | ||
| 165 | + if (!big) return 0; | ||
| 166 | + va_start(ap, fmt); | ||
| 167 | + vsnprintf(big, (size_t)n + 1, fmt, ap); | ||
| 168 | + va_end(ap); | ||
| 169 | + ok = buf_add(b, big, (size_t)n); | ||
| 170 | + free(big); | ||
| 171 | + return ok; | ||
| 172 | + } | ||
| 173 | +} | ||
| 174 | + | ||
| 175 | +static int buf_json(buf_t *b, const char *s) | ||
| 176 | +{ | ||
| 177 | + const unsigned char *p = (const unsigned char *)(s ? s : ""); | ||
| 178 | + if (!buf_addc(b, '"')) return 0; | ||
| 179 | + for (; *p; p++) { | ||
| 180 | + switch (*p) { | ||
| 181 | + case '"': if (!buf_adds(b, "\\\"")) return 0; break; | ||
| 182 | + case '\\': if (!buf_adds(b, "\\\\")) return 0; break; | ||
| 183 | + case '\n': if (!buf_adds(b, "\\n")) return 0; break; | ||
| 184 | + case '\r': if (!buf_adds(b, "\\r")) return 0; break; | ||
| 185 | + case '\t': if (!buf_adds(b, "\\t")) return 0; break; | ||
| 186 | + default: | ||
| 187 | + if (*p < 0x20) { | ||
| 188 | + if (!buf_addf(b, "\\u%04x", (unsigned)*p)) return 0; | ||
| 189 | + } else { | ||
| 190 | + if (!buf_addc(b, (char)*p)) return 0; | ||
| 191 | + } | ||
| 192 | + } | ||
| 193 | + } | ||
| 194 | + return buf_addc(b, '"'); | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +static const char *buf_str(const buf_t *b) | ||
| 198 | +{ | ||
| 199 | + return b->p ? b->p : ""; | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +static void buf_free(buf_t *b) | ||
| 203 | +{ | ||
| 204 | + free(b->p); | ||
| 205 | + b->p = NULL; | ||
| 206 | + b->n = 0; | ||
| 207 | + b->cap = 0; | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +/* ------------------------------------------------------------------ */ | ||
| 211 | +/* String, query & env helpers */ | ||
| 212 | +/* ------------------------------------------------------------------ */ | ||
| 213 | + | ||
| 214 | +static int ascii_strncasecmp(const char *a, const char *b, size_t n) | ||
| 215 | +{ | ||
| 216 | + size_t i; | ||
| 217 | + for (i = 0; i < n; i++) { | ||
| 218 | + unsigned char ca = (unsigned char)a[i]; | ||
| 219 | + unsigned char cb = (unsigned char)b[i]; | ||
| 220 | + int da = tolower(ca); | ||
| 221 | + int db = tolower(cb); | ||
| 222 | + if (da != db) return da - db; | ||
| 223 | + if (ca == '\0') return 0; | ||
| 224 | + } | ||
| 225 | + return 0; | ||
| 226 | +} | ||
| 227 | + | ||
| 228 | +static void trim_tail(char *s) | ||
| 229 | +{ | ||
| 230 | + size_t n; | ||
| 231 | + if (!s) return; | ||
| 232 | + n = strlen(s); | ||
| 233 | + while (n > 0 && (s[n - 1] == ' ' || s[n - 1] == '\t' || | ||
| 234 | + s[n - 1] == '\r' || s[n - 1] == '\n')) { | ||
| 235 | + s[--n] = '\0'; | ||
| 236 | + } | ||
| 237 | +} | ||
| 238 | + | ||
| 239 | +static void url_decode(char *s) | ||
| 240 | +{ | ||
| 241 | + char *w = s; | ||
| 242 | + char *r = s; | ||
| 243 | + if (!s) return; | ||
| 244 | + while (*r) { | ||
| 245 | + if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) { | ||
| 246 | + int hi = isdigit((unsigned char)r[1]) ? r[1] - '0' : tolower((unsigned char)r[1]) - 'a' + 10; | ||
| 247 | + int lo = isdigit((unsigned char)r[2]) ? r[2] - '0' : tolower((unsigned char)r[2]) - 'a' + 10; | ||
| 248 | + *w++ = (char)((hi << 4) | lo); | ||
| 249 | + r += 3; | ||
| 250 | + } else if (*r == '+') { | ||
| 251 | + *w++ = ' '; | ||
| 252 | + r++; | ||
| 253 | + } else { | ||
| 254 | + *w++ = *r++; | ||
| 255 | + } | ||
| 256 | + } | ||
| 257 | + *w = '\0'; | ||
| 258 | +} | ||
| 259 | + | ||
| 260 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 261 | +{ | ||
| 262 | + size_t klen; | ||
| 263 | + const char *p; | ||
| 264 | + | ||
| 265 | + if (!out || outsz == 0) return 0; | ||
| 266 | + out[0] = '\0'; | ||
| 267 | + if (!qs || !key) return 0; | ||
| 268 | + klen = strlen(key); | ||
| 269 | + p = qs; | ||
| 270 | + while (*p) { | ||
| 271 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 272 | + size_t i = 0; | ||
| 273 | + p += klen + 1; | ||
| 274 | + while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; | ||
| 275 | + out[i] = '\0'; | ||
| 276 | + url_decode(out); | ||
| 277 | + return 1; | ||
| 278 | + } | ||
| 279 | + p = strchr(p, '&'); | ||
| 280 | + if (!p) break; | ||
| 281 | + p++; | ||
| 282 | + } | ||
| 283 | + return 0; | ||
| 284 | +} | ||
| 285 | + | ||
| 286 | +static int query_has(const char *qs, const char *key) | ||
| 287 | +{ | ||
| 288 | + size_t klen; | ||
| 289 | + const char *p; | ||
| 290 | + | ||
| 291 | + if (!qs || !key) return 0; | ||
| 292 | + klen = strlen(key); | ||
| 293 | + p = qs; | ||
| 294 | + while (p && *p) { | ||
| 295 | + if (strncmp(p, key, klen) == 0 && (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&')) | ||
| 296 | + return 1; | ||
| 297 | + p = strchr(p, '&'); | ||
| 298 | + if (!p) break; | ||
| 299 | + p++; | ||
| 300 | + } | ||
| 301 | + return 0; | ||
| 302 | +} | ||
| 303 | + | ||
| 304 | +static void set_env_var(const char *k, const char *v) | ||
| 305 | +{ | ||
| 306 | +#if defined(_WIN32) | ||
| 307 | + _putenv_s(k, v ? v : ""); | ||
| 308 | +#else | ||
| 309 | + setenv(k, v ? v : "", 1); | ||
| 310 | +#endif | ||
| 311 | +} | ||
| 312 | + | ||
| 313 | +static void unset_env_var(const char *k) | ||
| 314 | +{ | ||
| 315 | +#if defined(_WIN32) | ||
| 316 | + _putenv_s(k, ""); | ||
| 317 | +#else | ||
| 318 | + unsetenv(k); | ||
| 319 | +#endif | ||
| 320 | +} | ||
| 321 | + | ||
| 322 | +/* ------------------------------------------------------------------ */ | ||
| 323 | +/* Node auth (X-Bot-Password / Bearer / ?pwd=) */ | ||
| 324 | +/* ------------------------------------------------------------------ */ | ||
| 325 | + | ||
| 326 | +static void require_node_auth(void) | ||
| 327 | +{ | ||
| 328 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 329 | + const char *xp; | ||
| 330 | + const char *auth; | ||
| 331 | + char qpwd[256] = {0}; | ||
| 332 | + | ||
| 333 | + if (!np || !*np) return; | ||
| 334 | + | ||
| 335 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 336 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 337 | + | ||
| 338 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 339 | + if (auth) { | ||
| 340 | + while (*auth == ' ') auth++; | ||
| 341 | + if (ascii_strncasecmp(auth, "Bearer ", 7) == 0) { | ||
| 342 | + auth += 7; | ||
| 343 | + while (*auth == ' ') auth++; | ||
| 344 | + if (strcmp(auth, np) == 0) return; | ||
| 345 | + } | ||
| 346 | + } | ||
| 347 | + | ||
| 348 | + if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) && | ||
| 349 | + strcmp(qpwd, np) == 0) return; | ||
| 350 | + | ||
| 351 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 352 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 353 | + "Cache-Control: no-store\r\n\r\n" | ||
| 354 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 355 | + exit(0); | ||
| 356 | +} | ||
| 357 | + | ||
| 358 | +/* ------------------------------------------------------------------ */ | ||
| 359 | +/* Paths & files */ | ||
| 360 | +/* ------------------------------------------------------------------ */ | ||
| 361 | + | ||
| 362 | +static const char *home_dir(void) | ||
| 363 | +{ | ||
| 364 | +#ifdef _WIN32 | ||
| 365 | + static char home[512]; | ||
| 366 | + DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)); | ||
| 367 | + if (n > 0 && n < sizeof(home)) return home; | ||
| 368 | + { | ||
| 369 | + const char *h = getenv("USERPROFILE"); | ||
| 370 | + if (h && *h) return h; | ||
| 371 | + h = getenv("HOME"); | ||
| 372 | + return (h && *h) ? h : NULL; | ||
| 373 | + } | ||
| 374 | +#else | ||
| 375 | + const char *h = getenv("HOME"); | ||
| 376 | + return (h && *h) ? h : NULL; | ||
| 377 | +#endif | ||
| 378 | +} | ||
| 379 | + | ||
| 380 | +static void accounts_path(char *out, size_t n) | ||
| 381 | +{ | ||
| 382 | + const char *env = getenv("GOOGLE_ACCOUNTS_FILE"); | ||
| 383 | + const char *home; | ||
| 384 | + | ||
| 385 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | ||
| 386 | + env = getenv("ANTIGRAVITY_CREDS_PATH"); | ||
| 387 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | ||
| 388 | + | ||
| 389 | + home = home_dir(); | ||
| 390 | + if (!home) { snprintf(out, n, "antigravity_accounts.json"); return; } | ||
| 391 | + snprintf(out, n, "%s%c.config%cgoogle-accounts%cantigravity_accounts.json", | ||
| 392 | + home, PATH_SEP, PATH_SEP, PATH_SEP); | ||
| 393 | +} | ||
| 394 | + | ||
| 395 | +static void selected_path(char *out, size_t n) | ||
| 396 | +{ | ||
| 397 | + const char *env = getenv("GOOGLE_SELECTED_FILE"); | ||
| 398 | + char base[PATH_SZ]; | ||
| 399 | + char *slash; | ||
| 400 | + | ||
| 401 | + if (env && *env) { snprintf(out, n, "%s", env); return; } | ||
| 402 | + | ||
| 403 | + accounts_path(base, sizeof(base)); | ||
| 404 | + slash = strrchr(base, PATH_SEP); | ||
| 405 | + if (!slash) slash = strrchr(base, '/'); | ||
| 406 | + if (!slash) { snprintf(out, n, "selected_account.txt"); return; } | ||
| 407 | + *(slash + 1) = '\0'; | ||
| 408 | + snprintf(out, n, "%sselected_account.txt", base); | ||
| 409 | +} | ||
| 410 | + | ||
| 411 | +static const char *quota_bin(void) | ||
| 412 | +{ | ||
| 413 | + const char *b = getenv("GOOGLE_QUOTA_BIN"); | ||
| 414 | + return (b && *b) ? b : DEFAULT_QUOTA_BIN; | ||
| 415 | +} | ||
| 416 | + | ||
| 417 | +#if defined(_WIN32) | ||
| 418 | +static int file_exists(const char *p) | ||
| 419 | +{ | ||
| 420 | + DWORD a = GetFileAttributesA(p); | ||
| 421 | + return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); | ||
| 422 | +} | ||
| 423 | +#endif | ||
| 424 | + | ||
| 425 | +static int bin_available(const char *bin) | ||
| 426 | +{ | ||
| 427 | + if (!bin || !*bin) return 0; | ||
| 428 | +#if defined(_WIN32) | ||
| 429 | + { | ||
| 430 | + char full[MAX_PATH]; | ||
| 431 | + DWORD n; | ||
| 432 | + if (strchr(bin, '\\') || strchr(bin, '/') || strchr(bin, ':')) | ||
| 433 | + return file_exists(bin); | ||
| 434 | + n = SearchPathA(NULL, bin, ".exe", (DWORD)sizeof(full), full, NULL); | ||
| 435 | + return n > 0 && n < (DWORD)sizeof(full); | ||
| 436 | + } | ||
| 437 | +#else | ||
| 438 | + if (strchr(bin, '/')) { | ||
| 439 | + struct stat st; | ||
| 440 | + return stat(bin, &st) == 0 && S_ISREG(st.st_mode) && access(bin, X_OK) == 0; | ||
| 441 | + } | ||
| 442 | + { | ||
| 443 | + const char *path_env = getenv("PATH"); | ||
| 444 | + const char *p; | ||
| 445 | + if (!path_env || !*path_env) return 0; | ||
| 446 | + p = path_env; | ||
| 447 | + while (*p) { | ||
| 448 | + const char *colon = strchr(p, ':'); | ||
| 449 | + size_t dlen = colon ? (size_t)(colon - p) : strlen(p); | ||
| 450 | + char cand[PATH_SZ]; | ||
| 451 | + if (dlen > 0 && dlen + 1 + strlen(bin) + 1 < sizeof(cand)) { | ||
| 452 | + struct stat st; | ||
| 453 | + memcpy(cand, p, dlen); | ||
| 454 | + cand[dlen] = '/'; | ||
| 455 | + strcpy(cand + dlen + 1, bin); | ||
| 456 | + if (stat(cand, &st) == 0 && S_ISREG(st.st_mode) && access(cand, X_OK) == 0) | ||
| 457 | + return 1; | ||
| 458 | + } | ||
| 459 | + if (!colon) break; | ||
| 460 | + p = colon + 1; | ||
| 461 | + } | ||
| 462 | + return 0; | ||
| 463 | + } | ||
| 464 | +#endif | ||
| 465 | +} | ||
| 466 | + | ||
| 467 | +static char *read_file(const char *path) | ||
| 468 | +{ | ||
| 469 | + FILE *f; | ||
| 470 | + long sz; | ||
| 471 | + char *buf; | ||
| 472 | + | ||
| 473 | + if (!path || !*path) return NULL; | ||
| 474 | + f = fopen(path, "rb"); | ||
| 475 | + if (!f) return NULL; | ||
| 476 | + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } | ||
| 477 | + sz = ftell(f); | ||
| 478 | + if (sz < 0 || sz > 4 * 1024 * 1024) { fclose(f); return NULL; } | ||
| 479 | + rewind(f); | ||
| 480 | + buf = (char *)malloc((size_t)sz + 1); | ||
| 481 | + if (!buf) { fclose(f); return NULL; } | ||
| 482 | + if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) { | ||
| 483 | + free(buf); | ||
| 484 | + fclose(f); | ||
| 485 | + return NULL; | ||
| 486 | + } | ||
| 487 | + buf[sz] = '\0'; | ||
| 488 | + fclose(f); | ||
| 489 | + return buf; | ||
| 490 | +} | ||
| 491 | + | ||
| 492 | +/* ------------------------------------------------------------------ */ | ||
| 493 | +/* Minimal JSON scanner (read-only, zero dependencies) */ | ||
| 494 | +/* ------------------------------------------------------------------ */ | ||
| 495 | + | ||
| 496 | +static const char *json_skip_ws(const char *p, const char *end) | ||
| 497 | +{ | ||
| 498 | + while (p && p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; | ||
| 499 | + return p; | ||
| 500 | +} | ||
| 501 | + | ||
| 502 | +static const char *json_skip_value(const char *p) | ||
| 503 | +{ | ||
| 504 | + int depth = 0; | ||
| 505 | + int in_str = 0; | ||
| 506 | + | ||
| 507 | + if (!p) return NULL; | ||
| 508 | + while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; | ||
| 509 | + if (!*p) return NULL; | ||
| 510 | + | ||
| 511 | + if (*p != '{' && *p != '[' && *p != '"') { | ||
| 512 | + while (*p && *p != ',' && *p != '}' && *p != ']' && | ||
| 513 | + *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r') p++; | ||
| 514 | + return p; | ||
| 515 | + } | ||
| 516 | + | ||
| 517 | + for (; *p; p++) { | ||
| 518 | + if (in_str) { | ||
| 519 | + if (*p == '\\' && p[1]) { p++; continue; } | ||
| 520 | + if (*p == '"') { | ||
| 521 | + in_str = 0; | ||
| 522 | + if (depth == 0) return p + 1; | ||
| 523 | + } | ||
| 524 | + continue; | ||
| 525 | + } | ||
| 526 | + if (*p == '"') { in_str = 1; continue; } | ||
| 527 | + if (*p == '{' || *p == '[') { depth++; continue; } | ||
| 528 | + if (*p == '}' || *p == ']') { | ||
| 529 | + depth--; | ||
| 530 | + if (depth <= 0) return p + 1; | ||
| 531 | + } | ||
| 532 | + } | ||
| 533 | + return p; | ||
| 534 | +} | ||
| 535 | + | ||
| 536 | +static int json_read_string_at(const char **pp, char *out, size_t outsz) | ||
| 537 | +{ | ||
| 538 | + const char *p = *pp; | ||
| 539 | + size_t o = 0; | ||
| 540 | + | ||
| 541 | + if (!p || *p != '"') return 0; | ||
| 542 | + p++; | ||
| 543 | + while (*p && *p != '"') { | ||
| 544 | + unsigned char c = (unsigned char)*p++; | ||
| 545 | + if (c == '\\' && *p) { | ||
| 546 | + char e = *p++; | ||
| 547 | + switch (e) { | ||
| 548 | + case '"': c = '"'; break; | ||
| 549 | + case '\\': c = '\\'; break; | ||
| 550 | + case '/': c = '/'; break; | ||
| 551 | + case 'n': c = '\n'; break; | ||
| 552 | + case 'r': c = '\r'; break; | ||
| 553 | + case 't': c = '\t'; break; | ||
| 554 | + default: c = (unsigned char)e; break; | ||
| 555 | + } | ||
| 556 | + } | ||
| 557 | + if (o + 1 < outsz) out[o++] = (char)c; | ||
| 558 | + } | ||
| 559 | + if (*p == '"') p++; | ||
| 560 | + out[o] = '\0'; | ||
| 561 | + *pp = p; | ||
| 562 | + return 1; | ||
| 563 | +} | ||
| 564 | + | ||
| 565 | +static const char *json_find_key(const char *obj, const char *end, const char *key) | ||
| 566 | +{ | ||
| 567 | + const char *p = obj; | ||
| 568 | + size_t klen = strlen(key); | ||
| 569 | + int depth = 0; | ||
| 570 | + | ||
| 571 | + p = json_skip_ws(p, end); | ||
| 572 | + if (p < end && *p == '{') p++; | ||
| 573 | + | ||
| 574 | + while (p && p < end) { | ||
| 575 | + if (*p == '"') { | ||
| 576 | + char name[128]; | ||
| 577 | + json_read_string_at(&p, name, sizeof(name)); | ||
| 578 | + if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) { | ||
| 579 | + const char *q = json_skip_ws(p, end); | ||
| 580 | + if (q < end && *q == ':') { | ||
| 581 | + q = json_skip_ws(q + 1, end); | ||
| 582 | + return (q < end) ? q : NULL; | ||
| 583 | + } | ||
| 584 | + } | ||
| 585 | + continue; | ||
| 586 | + } | ||
| 587 | + if (*p == '{' || *p == '[') depth++; | ||
| 588 | + else if (*p == '}' || *p == ']') depth--; | ||
| 589 | + p++; | ||
| 590 | + } | ||
| 591 | + return NULL; | ||
| 592 | +} | ||
| 593 | + | ||
| 594 | +static int json_str_field(const char *obj, const char *end, const char *key, | ||
| 595 | + char *out, size_t outsz) | ||
| 596 | +{ | ||
| 597 | + const char *v; | ||
| 598 | + | ||
| 599 | + if (!out || outsz == 0) return 0; | ||
| 600 | + v = json_find_key(obj, end, key); | ||
| 601 | + if (!v || *v == 'n') return 0; | ||
| 602 | + out[0] = '\0'; | ||
| 603 | + if (*v == '"') return json_read_string_at(&v, out, outsz); | ||
| 604 | + { | ||
| 605 | + size_t i = 0; | ||
| 606 | + while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++; | ||
| 607 | + out[i] = '\0'; | ||
| 608 | + trim_tail(out); | ||
| 609 | + return out[0] ? 1 : 0; | ||
| 610 | + } | ||
| 611 | +} | ||
| 612 | + | ||
| 613 | +static int json_bool_field(const char *obj, const char *end, const char *key, int dflt) | ||
| 614 | +{ | ||
| 615 | + const char *v = json_find_key(obj, end, key); | ||
| 616 | + if (!v) return dflt; | ||
| 617 | + if (strncmp(v, "true", 4) == 0) return 1; | ||
| 618 | + if (strncmp(v, "false", 5) == 0) return 0; | ||
| 619 | + if (*v == '1') return 1; | ||
| 620 | + return 0; | ||
| 621 | +} | ||
| 622 | + | ||
| 623 | +/* Returns 1 if numeric value parsed into *out, 0 if missing or null. */ | ||
| 624 | +static int json_double_field(const char *obj, const char *end, const char *key, double *out) | ||
| 625 | +{ | ||
| 626 | + const char *v = json_find_key(obj, end, key); | ||
| 627 | + char *ep = NULL; | ||
| 628 | + double val; | ||
| 629 | + | ||
| 630 | + if (!v || *v == 'n') return 0; | ||
| 631 | + if (*v != '-' && !isdigit((unsigned char)*v) && *v != '.') return 0; | ||
| 632 | + val = strtod(v, &ep); | ||
| 633 | + if (ep == v) return 0; | ||
| 634 | + *out = val; | ||
| 635 | + return 1; | ||
| 636 | +} | ||
| 637 | + | ||
| 638 | +/* ------------------------------------------------------------------ */ | ||
| 639 | +/* Account list loading (never copies refresh_token) */ | ||
| 640 | +/* ------------------------------------------------------------------ */ | ||
| 641 | + | ||
| 642 | +typedef struct { | ||
| 643 | + char email[EMAIL_SZ]; | ||
| 644 | + int has_refresh; | ||
| 645 | + int selected; | ||
| 646 | +} acct_entry_t; | ||
| 647 | + | ||
| 648 | +static int is_safe_email(const char *s) | ||
| 649 | +{ | ||
| 650 | + int has_at = 0; | ||
| 651 | + const char *p; | ||
| 652 | + | ||
| 653 | + if (!s || !*s || strlen(s) >= EMAIL_SZ) return 0; | ||
| 654 | + for (p = s; *p; p++) { | ||
| 655 | + unsigned char c = (unsigned char)*p; | ||
| 656 | + if (c == '@') { has_at = 1; continue; } | ||
| 657 | + if (isalnum(c) || c == '.' || c == '_' || c == '-' || c == '+') continue; | ||
| 658 | + return 0; | ||
| 659 | + } | ||
| 660 | + return has_at; | ||
| 661 | +} | ||
| 662 | + | ||
| 663 | +static int load_accounts(acct_entry_t *list, int max_n, char *selected_out, size_t sel_sz) | ||
| 664 | +{ | ||
| 665 | + char apath[PATH_SZ], spath[PATH_SZ]; | ||
| 666 | + char *raw_sel, *raw_accts; | ||
| 667 | + int count = 0; | ||
| 668 | + | ||
| 669 | + selected_out[0] = '\0'; | ||
| 670 | + selected_path(spath, sizeof(spath)); | ||
| 671 | + raw_sel = read_file(spath); | ||
| 672 | + if (raw_sel) { | ||
| 673 | + trim_tail(raw_sel); | ||
| 674 | + if (is_safe_email(raw_sel)) snprintf(selected_out, sel_sz, "%s", raw_sel); | ||
| 675 | + free(raw_sel); | ||
| 676 | + } | ||
| 677 | + | ||
| 678 | + accounts_path(apath, sizeof(apath)); | ||
| 679 | + raw_accts = read_file(apath); | ||
| 680 | + if (!raw_accts) return 0; | ||
| 681 | + | ||
| 682 | + { | ||
| 683 | + const char *p = raw_accts; | ||
| 684 | + while (p && *p && count < max_n) { | ||
| 685 | + const char *open = strchr(p, '{'); | ||
| 686 | + const char *end; | ||
| 687 | + char email[EMAIL_SZ] = {0}; | ||
| 688 | + char rt_probe[8] = {0}; | ||
| 689 | + int has_rt = 0; | ||
| 690 | + int dup = 0; | ||
| 691 | + int i; | ||
| 692 | + | ||
| 693 | + if (!open) break; | ||
| 694 | + end = json_skip_value(open); | ||
| 695 | + if (!end || end <= open) break; | ||
| 696 | + | ||
| 697 | + json_str_field(open, end, "email", email, sizeof(email)); | ||
| 698 | + /* Presence check only: never copy or retain the refresh token. */ | ||
| 699 | + if (json_str_field(open, end, "refresh_token", rt_probe, sizeof(rt_probe)) && rt_probe[0]) | ||
| 700 | + has_rt = 1; | ||
| 701 | + | ||
| 702 | + if (is_safe_email(email)) { | ||
| 703 | + for (i = 0; i < count; i++) { | ||
| 704 | + if (strcmp(list[i].email, email) == 0) { | ||
| 705 | + if (has_rt) list[i].has_refresh = 1; | ||
| 706 | + dup = 1; | ||
| 707 | + break; | ||
| 708 | + } | ||
| 709 | + } | ||
| 710 | + if (!dup) { | ||
| 711 | + snprintf(list[count].email, sizeof(list[count].email), "%s", email); | ||
| 712 | + list[count].has_refresh = has_rt; | ||
| 713 | + list[count].selected = (selected_out[0] && strcmp(selected_out, email) == 0) ? 1 : 0; | ||
| 714 | + count++; | ||
| 715 | + } | ||
| 716 | + } | ||
| 717 | + p = end; | ||
| 718 | + } | ||
| 719 | + } | ||
| 720 | + | ||
| 721 | + free(raw_accts); | ||
| 722 | + return count; | ||
| 723 | +} | ||
| 724 | + | ||
| 725 | +/* ------------------------------------------------------------------ */ | ||
| 726 | +/* Child process execution */ | ||
| 727 | +/* ------------------------------------------------------------------ */ | ||
| 728 | + | ||
| 729 | +static void prepare_quota_env(void) | ||
| 730 | +{ | ||
| 731 | + char apath[PATH_SZ]; | ||
| 732 | + accounts_path(apath, sizeof(apath)); | ||
| 733 | + | ||
| 734 | + /* Clear profile/token overrides so --account always resolves from the | ||
| 735 | + * local accounts file rather than an inherited agent profile. */ | ||
| 736 | + unset_env_var("ACTIVE_PROFILE"); | ||
| 737 | + unset_env_var("GOOGLE_ACCESS_TOKEN"); | ||
| 738 | + unset_env_var("GOOGLE_REMOTE_URL"); | ||
| 739 | + unset_env_var("GOOGLE_PROJECT_ID"); | ||
| 740 | + unset_env_var("GOOGLE_ACCOUNT"); | ||
| 741 | + set_env_var("GOOGLE_TOKEN_SOURCE", "local"); | ||
| 742 | + set_env_var("GOOGLE_ACCOUNTS_FILE", apath); | ||
| 743 | +} | ||
| 744 | + | ||
| 745 | +#if defined(_WIN32) | ||
| 746 | +static void shell_quote_into(const char *in, char *out, size_t outsz) | ||
| 747 | +{ | ||
| 748 | + size_t o = 0; | ||
| 749 | + const char *p; | ||
| 750 | + | ||
| 751 | + if (outsz < 3) { if (outsz) out[0] = '\0'; return; } | ||
| 752 | + out[o++] = '"'; | ||
| 753 | + for (p = in; p && *p; p++) { | ||
| 754 | + if (*p == '"') { | ||
| 755 | + if (o + 3 >= outsz) break; | ||
| 756 | + out[o++] = '\\'; | ||
| 757 | + out[o++] = '"'; | ||
| 758 | + } else { | ||
| 759 | + if (o + 2 >= outsz) break; | ||
| 760 | + out[o++] = *p; | ||
| 761 | + } | ||
| 762 | + } | ||
| 763 | + out[o++] = '"'; | ||
| 764 | + out[o] = '\0'; | ||
| 765 | +} | ||
| 766 | + | ||
| 767 | +static int run_quota_one(const char *bin, const char *email, buf_t *out) | ||
| 768 | +{ | ||
| 769 | + char cmd[CMD_SZ]; | ||
| 770 | + char qbin[FIELD_SZ]; | ||
| 771 | + char qemail[EMAIL_SZ + 16]; | ||
| 772 | + FILE *f; | ||
| 773 | + char line[2048]; | ||
| 774 | + size_t total = 0; | ||
| 775 | + int rc; | ||
| 776 | + | ||
| 777 | + if (!bin || !*bin || !is_safe_email(email)) return 0; | ||
| 778 | + if (!bin_available(bin)) return -1; | ||
| 779 | + shell_quote_into(bin, qbin, sizeof(qbin)); | ||
| 780 | + shell_quote_into(email, qemail, sizeof(qemail)); | ||
| 781 | + snprintf(cmd, sizeof(cmd), "%s --account %s --json 2>NUL", qbin, qemail); | ||
| 782 | + | ||
| 783 | + f = popen(cmd, "r"); | ||
| 784 | + if (!f) return 0; | ||
| 785 | + while (fgets(line, sizeof(line), f)) { | ||
| 786 | + total += strlen(line); | ||
| 787 | + if (total > OUT_MAX) break; | ||
| 788 | + buf_adds(out, line); | ||
| 789 | + } | ||
| 790 | + rc = pclose(f); | ||
| 791 | + if (rc != -1 && ((rc >> 8) & 0xff) == 127) return -1; | ||
| 792 | + return (rc == 0) ? 1 : 0; | ||
| 793 | +} | ||
| 794 | +#else | ||
| 795 | +static int run_quota_one(const char *bin, const char *email, buf_t *out) | ||
| 796 | +{ | ||
| 797 | + int pfd[2]; | ||
| 798 | + pid_t pid; | ||
| 799 | + char chunk[4096]; | ||
| 800 | + ssize_t n; | ||
| 801 | + int status = 0; | ||
| 802 | + | ||
| 803 | + if (!bin || !*bin || !is_safe_email(email)) return 0; | ||
| 804 | + if (!bin_available(bin)) return -1; | ||
| 805 | + if (pipe(pfd) != 0) return 0; | ||
| 806 | + | ||
| 807 | + pid = fork(); | ||
| 808 | + if (pid < 0) { | ||
| 809 | + close(pfd[0]); | ||
| 810 | + close(pfd[1]); | ||
| 811 | + return 0; | ||
| 812 | + } | ||
| 813 | + if (pid == 0) { | ||
| 814 | + int devnull = open("/dev/null", O_WRONLY); | ||
| 815 | + char *argv_exec[5]; | ||
| 816 | + close(pfd[0]); | ||
| 817 | + dup2(pfd[1], STDOUT_FILENO); | ||
| 818 | + close(pfd[1]); | ||
| 819 | + if (devnull >= 0) { | ||
| 820 | + dup2(devnull, STDERR_FILENO); | ||
| 821 | + close(devnull); | ||
| 822 | + } | ||
| 823 | + argv_exec[0] = (char *)bin; | ||
| 824 | + argv_exec[1] = "--account"; | ||
| 825 | + argv_exec[2] = (char *)email; | ||
| 826 | + argv_exec[3] = "--json"; | ||
| 827 | + argv_exec[4] = NULL; | ||
| 828 | + execvp(bin, argv_exec); | ||
| 829 | + _exit(127); | ||
| 830 | + } | ||
| 831 | + | ||
| 832 | + close(pfd[1]); | ||
| 833 | + while ((n = read(pfd[0], chunk, sizeof(chunk))) > 0) { | ||
| 834 | + if (out->n + (size_t)n <= OUT_MAX) buf_add(out, chunk, (size_t)n); | ||
| 835 | + } | ||
| 836 | + close(pfd[0]); | ||
| 837 | + if (waitpid(pid, &status, 0) < 0) return 0; | ||
| 838 | + if (WIFEXITED(status) && WEXITSTATUS(status) == 127) return -1; | ||
| 839 | + return (WIFEXITED(status) && WEXITSTATUS(status) == 0) ? 1 : 0; | ||
| 840 | +} | ||
| 841 | +#endif | ||
| 842 | + | ||
| 843 | +/* ------------------------------------------------------------------ */ | ||
| 844 | +/* Quota parsing & pool aggregation */ | ||
| 845 | +/* ------------------------------------------------------------------ */ | ||
| 846 | + | ||
| 847 | +typedef struct { | ||
| 848 | + char id[MODEL_SZ]; | ||
| 849 | + char pool[16]; | ||
| 850 | + double pct; | ||
| 851 | + int exhausted; | ||
| 852 | + char reset_time[RESET_SZ]; | ||
| 853 | +} model_quota_t; | ||
| 854 | + | ||
| 855 | +typedef struct { | ||
| 856 | + int present; | ||
| 857 | + double pct; | ||
| 858 | + int exhausted; | ||
| 859 | + char reset_time[RESET_SZ]; | ||
| 860 | + int count; | ||
| 861 | +} pool_summary_t; | ||
| 862 | + | ||
| 863 | +typedef struct { | ||
| 864 | + int ok; | ||
| 865 | + int cli_missing; | ||
| 866 | + char error[64]; | ||
| 867 | + char project[PROJ_SZ]; | ||
| 868 | + pool_summary_t gemini; | ||
| 869 | + pool_summary_t claude; | ||
| 870 | + model_quota_t models[MAX_MODELS]; | ||
| 871 | + int model_count; | ||
| 872 | +} acct_quota_t; | ||
| 873 | + | ||
| 874 | +static void pool_init(pool_summary_t *p) | ||
| 875 | +{ | ||
| 876 | + p->present = 0; | ||
| 877 | + p->pct = -1.0; | ||
| 878 | + p->exhausted = 0; | ||
| 879 | + p->reset_time[0] = '\0'; | ||
| 880 | + p->count = 0; | ||
| 881 | +} | ||
| 882 | + | ||
| 883 | +static void pool_add(pool_summary_t *p, double pct, int exhausted, const char *reset) | ||
| 884 | +{ | ||
| 885 | + if (!p->present || pct < p->pct) p->pct = pct; | ||
| 886 | + p->present = 1; | ||
| 887 | + if (exhausted || pct <= 0.0) p->exhausted = 1; | ||
| 888 | + if (!p->reset_time[0] && reset && reset[0]) | ||
| 889 | + snprintf(p->reset_time, sizeof(p->reset_time), "%s", reset); | ||
| 890 | + p->count++; | ||
| 891 | +} | ||
| 892 | + | ||
| 893 | +static const char *find_json_root(const buf_t *b) | ||
| 894 | +{ | ||
| 895 | + const char *p; | ||
| 896 | + if (!b || !b->p) return NULL; | ||
| 897 | + p = b->p; | ||
| 898 | + while (*p) { | ||
| 899 | + if (*p == '{') return p; | ||
| 900 | + p = strchr(p, '\n'); | ||
| 901 | + if (!p) break; | ||
| 902 | + p++; | ||
| 903 | + } | ||
| 904 | + return strchr(b->p, '{'); | ||
| 905 | +} | ||
| 906 | + | ||
| 907 | +static void parse_quota_output(const buf_t *raw, int run_rc, acct_quota_t *q) | ||
| 908 | +{ | ||
| 909 | + const char *root; | ||
| 910 | + const char *root_end; | ||
| 911 | + const char *buckets; | ||
| 912 | + const char *buckets_end; | ||
| 913 | + const char *p; | ||
| 914 | + | ||
| 915 | + memset(q, 0, sizeof(*q)); | ||
| 916 | + pool_init(&q->gemini); | ||
| 917 | + pool_init(&q->claude); | ||
| 918 | + | ||
| 919 | + if (run_rc == -1) { | ||
| 920 | + q->cli_missing = 1; | ||
| 921 | + snprintf(q->error, sizeof(q->error), "cli_unavailable"); | ||
| 922 | + return; | ||
| 923 | + } | ||
| 924 | + | ||
| 925 | + root = find_json_root(raw); | ||
| 926 | + if (!root) { | ||
| 927 | + snprintf(q->error, sizeof(q->error), "quota_fetch_failed"); | ||
| 928 | + return; | ||
| 929 | + } | ||
| 930 | + root_end = json_skip_value(root); | ||
| 931 | + if (!root_end || root_end <= root) { | ||
| 932 | + snprintf(q->error, sizeof(q->error), "invalid_quota_json"); | ||
| 933 | + return; | ||
| 934 | + } | ||
| 935 | + | ||
| 936 | + if (!json_bool_field(root, root_end, "ok", 0)) { | ||
| 937 | + json_str_field(root, root_end, "error", q->error, sizeof(q->error)); | ||
| 938 | + if (!q->error[0]) snprintf(q->error, sizeof(q->error), "quota_fetch_failed"); | ||
| 939 | + return; | ||
| 940 | + } | ||
| 941 | + | ||
| 942 | + json_str_field(root, root_end, "project", q->project, sizeof(q->project)); | ||
| 943 | + buckets = json_find_key(root, root_end, "buckets"); | ||
| 944 | + if (!buckets || *buckets != '[') { | ||
| 945 | + snprintf(q->error, sizeof(q->error), "missing_buckets"); | ||
| 946 | + return; | ||
| 947 | + } | ||
| 948 | + buckets_end = json_skip_value(buckets); | ||
| 949 | + if (!buckets_end || buckets_end <= buckets) { | ||
| 950 | + snprintf(q->error, sizeof(q->error), "invalid_buckets"); | ||
| 951 | + return; | ||
| 952 | + } | ||
| 953 | + | ||
| 954 | + p = buckets + 1; | ||
| 955 | + while (p && p < buckets_end) { | ||
| 956 | + const char *open = strchr(p, '{'); | ||
| 957 | + const char *end; | ||
| 958 | + char mid[MODEL_SZ] = {0}; | ||
| 959 | + char rst[RESET_SZ] = {0}; | ||
| 960 | + double frac = 0.0; | ||
| 961 | + double pct = 0.0; | ||
| 962 | + int exhausted = 0; | ||
| 963 | + const char *pool_name = "other"; | ||
| 964 | + | ||
| 965 | + if (!open || open >= buckets_end) break; | ||
| 966 | + end = json_skip_value(open); | ||
| 967 | + if (!end || end <= open || end > buckets_end) break; | ||
| 968 | + | ||
| 969 | + json_str_field(open, end, "modelId", mid, sizeof(mid)); | ||
| 970 | + json_str_field(open, end, "resetTime", rst, sizeof(rst)); | ||
| 971 | + | ||
| 972 | + if (mid[0] && strncmp(mid, "chat_", 5) != 0 && strncmp(mid, "tab_", 4) != 0) { | ||
| 973 | + if (json_double_field(open, end, "remainingFraction", &frac)) { | ||
| 974 | + pct = frac * 100.0; | ||
| 975 | + if (pct < 0.0) pct = 0.0; | ||
| 976 | + if (pct > 100.0) pct = 100.0; | ||
| 977 | + if (frac <= 0.0) exhausted = 1; | ||
| 978 | + } else { | ||
| 979 | + /* Absent or null remainingFraction means exhausted. */ | ||
| 980 | + pct = 0.0; | ||
| 981 | + exhausted = 1; | ||
| 982 | + } | ||
| 983 | + | ||
| 984 | + if (strncmp(mid, "gemini-", 7) == 0) { | ||
| 985 | + pool_name = "gemini"; | ||
| 986 | + pool_add(&q->gemini, pct, exhausted, rst); | ||
| 987 | + } else if (strncmp(mid, "claude-", 7) == 0) { | ||
| 988 | + pool_name = "claude"; | ||
| 989 | + pool_add(&q->claude, pct, exhausted, rst); | ||
| 990 | + } | ||
| 991 | + | ||
| 992 | + if (q->model_count < MAX_MODELS) { | ||
| 993 | + model_quota_t *m = &q->models[q->model_count++]; | ||
| 994 | + snprintf(m->id, sizeof(m->id), "%s", mid); | ||
| 995 | + snprintf(m->pool, sizeof(m->pool), "%s", pool_name); | ||
| 996 | + m->pct = pct; | ||
| 997 | + m->exhausted = exhausted; | ||
| 998 | + snprintf(m->reset_time, sizeof(m->reset_time), "%s", rst); | ||
| 999 | + } | ||
| 1000 | + } | ||
| 1001 | + p = end; | ||
| 1002 | + } | ||
| 1003 | + | ||
| 1004 | + q->ok = 1; | ||
| 1005 | +} | ||
| 1006 | + | ||
| 1007 | +static void fetch_all_quotas(const char *bin, const acct_entry_t *accts, int count, | ||
| 1008 | + acct_quota_t *out_q) | ||
| 1009 | +{ | ||
| 1010 | +#if defined(_WIN32) | ||
| 1011 | + int i; | ||
| 1012 | + for (i = 0; i < count; i++) { | ||
| 1013 | + buf_t raw; | ||
| 1014 | + int rc; | ||
| 1015 | + buf_init(&raw); | ||
| 1016 | + rc = run_quota_one(bin, accts[i].email, &raw); | ||
| 1017 | + parse_quota_output(&raw, rc, &out_q[i]); | ||
| 1018 | + buf_free(&raw); | ||
| 1019 | + } | ||
| 1020 | +#else | ||
| 1021 | + int next_idx = 0; | ||
| 1022 | + int done = 0; | ||
| 1023 | + | ||
| 1024 | + if (count <= 0) return; | ||
| 1025 | + if (!bin_available(bin)) { | ||
| 1026 | + int i; | ||
| 1027 | + for (i = 0; i < count; i++) { | ||
| 1028 | + buf_t empty; | ||
| 1029 | + buf_init(&empty); | ||
| 1030 | + parse_quota_output(&empty, -1, &out_q[i]); | ||
| 1031 | + } | ||
| 1032 | + return; | ||
| 1033 | + } | ||
| 1034 | + | ||
| 1035 | + { | ||
| 1036 | + typedef struct { | ||
| 1037 | + int active; | ||
| 1038 | + int acct_idx; | ||
| 1039 | + int fd; | ||
| 1040 | + pid_t pid; | ||
| 1041 | + buf_t raw; | ||
| 1042 | + } worker_t; | ||
| 1043 | + | ||
| 1044 | + worker_t w[MAX_WORKERS]; | ||
| 1045 | + int i; | ||
| 1046 | + memset(w, 0, sizeof(w)); | ||
| 1047 | + | ||
| 1048 | + while (done < count) { | ||
| 1049 | + struct pollfd pfds[MAX_WORKERS]; | ||
| 1050 | + int pmap[MAX_WORKERS]; | ||
| 1051 | + int nfds = 0; | ||
| 1052 | + | ||
| 1053 | + for (i = 0; i < MAX_WORKERS && next_idx < count; i++) { | ||
| 1054 | + if (w[i].active) continue; | ||
| 1055 | + { | ||
| 1056 | + int pfd[2]; | ||
| 1057 | + pid_t pid; | ||
| 1058 | + if (pipe(pfd) != 0) { | ||
| 1059 | + buf_t empty; | ||
| 1060 | + buf_init(&empty); | ||
| 1061 | + parse_quota_output(&empty, 0, &out_q[next_idx]); | ||
| 1062 | + next_idx++; | ||
| 1063 | + done++; | ||
| 1064 | + continue; | ||
| 1065 | + } | ||
| 1066 | + pid = fork(); | ||
| 1067 | + if (pid < 0) { | ||
| 1068 | + close(pfd[0]); | ||
| 1069 | + close(pfd[1]); | ||
| 1070 | + buf_t empty; | ||
| 1071 | + buf_init(&empty); | ||
| 1072 | + parse_quota_output(&empty, 0, &out_q[next_idx]); | ||
| 1073 | + next_idx++; | ||
| 1074 | + done++; | ||
| 1075 | + continue; | ||
| 1076 | + } | ||
| 1077 | + if (pid == 0) { | ||
| 1078 | + int devnull = open("/dev/null", O_WRONLY); | ||
| 1079 | + char *argv_exec[5]; | ||
| 1080 | + close(pfd[0]); | ||
| 1081 | + dup2(pfd[1], STDOUT_FILENO); | ||
| 1082 | + close(pfd[1]); | ||
| 1083 | + if (devnull >= 0) { | ||
| 1084 | + dup2(devnull, STDERR_FILENO); | ||
| 1085 | + close(devnull); | ||
| 1086 | + } | ||
| 1087 | + argv_exec[0] = (char *)bin; | ||
| 1088 | + argv_exec[1] = "--account"; | ||
| 1089 | + argv_exec[2] = (char *)accts[next_idx].email; | ||
| 1090 | + argv_exec[3] = "--json"; | ||
| 1091 | + argv_exec[4] = NULL; | ||
| 1092 | + execvp(bin, argv_exec); | ||
| 1093 | + _exit(127); | ||
| 1094 | + } | ||
| 1095 | + close(pfd[1]); | ||
| 1096 | + w[i].active = 1; | ||
| 1097 | + w[i].acct_idx = next_idx; | ||
| 1098 | + w[i].fd = pfd[0]; | ||
| 1099 | + w[i].pid = pid; | ||
| 1100 | + buf_init(&w[i].raw); | ||
| 1101 | + next_idx++; | ||
| 1102 | + } | ||
| 1103 | + } | ||
| 1104 | + | ||
| 1105 | + for (i = 0; i < MAX_WORKERS; i++) { | ||
| 1106 | + if (!w[i].active) continue; | ||
| 1107 | + pfds[nfds].fd = w[i].fd; | ||
| 1108 | + pfds[nfds].events = POLLIN; | ||
| 1109 | + pfds[nfds].revents = 0; | ||
| 1110 | + pmap[nfds] = i; | ||
| 1111 | + nfds++; | ||
| 1112 | + } | ||
| 1113 | + if (nfds == 0) break; | ||
| 1114 | + | ||
| 1115 | + if (poll(pfds, (nfds_t)nfds, 30000) < 0) { | ||
| 1116 | + if (errno == EINTR) continue; | ||
| 1117 | + break; | ||
| 1118 | + } | ||
| 1119 | + | ||
| 1120 | + for (i = 0; i < nfds; i++) { | ||
| 1121 | + int wi = pmap[i]; | ||
| 1122 | + if (pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) { | ||
| 1123 | + char chunk[4096]; | ||
| 1124 | + ssize_t n = read(w[wi].fd, chunk, sizeof(chunk)); | ||
| 1125 | + if (n > 0) { | ||
| 1126 | + if (w[wi].raw.n + (size_t)n <= OUT_MAX) | ||
| 1127 | + buf_add(&w[wi].raw, chunk, (size_t)n); | ||
| 1128 | + } else if (n == 0 || (n < 0 && errno != EINTR)) { | ||
| 1129 | + int status = 0; | ||
| 1130 | + int rc = 0; | ||
| 1131 | + close(w[wi].fd); | ||
| 1132 | + if (waitpid(w[wi].pid, &status, 0) >= 0) { | ||
| 1133 | + if (WIFEXITED(status) && WEXITSTATUS(status) == 127) rc = -1; | ||
| 1134 | + else if (WIFEXITED(status) && WEXITSTATUS(status) == 0) rc = 1; | ||
| 1135 | + } | ||
| 1136 | + parse_quota_output(&w[wi].raw, rc, &out_q[w[wi].acct_idx]); | ||
| 1137 | + buf_free(&w[wi].raw); | ||
| 1138 | + w[wi].active = 0; | ||
| 1139 | + done++; | ||
| 1140 | + } | ||
| 1141 | + } | ||
| 1142 | + } | ||
| 1143 | + } | ||
| 1144 | + | ||
| 1145 | + for (i = 0; i < MAX_WORKERS; i++) { | ||
| 1146 | + if (w[i].active) { | ||
| 1147 | + int status = 0; | ||
| 1148 | + close(w[i].fd); | ||
| 1149 | + waitpid(w[i].pid, &status, 0); | ||
| 1150 | + parse_quota_output(&w[i].raw, 0, &out_q[w[i].acct_idx]); | ||
| 1151 | + buf_free(&w[i].raw); | ||
| 1152 | + w[i].active = 0; | ||
| 1153 | + } | ||
| 1154 | + } | ||
| 1155 | + } | ||
| 1156 | +#endif | ||
| 1157 | +} | ||
| 1158 | + | ||
| 1159 | +/* ------------------------------------------------------------------ */ | ||
| 1160 | +/* JSON emitters */ | ||
| 1161 | +/* ------------------------------------------------------------------ */ | ||
| 1162 | + | ||
| 1163 | +static void json_headers(void) | ||
| 1164 | +{ | ||
| 1165 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 1166 | + "Cache-Control: no-store\r\n" | ||
| 1167 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1168 | +} | ||
| 1169 | + | ||
| 1170 | +static void emit_error(int code, const char *status, const char *err, const char *detail) | ||
| 1171 | +{ | ||
| 1172 | + buf_t b; | ||
| 1173 | + | ||
| 1174 | + buf_init(&b); | ||
| 1175 | + buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n" | ||
| 1176 | + "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n", | ||
| 1177 | + code, status); | ||
| 1178 | + buf_adds(&b, "{\"ok\":false,\"error\":"); | ||
| 1179 | + buf_json(&b, err); | ||
| 1180 | + if (detail && *detail) { | ||
| 1181 | + buf_adds(&b, ",\"detail\":"); | ||
| 1182 | + buf_json(&b, detail); | ||
| 1183 | + } | ||
| 1184 | + buf_adds(&b, "}\n"); | ||
| 1185 | + fputs(buf_str(&b), stdout); | ||
| 1186 | + buf_free(&b); | ||
| 1187 | +} | ||
| 1188 | + | ||
| 1189 | +static void emit_pool_json(buf_t *b, const pool_summary_t *p) | ||
| 1190 | +{ | ||
| 1191 | + if (!p->present) { | ||
| 1192 | + buf_adds(b, "{\"pct\":-1,\"exhausted\":false,\"reset_time\":\"\",\"count\":0}"); | ||
| 1193 | + return; | ||
| 1194 | + } | ||
| 1195 | + buf_addf(b, "{\"pct\":%.2f,\"exhausted\":%s,\"reset_time\":", | ||
| 1196 | + p->pct, p->exhausted ? "true" : "false"); | ||
| 1197 | + buf_json(b, p->reset_time); | ||
| 1198 | + buf_addf(b, ",\"count\":%d}", p->count); | ||
| 1199 | +} | ||
| 1200 | + | ||
| 1201 | +static void emit_acct_quota_json(buf_t *b, const acct_entry_t *a, const acct_quota_t *q) | ||
| 1202 | +{ | ||
| 1203 | + int i; | ||
| 1204 | + | ||
| 1205 | + buf_adds(b, "{\"email\":"); | ||
| 1206 | + buf_json(b, a->email); | ||
| 1207 | + buf_addf(b, ",\"selected\":%s,\"has_refresh\":%s,\"ok\":%s", | ||
| 1208 | + a->selected ? "true" : "false", | ||
| 1209 | + a->has_refresh ? "true" : "false", | ||
| 1210 | + q->ok ? "true" : "false"); | ||
| 1211 | + | ||
| 1212 | + if (!q->ok) { | ||
| 1213 | + buf_adds(b, ",\"error\":"); | ||
| 1214 | + buf_json(b, q->error[0] ? q->error : "quota_fetch_failed"); | ||
| 1215 | + if (q->cli_missing) { | ||
| 1216 | + buf_adds(b, ",\"detail\":"); | ||
| 1217 | + buf_json(b, "scorpiox-google-quota was not found on PATH; install SCORPIOX CODE or set GOOGLE_QUOTA_BIN"); | ||
| 1218 | + } | ||
| 1219 | + buf_addc(b, '}'); | ||
| 1220 | + return; | ||
| 1221 | + } | ||
| 1222 | + | ||
| 1223 | + buf_adds(b, ",\"project\":"); | ||
| 1224 | + buf_json(b, q->project); | ||
| 1225 | + buf_adds(b, ",\"gemini\":"); | ||
| 1226 | + emit_pool_json(b, &q->gemini); | ||
| 1227 | + buf_adds(b, ",\"claude\":"); | ||
| 1228 | + emit_pool_json(b, &q->claude); | ||
| 1229 | + buf_adds(b, ",\"models\":["); | ||
| 1230 | + for (i = 0; i < q->model_count; i++) { | ||
| 1231 | + const model_quota_t *m = &q->models[i]; | ||
| 1232 | + if (i > 0) buf_addc(b, ','); | ||
| 1233 | + buf_adds(b, "{\"id\":"); | ||
| 1234 | + buf_json(b, m->id); | ||
| 1235 | + buf_adds(b, ",\"pool\":"); | ||
| 1236 | + buf_json(b, m->pool); | ||
| 1237 | + buf_addf(b, ",\"pct\":%.2f,\"exhausted\":%s,\"reset_time\":", | ||
| 1238 | + m->pct, m->exhausted ? "true" : "false"); | ||
| 1239 | + buf_json(b, m->reset_time); | ||
| 1240 | + buf_addc(b, '}'); | ||
| 1241 | + } | ||
| 1242 | + buf_adds(b, "]}"); | ||
| 1243 | +} | ||
| 1244 | + | ||
| 1245 | +/* ------------------------------------------------------------------ */ | ||
| 1246 | +/* Actions */ | ||
| 1247 | +/* ------------------------------------------------------------------ */ | ||
| 1248 | + | ||
| 1249 | +static int action_status(void) | ||
| 1250 | +{ | ||
| 1251 | + acct_entry_t accts[MAX_ACCOUNTS]; | ||
| 1252 | + char selected[EMAIL_SZ]; | ||
| 1253 | + char apath[PATH_SZ], spath[PATH_SZ]; | ||
| 1254 | + int count, i; | ||
| 1255 | + int cli_ok; | ||
| 1256 | + buf_t b; | ||
| 1257 | + | ||
| 1258 | + count = load_accounts(accts, MAX_ACCOUNTS, selected, sizeof(selected)); | ||
| 1259 | + accounts_path(apath, sizeof(apath)); | ||
| 1260 | + selected_path(spath, sizeof(spath)); | ||
| 1261 | + cli_ok = bin_available(quota_bin()); | ||
| 1262 | + | ||
| 1263 | + buf_init(&b); | ||
| 1264 | + buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"selected\":"); | ||
| 1265 | + buf_json(&b, selected); | ||
| 1266 | + buf_adds(&b, ",\"accounts_path\":"); | ||
| 1267 | + buf_json(&b, apath); | ||
| 1268 | + buf_adds(&b, ",\"selected_path\":"); | ||
| 1269 | + buf_json(&b, spath); | ||
| 1270 | + buf_addf(&b, ",\"cli_present\":%s,\"count\":%d,\"accounts\":[", | ||
| 1271 | + cli_ok ? "true" : "false", count); | ||
| 1272 | + | ||
| 1273 | + for (i = 0; i < count; i++) { | ||
| 1274 | + if (i > 0) buf_addc(&b, ','); | ||
| 1275 | + buf_adds(&b, "{\"email\":"); | ||
| 1276 | + buf_json(&b, accts[i].email); | ||
| 1277 | + buf_addf(&b, ",\"has_refresh\":%s,\"selected\":%s}", | ||
| 1278 | + accts[i].has_refresh ? "true" : "false", | ||
| 1279 | + accts[i].selected ? "true" : "false"); | ||
| 1280 | + } | ||
| 1281 | + buf_adds(&b, "]}\n"); | ||
| 1282 | + | ||
| 1283 | + json_headers(); | ||
| 1284 | + fputs(buf_str(&b), stdout); | ||
| 1285 | + buf_free(&b); | ||
| 1286 | + return 0; | ||
| 1287 | +} | ||
| 1288 | + | ||
| 1289 | +static int action_quota(const char *target_email) | ||
| 1290 | +{ | ||
| 1291 | + acct_entry_t accts[MAX_ACCOUNTS]; | ||
| 1292 | + char selected[EMAIL_SZ]; | ||
| 1293 | + int count, i; | ||
| 1294 | + const char *bin = quota_bin(); | ||
| 1295 | + buf_t b; | ||
| 1296 | + | ||
| 1297 | + count = load_accounts(accts, MAX_ACCOUNTS, selected, sizeof(selected)); | ||
| 1298 | + prepare_quota_env(); | ||
| 1299 | + | ||
| 1300 | + if (target_email && target_email[0]) { | ||
| 1301 | + int idx = -1; | ||
| 1302 | + buf_t raw; | ||
| 1303 | + acct_quota_t q; | ||
| 1304 | + int rc; | ||
| 1305 | + | ||
| 1306 | + for (i = 0; i < count; i++) { | ||
| 1307 | + if (strcmp(accts[i].email, target_email) == 0) { idx = i; break; } | ||
| 1308 | + } | ||
| 1309 | + if (idx < 0) { | ||
| 1310 | + emit_error(404, "Not Found", "unknown_account", target_email); | ||
| 1311 | + return 1; | ||
| 1312 | + } | ||
| 1313 | + | ||
| 1314 | + buf_init(&raw); | ||
| 1315 | + rc = run_quota_one(bin, accts[idx].email, &raw); | ||
| 1316 | + parse_quota_output(&raw, rc, &q); | ||
| 1317 | + buf_free(&raw); | ||
| 1318 | + | ||
| 1319 | + if (q.cli_missing) { | ||
| 1320 | + emit_error(200, "OK", "cli_unavailable", | ||
| 1321 | + "scorpiox-google-quota was not found on PATH; install SCORPIOX CODE or set GOOGLE_QUOTA_BIN"); | ||
| 1322 | + return 1; | ||
| 1323 | + } | ||
| 1324 | + | ||
| 1325 | + buf_init(&b); | ||
| 1326 | + buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"selected\":"); | ||
| 1327 | + buf_json(&b, selected); | ||
| 1328 | + buf_adds(&b, ",\"account\":"); | ||
| 1329 | + emit_acct_quota_json(&b, &accts[idx], &q); | ||
| 1330 | + buf_adds(&b, "}\n"); | ||
| 1331 | + | ||
| 1332 | + json_headers(); | ||
| 1333 | + fputs(buf_str(&b), stdout); | ||
| 1334 | + buf_free(&b); | ||
| 1335 | + return 0; | ||
| 1336 | + } | ||
| 1337 | + | ||
| 1338 | + { | ||
| 1339 | + acct_quota_t *qs = NULL; | ||
| 1340 | + const char *best_g = ""; | ||
| 1341 | + const char *best_c = ""; | ||
| 1342 | + double best_gp = -1.0; | ||
| 1343 | + double best_cp = -1.0; | ||
| 1344 | + | ||
| 1345 | + if (count > 0) { | ||
| 1346 | + qs = (acct_quota_t *)calloc((size_t)count, sizeof(acct_quota_t)); | ||
| 1347 | + if (!qs) { | ||
| 1348 | + emit_error(500, "Internal Server Error", "oom", "out of memory"); | ||
| 1349 | + return 1; | ||
| 1350 | + } | ||
| 1351 | + fetch_all_quotas(bin, accts, count, qs); | ||
| 1352 | + | ||
| 1353 | + if (qs[0].cli_missing) { | ||
| 1354 | + free(qs); | ||
| 1355 | + emit_error(200, "OK", "cli_unavailable", | ||
| 1356 | + "scorpiox-google-quota was not found on PATH; install SCORPIOX CODE or set GOOGLE_QUOTA_BIN"); | ||
| 1357 | + return 1; | ||
| 1358 | + } | ||
| 1359 | + | ||
| 1360 | + for (i = 0; i < count; i++) { | ||
| 1361 | + if (!qs[i].ok) continue; | ||
| 1362 | + if (qs[i].gemini.present && !qs[i].gemini.exhausted && qs[i].gemini.pct > best_gp) { | ||
| 1363 | + best_gp = qs[i].gemini.pct; | ||
| 1364 | + best_g = accts[i].email; | ||
| 1365 | + } | ||
| 1366 | + if (qs[i].claude.present && !qs[i].claude.exhausted && qs[i].claude.pct > best_cp) { | ||
| 1367 | + best_cp = qs[i].claude.pct; | ||
| 1368 | + best_c = accts[i].email; | ||
| 1369 | + } | ||
| 1370 | + } | ||
| 1371 | + } | ||
| 1372 | + | ||
| 1373 | + buf_init(&b); | ||
| 1374 | + buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"selected\":"); | ||
| 1375 | + buf_json(&b, selected); | ||
| 1376 | + buf_adds(&b, ",\"best_gemini\":"); | ||
| 1377 | + buf_json(&b, best_g); | ||
| 1378 | + buf_adds(&b, ",\"best_claude\":"); | ||
| 1379 | + buf_json(&b, best_c); | ||
| 1380 | + buf_addf(&b, ",\"count\":%d,\"accounts\":[", count); | ||
| 1381 | + for (i = 0; i < count; i++) { | ||
| 1382 | + if (i > 0) buf_addc(&b, ','); | ||
| 1383 | + emit_acct_quota_json(&b, &accts[i], &qs[i]); | ||
| 1384 | + } | ||
| 1385 | + buf_adds(&b, "]}\n"); | ||
| 1386 | + | ||
| 1387 | + free(qs); | ||
| 1388 | + json_headers(); | ||
| 1389 | + fputs(buf_str(&b), stdout); | ||
| 1390 | + buf_free(&b); | ||
| 1391 | + return 0; | ||
| 1392 | + } | ||
| 1393 | +} | ||
| 1394 | + | ||
| 1395 | +static int action_switch(const char *target_email) | ||
| 1396 | +{ | ||
| 1397 | + acct_entry_t accts[MAX_ACCOUNTS]; | ||
| 1398 | + char selected[EMAIL_SZ]; | ||
| 1399 | + char spath[PATH_SZ]; | ||
| 1400 | + int count, i, found = 0; | ||
| 1401 | + FILE *f; | ||
| 1402 | + buf_t b; | ||
| 1403 | + | ||
| 1404 | + if (!target_email || !target_email[0]) { | ||
| 1405 | + emit_error(400, "Bad Request", "missing_account", "pass ?account=<email>"); | ||
| 1406 | + return 1; | ||
| 1407 | + } | ||
| 1408 | + if (!is_safe_email(target_email)) { | ||
| 1409 | + emit_error(400, "Bad Request", "invalid_account", target_email); | ||
| 1410 | + return 1; | ||
| 1411 | + } | ||
| 1412 | + | ||
| 1413 | + count = load_accounts(accts, MAX_ACCOUNTS, selected, sizeof(selected)); | ||
| 1414 | + for (i = 0; i < count; i++) { | ||
| 1415 | + if (strcmp(accts[i].email, target_email) == 0) { found = 1; break; } | ||
| 1416 | + } | ||
| 1417 | + if (!found) { | ||
| 1418 | + emit_error(404, "Not Found", "unknown_account", target_email); | ||
| 1419 | + return 1; | ||
| 1420 | + } | ||
| 1421 | + | ||
| 1422 | + selected_path(spath, sizeof(spath)); | ||
| 1423 | + f = fopen(spath, "wb"); | ||
| 1424 | + if (!f) { | ||
| 1425 | + emit_error(500, "Internal Server Error", "write_failed", strerror(errno)); | ||
| 1426 | + return 1; | ||
| 1427 | + } | ||
| 1428 | + fprintf(f, "%s\n", target_email); | ||
| 1429 | + fclose(f); | ||
| 1430 | + | ||
| 1431 | + buf_init(&b); | ||
| 1432 | + buf_adds(&b, "{\"ok\":true,\"selected\":"); | ||
| 1433 | + buf_json(&b, target_email); | ||
| 1434 | + buf_adds(&b, "}\n"); | ||
| 1435 | + json_headers(); | ||
| 1436 | + fputs(buf_str(&b), stdout); | ||
| 1437 | + buf_free(&b); | ||
| 1438 | + return 0; | ||
| 1439 | +} | ||
| 1440 | + | ||
| 1441 | +/* ------------------------------------------------------------------ */ | ||
| 1442 | +/* HTML emission */ | ||
| 1443 | +/* ------------------------------------------------------------------ */ | ||
| 1444 | + | ||
| 1445 | +static void emit_ui(void) | ||
| 1446 | +{ | ||
| 1447 | + const char *p = UI_HTML; | ||
| 1448 | + | ||
| 1449 | + while (*p) { | ||
| 1450 | + if (*p == '\001') { | ||
| 1451 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout); | ||
| 1452 | + p++; | ||
| 1453 | + } else if (*p == '\002') { | ||
| 1454 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | ||
| 1455 | + p++; | ||
| 1456 | + } else { | ||
| 1457 | + putchar(*p++); | ||
| 1458 | + } | ||
| 1459 | + } | ||
| 1460 | +} | ||
| 1461 | + | ||
| 1462 | +/* ------------------------------------------------------------------ */ | ||
| 1463 | +/* main */ | ||
| 1464 | +/* ------------------------------------------------------------------ */ | ||
| 1465 | + | ||
| 1466 | +static void read_post_account(char *out, size_t outsz) | ||
| 1467 | +{ | ||
| 1468 | + const char *cl = getenv("CONTENT_LENGTH"); | ||
| 1469 | + long n = (cl && *cl) ? atol(cl) : 0; | ||
| 1470 | + char body[4096]; | ||
| 1471 | + size_t len = 0; | ||
| 1472 | + | ||
| 1473 | + if (n > 0 && n < (long)sizeof(body)) { | ||
| 1474 | + len = fread(body, 1, (size_t)n, stdin); | ||
| 1475 | + } else { | ||
| 1476 | + const char *pbf = getenv("POST_BODY_FILE"); | ||
| 1477 | + if (pbf && *pbf) { | ||
| 1478 | + char *fbuf = read_file(pbf); | ||
| 1479 | + if (fbuf) { | ||
| 1480 | + len = strlen(fbuf); | ||
| 1481 | + if (len >= sizeof(body)) len = sizeof(body) - 1; | ||
| 1482 | + memcpy(body, fbuf, len); | ||
| 1483 | + free(fbuf); | ||
| 1484 | + } | ||
| 1485 | + } | ||
| 1486 | + } | ||
| 1487 | + if (len == 0) return; | ||
| 1488 | + body[len] = '\0'; | ||
| 1489 | + if (!json_str_field(body, body + len, "account", out, outsz)) | ||
| 1490 | + json_str_field(body, body + len, "email", out, outsz); | ||
| 1491 | +} | ||
| 1492 | + | ||
| 1493 | +int main(int argc, char **argv) | ||
| 1494 | +{ | ||
| 1495 | + const char *qs; | ||
| 1496 | + char action[64] = {0}; | ||
| 1497 | + | ||
| 1498 | + /* 1. Discovery metadata. Must stay unauthenticated. */ | ||
| 1499 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { | ||
| 1500 | + puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}"); | ||
| 1501 | + return 0; | ||
| 1502 | + } | ||
| 1503 | + if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) { | ||
| 1504 | + puts(PLUGIN_ID " " PLUGIN_VER); | ||
| 1505 | + return 0; | ||
| 1506 | + } | ||
| 1507 | + | ||
| 1508 | + require_node_auth(); | ||
| 1509 | + | ||
| 1510 | + qs = getenv("QUERY_STRING"); | ||
| 1511 | + if (!qs) qs = ""; | ||
| 1512 | + | ||
| 1513 | + /* 2. JSON API mode. */ | ||
| 1514 | + if (query_has(qs, "action") || query_has(qs, "format")) { | ||
| 1515 | + char fmt[32] = {0}; | ||
| 1516 | + char account[EMAIL_SZ] = {0}; | ||
| 1517 | + | ||
| 1518 | + get_query_val(qs, "action", action, sizeof(action)); | ||
| 1519 | + get_query_val(qs, "format", fmt, sizeof(fmt)); | ||
| 1520 | + if (!get_query_val(qs, "account", account, sizeof(account))) | ||
| 1521 | + get_query_val(qs, "email", account, sizeof(account)); | ||
| 1522 | + | ||
| 1523 | + if (!action[0] && strcmp(fmt, "json") == 0) | ||
| 1524 | + snprintf(action, sizeof(action), "quota"); | ||
| 1525 | + | ||
| 1526 | + if (strcmp(action, "status") == 0 || !action[0]) return action_status(); | ||
| 1527 | + if (strcmp(action, "quota") == 0) return action_quota(account); | ||
| 1528 | + if (strcmp(action, "switch") == 0) { | ||
| 1529 | + if (!account[0]) read_post_account(account, sizeof(account)); | ||
| 1530 | + return action_switch(account); | ||
| 1531 | + } | ||
| 1532 | + emit_error(404, "Not Found", "unknown_action", action); | ||
| 1533 | + return 1; | ||
| 1534 | + } | ||
| 1535 | + | ||
| 1536 | + /* 3. HTML UI mode. */ | ||
| 1537 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 1538 | + "Cache-Control: no-store\r\n" | ||
| 1539 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1540 | + emit_ui(); | ||
| 1541 | + return 0; | ||
| 1542 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..4a15f36 | index 0000000..4a15f36 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui.html | +++ b/src/ui.html | ||
| @@ -0,0 +1,462 @@ | @@ -0,0 +1,462 @@ | ||
| 1 | +<!DOCTYPE html> | ||
| 2 | +<html lang="en"><head><meta charset="utf-8"> | ||
| 3 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | ||
| 4 | +<title>google quota</title> | ||
| 5 | +<!--TOKENS--> | ||
| 6 | +<style> | ||
| 7 | +*{box-sizing:border-box} | ||
| 8 | +html,body{margin:0;min-height:100%} | ||
| 9 | +body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px; | ||
| 10 | + line-height:1.5;-webkit-font-smoothing:antialiased} | ||
| 11 | +#app{max-width:880px;margin:0 auto;padding:16px 16px 40px} | ||
| 12 | +.hd{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px} | ||
| 13 | +.hd .grow{flex:1 1 auto;min-width:0} | ||
| 14 | +.hd h1{margin:0;font-size:18px;font-weight:650;letter-spacing:-.01em} | ||
| 15 | +.hd .sub{font-size:11.5px;color:var(--text-2);margin-top:2px;white-space:nowrap; | ||
| 16 | + overflow:hidden;text-overflow:ellipsis} | ||
| 17 | +.pill{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:650; | ||
| 18 | + padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-2); | ||
| 19 | + border:1px solid var(--line);white-space:nowrap} | ||
| 20 | +.pill .dot{width:7px;height:7px;border-radius:50%;background:var(--gray);flex:0 0 auto} | ||
| 21 | +.pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)} | ||
| 22 | +.pill.ok .dot{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.15)} | ||
| 23 | +.pill.warn{color:var(--orange);border-color:rgba(255,159,10,.35)} | ||
| 24 | +.pill.warn .dot{background:var(--orange)} | ||
| 25 | +.pill.bad{color:var(--red);border-color:rgba(255,69,58,.35)} | ||
| 26 | +.pill.bad .dot{background:var(--red)} | ||
| 27 | +.pill.off .dot{background:var(--gray)} | ||
| 28 | +#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text); | ||
| 29 | + border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer; | ||
| 30 | + font-family:inherit} | ||
| 31 | +.kpis{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin-bottom:12px} | ||
| 32 | +.kpi{background:var(--bg-card);border:1px solid var(--line);border-radius:12px;padding:12px 14px;min-width:0} | ||
| 33 | +.kpi .lbl{font-size:11px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--text-2)} | ||
| 34 | +.kpi .val{margin-top:4px;font-size:15px;font-weight:650;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} | ||
| 35 | +.kpi .meta{margin-top:2px;font-size:11.5px;color:var(--text-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} | ||
| 36 | +.bar-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:12px} | ||
| 37 | +.bar-row .spacer{flex:1 1 auto} | ||
| 38 | +.status-txt{font-size:12px;color:var(--text-2)} | ||
| 39 | +.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:6px 14px; | ||
| 40 | + font-weight:600;font-size:12.5px;cursor:pointer;font-family:inherit; | ||
| 41 | + transition:transform .12s var(--ease),opacity .12s} | ||
| 42 | +.btn:active{transform:scale(.98)} | ||
| 43 | +.btn:disabled{opacity:.5;cursor:default} | ||
| 44 | +.btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)} | ||
| 45 | +.btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)} | ||
| 46 | +.btn.sm{padding:4px 11px;font-size:11.5px} | ||
| 47 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px; | ||
| 48 | + padding:14px 16px;margin-bottom:10px} | ||
| 49 | +.card.selected{border-color:var(--blue)} | ||
| 50 | +.card h2{margin:0 0 4px;font-size:12.5px;font-weight:700;letter-spacing:.08em; | ||
| 51 | + text-transform:uppercase;color:var(--text-2)} | ||
| 52 | +.acct-top{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:10px} | ||
| 53 | +.acct-email{font-family:var(--mono);font-size:13px;font-weight:650;word-break:break-all;flex:1 1 auto;min-width:0} | ||
| 54 | +.badges{display:flex;align-items:center;gap:6px;flex-wrap:wrap} | ||
| 55 | +.tag{font-size:11px;font-weight:650;padding:2px 8px;border-radius:999px; | ||
| 56 | + background:var(--surface-2);color:var(--text-2);border:1px solid var(--line)} | ||
| 57 | +.tag.sel{color:var(--blue);border-color:rgba(10,132,255,.4)} | ||
| 58 | +.tag.best{color:var(--green);border-color:rgba(48,209,88,.35)} | ||
| 59 | +.pools{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px} | ||
| 60 | +.pool{background:var(--surface-2);border:1px solid var(--line);border-radius:10px;padding:10px 12px} | ||
| 61 | +.pool-hd{display:flex;align-items:baseline;justify-content:space-between;gap:8px;margin-bottom:6px} | ||
| 62 | +.pool-name{font-size:12px;font-weight:650;color:var(--text)} | ||
| 63 | +.pool-pct{font-family:var(--mono);font-size:12.5px;font-weight:700} | ||
| 64 | +.pool-pct.ok{color:var(--green)} | ||
| 65 | +.pool-pct.warn{color:var(--orange)} | ||
| 66 | +.pool-pct.bad{color:var(--red)} | ||
| 67 | +.pool-pct.dim{color:var(--text-2)} | ||
| 68 | +.meter{height:6px;border-radius:999px;background:var(--line);overflow:hidden} | ||
| 69 | +.meter > i{display:block;height:100%;border-radius:999px;background:var(--gray);transition:width .25s var(--ease)} | ||
| 70 | +.meter > i.ok{background:var(--green)} | ||
| 71 | +.meter > i.warn{background:var(--orange)} | ||
| 72 | +.meter > i.bad{background:var(--red)} | ||
| 73 | +.pool-reset{margin-top:6px;font-size:11.5px;color:var(--text-2)} | ||
| 74 | +.models{display:none;margin-top:10px;padding-top:10px;border-top:1px solid var(--line); | ||
| 75 | + grid-template-columns:repeat(2,minmax(0,1fr));gap:4px 14px} | ||
| 76 | +.models.show{display:grid} | ||
| 77 | +.mrow{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:11.5px;padding:2px 0} | ||
| 78 | +.mrow .mid{font-family:var(--mono);color:var(--text-2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | ||
| 79 | +.mrow .mpct{font-family:var(--mono);font-weight:650;flex:0 0 auto} | ||
| 80 | +.mrow .mpct.ok{color:var(--green)} | ||
| 81 | +.mrow .mpct.warn{color:var(--orange)} | ||
| 82 | +.mrow .mpct.bad{color:var(--red)} | ||
| 83 | +.err-msg{font-size:12px;color:var(--red);padding:4px 0} | ||
| 84 | +.empty{padding:18px 16px;text-align:center;color:var(--text-2);font-size:13px} | ||
| 85 | +.kv{display:grid;grid-template-columns:120px minmax(0,1fr);gap:5px 12px;font-size:12px} | ||
| 86 | +.kv .k{color:var(--text-2)} | ||
| 87 | +.kv .v{font-family:var(--mono);word-break:break-all} | ||
| 88 | +.note{display:none;margin-bottom:12px;padding:10px 12px;border-radius:10px;font-size:12.5px; | ||
| 89 | + border:1px solid var(--line);background:var(--surface-2)} | ||
| 90 | +.note.show{display:block} | ||
| 91 | +.note.err{color:var(--red);border-color:rgba(255,69,58,.35)} | ||
| 92 | +.note.warn{color:var(--orange);border-color:rgba(255,159,10,.35)} | ||
| 93 | +.toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0; | ||
| 94 | + pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2); | ||
| 95 | + color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px; | ||
| 96 | + box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease); | ||
| 97 | + z-index:9;max-width:calc(100vw - 32px)} | ||
| 98 | +.toast.show{opacity:1;transform:translate(-50%,0)} | ||
| 99 | +@media (max-width:600px){ | ||
| 100 | + #app{padding:12px 12px 32px} | ||
| 101 | + .kpis{grid-template-columns:1fr} | ||
| 102 | + .pools{grid-template-columns:1fr} | ||
| 103 | + .models{grid-template-columns:1fr} | ||
| 104 | + .kv{grid-template-columns:1fr;gap:2px 0} | ||
| 105 | + .kv .k{margin-top:6px} | ||
| 106 | +} | ||
| 107 | +</style> | ||
| 108 | +</head> | ||
| 109 | +<body> | ||
| 110 | +<div id="app"> | ||
| 111 | + <div class="hd"> | ||
| 112 | + <div class="grow"> | ||
| 113 | + <h1>Google Quotas</h1> | ||
| 114 | + <div class="sub" id="sub">Antigravity account pools on this node</div> | ||
| 115 | + </div> | ||
| 116 | + <span class="pill off" id="pill"><span class="dot"></span><span id="pillText">Loading</span></span> | ||
| 117 | + <button id="themeToggle" class="embed-hide" type="button">Theme</button> | ||
| 118 | + </div> | ||
| 119 | + | ||
| 120 | + <div class="kpis"> | ||
| 121 | + <div class="kpi"> | ||
| 122 | + <div class="lbl">Active Account</div> | ||
| 123 | + <div class="val" id="kpiSelected">-</div> | ||
| 124 | + <div class="meta" id="kpiSelectedMeta">selected_account.txt</div> | ||
| 125 | + </div> | ||
| 126 | + <div class="kpi"> | ||
| 127 | + <div class="lbl">Best Gemini</div> | ||
| 128 | + <div class="val" id="kpiGemini">-</div> | ||
| 129 | + <div class="meta" id="kpiGeminiMeta">Waiting for quota</div> | ||
| 130 | + </div> | ||
| 131 | + <div class="kpi"> | ||
| 132 | + <div class="lbl">Best Claude</div> | ||
| 133 | + <div class="val" id="kpiClaude">-</div> | ||
| 134 | + <div class="meta" id="kpiClaudeMeta">Waiting for quota</div> | ||
| 135 | + </div> | ||
| 136 | + </div> | ||
| 137 | + | ||
| 138 | + <div class="bar-row"> | ||
| 139 | + <button class="btn" id="btnRefresh" type="button">Refresh Quotas</button> | ||
| 140 | + <button class="btn ghost" id="btnModels" type="button">Show Models</button> | ||
| 141 | + <span class="spacer"></span> | ||
| 142 | + <span class="status-txt" id="statusTxt"></span> | ||
| 143 | + </div> | ||
| 144 | + | ||
| 145 | + <div class="note" id="banner"></div> | ||
| 146 | + <div id="accounts"></div> | ||
| 147 | + | ||
| 148 | + <div class="card"> | ||
| 149 | + <h2>Node Paths</h2> | ||
| 150 | + <div class="kv" id="paths"></div> | ||
| 151 | + </div> | ||
| 152 | +</div> | ||
| 153 | + | ||
| 154 | +<div class="toast" id="toast"></div> | ||
| 155 | + | ||
| 156 | +<script> | ||
| 157 | +var q=new URLSearchParams(location.search); | ||
| 158 | +var node=q.get('node')||''; | ||
| 159 | +var sid=q.get('id')||''; | ||
| 160 | +var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))|| | ||
| 161 | + localStorage.getItem('bot_active_pwd')||''; | ||
| 162 | +var HUB=q.get('plugin')||''; | ||
| 163 | + | ||
| 164 | +function url(action,extra){ | ||
| 165 | + return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_google_quota')+ | ||
| 166 | + '?action='+encodeURIComponent(action)+ | ||
| 167 | + (extra?('&'+extra):'')+ | ||
| 168 | + (node?'&node='+encodeURIComponent(node):'')+ | ||
| 169 | + (sid?'&id='+encodeURIComponent(sid):'')+ | ||
| 170 | + (pwd?'&pwd='+encodeURIComponent(pwd):''); | ||
| 171 | +} | ||
| 172 | +function hdr(){ | ||
| 173 | + var h={}; | ||
| 174 | + if(pwd)h['X-Bot-Password']=pwd; | ||
| 175 | + return h; | ||
| 176 | +} | ||
| 177 | +function api(action,extra){ | ||
| 178 | + return fetch(url(action,extra),{headers:hdr()}).then(function(r){ | ||
| 179 | + return r.json().catch(function(){return {ok:false,error:'bad response'};}); | ||
| 180 | + }); | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +var $=function(id){return document.getElementById(id);}; | ||
| 184 | +var state={selected:'',accounts:[],quotas:{},showModels:false,cliPresent:false,loading:false}; | ||
| 185 | + | ||
| 186 | +function toast(msg){ | ||
| 187 | + var t=$('toast');t.textContent=msg;t.classList.add('show'); | ||
| 188 | + clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200); | ||
| 189 | +} | ||
| 190 | +function setBanner(msg,kind){ | ||
| 191 | + var el=$('banner'); | ||
| 192 | + el.textContent=msg||''; | ||
| 193 | + el.className='note'+(msg?' show '+(kind||''):''); | ||
| 194 | +} | ||
| 195 | +function shortEmail(e){ | ||
| 196 | + if(!e)return '-'; | ||
| 197 | + var i=e.indexOf('@'); | ||
| 198 | + return i>0?e.slice(0,i):e; | ||
| 199 | +} | ||
| 200 | +function pctClass(pct,exhausted){ | ||
| 201 | + if(exhausted||pct===null||pct===undefined||pct<10)return 'bad'; | ||
| 202 | + if(pct<50)return 'warn'; | ||
| 203 | + return 'ok'; | ||
| 204 | +} | ||
| 205 | +function fmtPct(pool){ | ||
| 206 | + if(!pool)return '...'; | ||
| 207 | + if(pool.exhausted||pool.pct===null||pool.pct===undefined)return 'EXHAUSTED'; | ||
| 208 | + if(pool.pct<0)return 'N/A'; | ||
| 209 | + return pool.pct.toFixed(1)+'%'; | ||
| 210 | +} | ||
| 211 | +function fmtReset(iso){ | ||
| 212 | + if(!iso)return 'Reset: -'; | ||
| 213 | + var t=Date.parse(iso); | ||
| 214 | + if(isNaN(t))return 'Reset: '+iso; | ||
| 215 | + var diff=Math.floor((t-Date.now())/1000); | ||
| 216 | + if(diff<=0)return 'Resets soon'; | ||
| 217 | + var d=Math.floor(diff/86400); | ||
| 218 | + var h=Math.floor((diff%86400)/3600); | ||
| 219 | + var m=Math.floor((diff%3600)/60); | ||
| 220 | + if(d>0)return 'Resets in '+d+'d '+h+'h'; | ||
| 221 | + if(h>0)return 'Resets in '+h+'h '+m+'m'; | ||
| 222 | + return 'Resets in '+Math.max(1,m)+'m'; | ||
| 223 | +} | ||
| 224 | +function el(tag,cls,txt){ | ||
| 225 | + var n=document.createElement(tag); | ||
| 226 | + if(cls)n.className=cls; | ||
| 227 | + if(txt!==undefined&&txt!==null)n.textContent=txt; | ||
| 228 | + return n; | ||
| 229 | +} | ||
| 230 | + | ||
| 231 | +function computeBest(){ | ||
| 232 | + var bestG=null,bestGP=-1,bestC=null,bestCP=-1; | ||
| 233 | + state.accounts.forEach(function(a){ | ||
| 234 | + var qd=state.quotas[a.email]; | ||
| 235 | + if(!qd||!qd.ok)return; | ||
| 236 | + if(qd.gemini&&!qd.gemini.exhausted&&qd.gemini.pct>bestGP){ | ||
| 237 | + bestGP=qd.gemini.pct;bestG=a.email; | ||
| 238 | + } | ||
| 239 | + if(qd.claude&&!qd.claude.exhausted&&qd.claude.pct>bestCP){ | ||
| 240 | + bestCP=qd.claude.pct;bestC=a.email; | ||
| 241 | + } | ||
| 242 | + }); | ||
| 243 | + return {gemini:bestG,geminiPct:bestGP,claude:bestC,claudePct:bestCP}; | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +function renderPool(label,pool,loading){ | ||
| 247 | + var box=el('div','pool'); | ||
| 248 | + var hd=el('div','pool-hd'); | ||
| 249 | + hd.appendChild(el('span','pool-name',label)); | ||
| 250 | + var pctEl=el('span','pool-pct'); | ||
| 251 | + var bar=el('div','meter'); | ||
| 252 | + var fill=el('i'); | ||
| 253 | + var rst=el('div','pool-reset'); | ||
| 254 | + | ||
| 255 | + if(loading&&!pool){ | ||
| 256 | + pctEl.className='pool-pct dim'; | ||
| 257 | + pctEl.textContent='Checking...'; | ||
| 258 | + fill.style.width='0%'; | ||
| 259 | + rst.textContent='Querying quota CLI'; | ||
| 260 | + }else if(!pool||pool.pct<0){ | ||
| 261 | + pctEl.className='pool-pct dim'; | ||
| 262 | + pctEl.textContent='N/A'; | ||
| 263 | + fill.style.width='0%'; | ||
| 264 | + rst.textContent='No buckets reported'; | ||
| 265 | + }else{ | ||
| 266 | + var cls=pctClass(pool.pct,pool.exhausted); | ||
| 267 | + pctEl.className='pool-pct '+cls; | ||
| 268 | + pctEl.textContent=fmtPct(pool); | ||
| 269 | + var w=pool.exhausted?0:Math.max(0,Math.min(100,pool.pct)); | ||
| 270 | + fill.className=cls; | ||
| 271 | + fill.style.width=w.toFixed(1)+'%'; | ||
| 272 | + rst.textContent=fmtReset(pool.reset_time); | ||
| 273 | + } | ||
| 274 | + hd.appendChild(pctEl); | ||
| 275 | + bar.appendChild(fill); | ||
| 276 | + box.appendChild(hd); | ||
| 277 | + box.appendChild(bar); | ||
| 278 | + box.appendChild(rst); | ||
| 279 | + return box; | ||
| 280 | +} | ||
| 281 | + | ||
| 282 | +function render(){ | ||
| 283 | + var best=computeBest(); | ||
| 284 | + $('kpiSelected').textContent=shortEmail(state.selected); | ||
| 285 | + $('kpiSelected').title=state.selected||''; | ||
| 286 | + $('kpiSelectedMeta').textContent=state.selected||'None selected'; | ||
| 287 | + | ||
| 288 | + $('kpiGemini').textContent=best.gemini?shortEmail(best.gemini):'-'; | ||
| 289 | + $('kpiGemini').title=best.gemini||''; | ||
| 290 | + $('kpiGeminiMeta').textContent=best.gemini?(best.geminiPct.toFixed(1)+'% remaining'):(state.loading?'Checking...':'No quota data'); | ||
| 291 | + | ||
| 292 | + $('kpiClaude').textContent=best.claude?shortEmail(best.claude):'-'; | ||
| 293 | + $('kpiClaude').title=best.claude||''; | ||
| 294 | + $('kpiClaudeMeta').textContent=best.claude?(best.claudePct.toFixed(1)+'% remaining'):(state.loading?'Checking...':'No quota data'); | ||
| 295 | + | ||
| 296 | + var wrap=$('accounts'); | ||
| 297 | + wrap.innerHTML=''; | ||
| 298 | + if(!state.accounts.length){ | ||
| 299 | + var empty=el('div','card empty','No accounts found in antigravity_accounts.json. Sign in with scorpiox-antigravity-login first.'); | ||
| 300 | + wrap.appendChild(empty); | ||
| 301 | + return; | ||
| 302 | + } | ||
| 303 | + | ||
| 304 | + state.accounts.forEach(function(a){ | ||
| 305 | + var isSel=(a.email===state.selected); | ||
| 306 | + var qd=state.quotas[a.email]; | ||
| 307 | + var card=el('div','card'+(isSel?' selected':'')); | ||
| 308 | + | ||
| 309 | + var top=el('div','acct-top'); | ||
| 310 | + top.appendChild(el('div','acct-email',a.email)); | ||
| 311 | + | ||
| 312 | + var badges=el('div','badges'); | ||
| 313 | + if(isSel)badges.appendChild(el('span','tag sel','Selected')); | ||
| 314 | + if(best.gemini===a.email)badges.appendChild(el('span','tag best','Best Gemini')); | ||
| 315 | + if(best.claude===a.email)badges.appendChild(el('span','tag best','Best Claude')); | ||
| 316 | + if(!a.has_refresh)badges.appendChild(el('span','tag','No refresh token')); | ||
| 317 | + top.appendChild(badges); | ||
| 318 | + | ||
| 319 | + var sw=el('button','btn sm'+(isSel?' ghost':''),isSel?'Active':'Use'); | ||
| 320 | + sw.type='button'; | ||
| 321 | + sw.disabled=isSel; | ||
| 322 | + sw.onclick=function(){switchAccount(a.email,sw);}; | ||
| 323 | + top.appendChild(sw); | ||
| 324 | + card.appendChild(top); | ||
| 325 | + | ||
| 326 | + if(qd&&!qd.ok){ | ||
| 327 | + card.appendChild(el('div','err-msg','Error: '+(qd.detail||qd.error||'quota fetch failed'))); | ||
| 328 | + }else{ | ||
| 329 | + var pools=el('div','pools'); | ||
| 330 | + pools.appendChild(renderPool('Gemini Pool',qd?qd.gemini:null,state.loading)); | ||
| 331 | + pools.appendChild(renderPool('Claude Pool',qd?qd.claude:null,state.loading)); | ||
| 332 | + card.appendChild(pools); | ||
| 333 | + | ||
| 334 | + if(qd&&qd.models&&qd.models.length){ | ||
| 335 | + var mgrid=el('div','models'+(state.showModels?' show':'')); | ||
| 336 | + qd.models.forEach(function(m){ | ||
| 337 | + var row=el('div','mrow'); | ||
| 338 | + row.appendChild(el('span','mid',m.id)); | ||
| 339 | + var cls=pctClass(m.pct,m.exhausted); | ||
| 340 | + row.appendChild(el('span','mpct '+cls,m.exhausted?'EXH':(m.pct.toFixed(1)+'%'))); | ||
| 341 | + mgrid.appendChild(row); | ||
| 342 | + }); | ||
| 343 | + card.appendChild(mgrid); | ||
| 344 | + } | ||
| 345 | + } | ||
| 346 | + wrap.appendChild(card); | ||
| 347 | + }); | ||
| 348 | +} | ||
| 349 | + | ||
| 350 | +function switchAccount(email,btn){ | ||
| 351 | + btn.disabled=true; | ||
| 352 | + btn.textContent='Switching...'; | ||
| 353 | + api('switch','account='+encodeURIComponent(email)).then(function(d){ | ||
| 354 | + if(!d||!d.ok){ | ||
| 355 | + toast((d&&(d.detail||d.error))||'Switch failed'); | ||
| 356 | + render(); | ||
| 357 | + return; | ||
| 358 | + } | ||
| 359 | + state.selected=d.selected||email; | ||
| 360 | + toast('Selected '+state.selected); | ||
| 361 | + render(); | ||
| 362 | + }).catch(function(e){ | ||
| 363 | + toast('Switch failed: '+e.message); | ||
| 364 | + render(); | ||
| 365 | + }); | ||
| 366 | +} | ||
| 367 | + | ||
| 368 | +function fetchQuotas(){ | ||
| 369 | + if(!state.accounts.length||!state.cliPresent)return; | ||
| 370 | + state.loading=true; | ||
| 371 | + $('btnRefresh').disabled=true; | ||
| 372 | + $('btnRefresh').textContent='Refreshing...'; | ||
| 373 | + $('statusTxt').textContent='Querying '+state.accounts.length+' account(s)...'; | ||
| 374 | + render(); | ||
| 375 | + | ||
| 376 | + var queue=state.accounts.slice(); | ||
| 377 | + var done=0,total=queue.length; | ||
| 378 | + var workers=Math.min(4,total); | ||
| 379 | + | ||
| 380 | + function next(){ | ||
| 381 | + if(!queue.length)return Promise.resolve(); | ||
| 382 | + var acct=queue.shift(); | ||
| 383 | + return api('quota','account='+encodeURIComponent(acct.email)).then(function(d){ | ||
| 384 | + if(d&&d.ok&&d.account){ | ||
| 385 | + state.quotas[acct.email]=d.account; | ||
| 386 | + }else{ | ||
| 387 | + state.quotas[acct.email]={ok:false,error:(d&&d.error)||'failed',detail:d&&d.detail}; | ||
| 388 | + } | ||
| 389 | + }).catch(function(e){ | ||
| 390 | + state.quotas[acct.email]={ok:false,error:e.message}; | ||
| 391 | + }).then(function(){ | ||
| 392 | + done++; | ||
| 393 | + $('statusTxt').textContent='Loaded '+done+'/'+total; | ||
| 394 | + render(); | ||
| 395 | + return next(); | ||
| 396 | + }); | ||
| 397 | + } | ||
| 398 | + | ||
| 399 | + var ps=[]; | ||
| 400 | + for(var i=0;i<workers;i++)ps.push(next()); | ||
| 401 | + Promise.all(ps).then(function(){ | ||
| 402 | + state.loading=false; | ||
| 403 | + $('btnRefresh').disabled=false; | ||
| 404 | + $('btnRefresh').textContent='Refresh Quotas'; | ||
| 405 | + $('statusTxt').textContent='Updated '+new Date().toLocaleTimeString(); | ||
| 406 | + render(); | ||
| 407 | + }); | ||
| 408 | +} | ||
| 409 | + | ||
| 410 | +function load(){ | ||
| 411 | + setBanner(''); | ||
| 412 | + api('status').then(function(d){ | ||
| 413 | + if(!d||!d.ok){ | ||
| 414 | + setBanner((d&&(d.detail||d.error))||'Failed to read accounts','err'); | ||
| 415 | + return; | ||
| 416 | + } | ||
| 417 | + state.selected=d.selected||''; | ||
| 418 | + state.accounts=d.accounts||[]; | ||
| 419 | + state.cliPresent=!!d.cli_present; | ||
| 420 | + | ||
| 421 | + var pill=$('pill'),pt=$('pillText'); | ||
| 422 | + if(!state.cliPresent){ | ||
| 423 | + pill.className='pill bad';pt.textContent='CLI missing'; | ||
| 424 | + setBanner('scorpiox-google-quota was not found on PATH. Install SCORPIOX CODE or set GOOGLE_QUOTA_BIN.','warn'); | ||
| 425 | + }else if(!state.accounts.length){ | ||
| 426 | + pill.className='pill warn';pt.textContent='0 accounts'; | ||
| 427 | + }else{ | ||
| 428 | + pill.className='pill ok';pt.textContent=state.accounts.length+' account'+(state.accounts.length===1?'':'s'); | ||
| 429 | + } | ||
| 430 | + | ||
| 431 | + var paths=$('paths'); | ||
| 432 | + paths.innerHTML=''; | ||
| 433 | + [ | ||
| 434 | + ['Accounts JSON',d.accounts_path||'-'], | ||
| 435 | + ['Selected file',d.selected_path||'-'], | ||
| 436 | + ['Quota CLI',d.cli_present?'found':'not found'] | ||
| 437 | + ].forEach(function(r){ | ||
| 438 | + paths.appendChild(el('div','k',r[0])); | ||
| 439 | + paths.appendChild(el('div','v',r[1])); | ||
| 440 | + }); | ||
| 441 | + | ||
| 442 | + render(); | ||
| 443 | + if(state.accounts.length&&state.cliPresent)fetchQuotas(); | ||
| 444 | + }).catch(function(e){ | ||
| 445 | + setBanner('Status failed: '+e.message,'err'); | ||
| 446 | + }); | ||
| 447 | +} | ||
| 448 | + | ||
| 449 | +$('btnRefresh').onclick=fetchQuotas; | ||
| 450 | +$('btnModels').onclick=function(){ | ||
| 451 | + state.showModels=!state.showModels; | ||
| 452 | + $('btnModels').textContent=state.showModels?'Hide Models':'Show Models'; | ||
| 453 | + render(); | ||
| 454 | +}; | ||
| 455 | +$('themeToggle').onclick=function(){ | ||
| 456 | + if(window.sxApplyTheme&&window.sxTheme){ | ||
| 457 | + window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark'); | ||
| 458 | + } | ||
| 459 | +}; | ||
| 460 | +load(); | ||
| 461 | +</script> | ||
| 462 | +</body></html> |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..87a7ad6 | index 0000000..87a7ad6 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui_html.h | +++ b/src/ui_html.h | ||
| @@ -0,0 +1,470 @@ | @@ -0,0 +1,470 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | ||
| 2 | +#ifndef SX_GQUOTA_UI_HTML_H | ||
| 3 | +#define SX_GQUOTA_UI_HTML_H | ||
| 4 | + | ||
| 5 | +static const char *UI_HTML = | ||
| 6 | + "<!DOCTYPE html>\n" | ||
| 7 | + "<html lang=\"en\"><head><meta charset=\"utf-8\">\n" | ||
| 8 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | ||
| 9 | + "<title>google quota</title>\n" | ||
| 10 | + "\001\n" | ||
| 11 | + "<style>\n" | ||
| 12 | + "*{box-sizing:border-box}\n" | ||
| 13 | + "html,body{margin:0;min-height:100%}\n" | ||
| 14 | + "body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;\n" | ||
| 15 | + " line-height:1.5;-webkit-font-smoothing:antialiased}\n" | ||
| 16 | + "#app{max-width:880px;margin:0 auto;padding:16px 16px 40px}\n" | ||
| 17 | + ".hd{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}\n" | ||
| 18 | + ".hd .grow{flex:1 1 auto;min-width:0}\n" | ||
| 19 | + ".hd h1{margin:0;font-size:18px;font-weight:650;letter-spacing:-.01em}\n" | ||
| 20 | + ".hd .sub{font-size:11.5px;color:var(--text-2);margin-top:2px;white-space:nowrap;\n" | ||
| 21 | + " overflow:hidden;text-overflow:ellipsis}\n" | ||
| 22 | + ".pill{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:650;\n" | ||
| 23 | + " padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-2);\n" | ||
| 24 | + " border:1px solid var(--line);white-space:nowrap}\n" | ||
| 25 | + ".pill .dot{width:7px;height:7px;border-radius:50%;background:var(--gray);flex:0 0 auto}\n" | ||
| 26 | + ".pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n" | ||
| 27 | + ".pill.ok .dot{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.15)}\n" | ||
| 28 | + ".pill.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}\n" | ||
| 29 | + ".pill.warn .dot{background:var(--orange)}\n" | ||
| 30 | + ".pill.bad{color:var(--red);border-color:rgba(255,69,58,.35)}\n" | ||
| 31 | + ".pill.bad .dot{background:var(--red)}\n" | ||
| 32 | + ".pill.off .dot{background:var(--gray)}\n" | ||
| 33 | + "#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n" | ||
| 34 | + " border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;\n" | ||
| 35 | + " font-family:inherit}\n" | ||
| 36 | + ".kpis{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin-bottom:12px}\n" | ||
| 37 | + ".kpi{background:var(--bg-card);border:1px solid var(--line);border-radius:12px;padding:12px 14px;min-width:0}\n" | ||
| 38 | + ".kpi .lbl{font-size:11px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--text-2)}\n" | ||
| 39 | + ".kpi .val{margin-top:4px;font-size:15px;font-weight:650;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n" | ||
| 40 | + ".kpi .meta{margin-top:2px;font-size:11.5px;color:var(--text-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n" | ||
| 41 | + ".bar-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:12px}\n" | ||
| 42 | + ".bar-row .spacer{flex:1 1 auto}\n" | ||
| 43 | + ".status-txt{font-size:12px;color:var(--text-2)}\n" | ||
| 44 | + ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:6px 14px;\n" | ||
| 45 | + " font-weight:600;font-size:12.5px;cursor:pointer;font-family:inherit;\n" | ||
| 46 | + " transition:transform .12s var(--ease),opacity .12s}\n" | ||
| 47 | + ".btn:active{transform:scale(.98)}\n" | ||
| 48 | + ".btn:disabled{opacity:.5;cursor:default}\n" | ||
| 49 | + ".btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}\n" | ||
| 50 | + ".btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | ||
| 51 | + ".btn.sm{padding:4px 11px;font-size:11.5px}\n" | ||
| 52 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n" | ||
| 53 | + " padding:14px 16px;margin-bottom:10px}\n" | ||
| 54 | + ".card.selected{border-color:var(--blue)}\n" | ||
| 55 | + ".card h2{margin:0 0 4px;font-size:12.5px;font-weight:700;letter-spacing:.08em;\n" | ||
| 56 | + " text-transform:uppercase;color:var(--text-2)}\n" | ||
| 57 | + ".acct-top{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:10px}\n" | ||
| 58 | + ".acct-email{font-family:var(--mono);font-size:13px;font-weight:650;word-break:break-all;flex:1 1 auto;min-width:0}\n" | ||
| 59 | + ".badges{display:flex;align-items:center;gap:6px;flex-wrap:wrap}\n" | ||
| 60 | + ".tag{font-size:11px;font-weight:650;padding:2px 8px;border-radius:999px;\n" | ||
| 61 | + " background:var(--surface-2);color:var(--text-2);border:1px solid var(--line)}\n" | ||
| 62 | + ".tag.sel{color:var(--blue);border-color:rgba(10,132,255,.4)}\n" | ||
| 63 | + ".tag.best{color:var(--green);border-color:rgba(48,209,88,.35)}\n" | ||
| 64 | + ".pools{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}\n" | ||
| 65 | + ".pool{background:var(--surface-2);border:1px solid var(--line);border-radius:10px;padding:10px 12px}\n" | ||
| 66 | + ".pool-hd{display:flex;align-items:baseline;justify-content:space-between;gap:8px;margin-bottom:6px}\n" | ||
| 67 | + ".pool-name{font-size:12px;font-weight:650;color:var(--text)}\n" | ||
| 68 | + ".pool-pct{font-family:var(--mono);font-size:12.5px;font-weight:700}\n" | ||
| 69 | + ".pool-pct.ok{color:var(--green)}\n" | ||
| 70 | + ".pool-pct.warn{color:var(--orange)}\n" | ||
| 71 | + ".pool-pct.bad{color:var(--red)}\n" | ||
| 72 | + ".pool-pct.dim{color:var(--text-2)}\n" | ||
| 73 | + ".meter{height:6px;border-radius:999px;background:var(--line);overflow:hidden}\n" | ||
| 74 | + ".meter > i{display:block;height:100%;border-radius:999px;background:var(--gray);transition:width .25s var(--ease)}\n" | ||
| 75 | + ".meter > i.ok{background:var(--green)}\n" | ||
| 76 | + ".meter > i.warn{background:var(--orange)}\n" | ||
| 77 | + ".meter > i.bad{background:var(--red)}\n" | ||
| 78 | + ".pool-reset{margin-top:6px;font-size:11.5px;color:var(--text-2)}\n" | ||
| 79 | + ".models{display:none;margin-top:10px;padding-top:10px;border-top:1px solid var(--line);\n" | ||
| 80 | + " grid-template-columns:repeat(2,minmax(0,1fr));gap:4px 14px}\n" | ||
| 81 | + ".models.show{display:grid}\n" | ||
| 82 | + ".mrow{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:11.5px;padding:2px 0}\n" | ||
| 83 | + ".mrow .mid{font-family:var(--mono);color:var(--text-2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | ||
| 84 | + ".mrow .mpct{font-family:var(--mono);font-weight:650;flex:0 0 auto}\n" | ||
| 85 | + ".mrow .mpct.ok{color:var(--green)}\n" | ||
| 86 | + ".mrow .mpct.warn{color:var(--orange)}\n" | ||
| 87 | + ".mrow .mpct.bad{color:var(--red)}\n" | ||
| 88 | + ".err-msg{font-size:12px;color:var(--red);padding:4px 0}\n" | ||
| 89 | + ".empty{padding:18px 16px;text-align:center;color:var(--text-2);font-size:13px}\n" | ||
| 90 | + ".kv{display:grid;grid-template-columns:120px minmax(0,1fr);gap:5px 12px;font-size:12px}\n" | ||
| 91 | + ".kv .k{color:var(--text-2)}\n" | ||
| 92 | + ".kv .v{font-family:var(--mono);word-break:break-all}\n" | ||
| 93 | + ".note{display:none;margin-bottom:12px;padding:10px 12px;border-radius:10px;font-size:12.5px;\n" | ||
| 94 | + " border:1px solid var(--line);background:var(--surface-2)}\n" | ||
| 95 | + ".note.show{display:block}\n" | ||
| 96 | + ".note.err{color:var(--red);border-color:rgba(255,69,58,.35)}\n" | ||
| 97 | + ".note.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}\n" | ||
| 98 | + ".toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;\n" | ||
| 99 | + " pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);\n" | ||
| 100 | + " color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;\n" | ||
| 101 | + " box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);\n" | ||
| 102 | + " z-index:9;max-width:calc(100vw - 32px)}\n" | ||
| 103 | + ".toast.show{opacity:1;transform:translate(-50%,0)}\n" | ||
| 104 | + "@media (max-width:600px){\n" | ||
| 105 | + " #app{padding:12px 12px 32px}\n" | ||
| 106 | + " .kpis{grid-template-columns:1fr}\n" | ||
| 107 | + " .pools{grid-template-columns:1fr}\n" | ||
| 108 | + " .models{grid-template-columns:1fr}\n" | ||
| 109 | + " .kv{grid-template-columns:1fr;gap:2px 0}\n" | ||
| 110 | + " .kv .k{margin-top:6px}\n" | ||
| 111 | + "}\n" | ||
| 112 | + "</style>\n" | ||
| 113 | + "</head>\n" | ||
| 114 | + "<body>\n" | ||
| 115 | + "<div id=\"app\">\n" | ||
| 116 | + " <div class=\"hd\">\n" | ||
| 117 | + " <div class=\"grow\">\n" | ||
| 118 | + " <h1>Google Quotas</h1>\n" | ||
| 119 | + " <div class=\"sub\" id=\"sub\">Antigravity account pools on this node</div>\n" | ||
| 120 | + " </div>\n" | ||
| 121 | + " <span class=\"pill off\" id=\"pill\"><span class=\"dot\"></span><span id=\"pillText\">Loading</span></span>\n" | ||
| 122 | + " <button id=\"themeToggle\" class=\"embed-hide\" type=\"button\">Theme</button>\n" | ||
| 123 | + " </div>\n" | ||
| 124 | + "\n" | ||
| 125 | + " <div class=\"kpis\">\n" | ||
| 126 | + " <div class=\"kpi\">\n" | ||
| 127 | + " <div class=\"lbl\">Active Account</div>\n" | ||
| 128 | + " <div class=\"val\" id=\"kpiSelected\">-</div>\n" | ||
| 129 | + " <div class=\"meta\" id=\"kpiSelectedMeta\">selected_account.txt</div>\n" | ||
| 130 | + " </div>\n" | ||
| 131 | + " <div class=\"kpi\">\n" | ||
| 132 | + " <div class=\"lbl\">Best Gemini</div>\n" | ||
| 133 | + " <div class=\"val\" id=\"kpiGemini\">-</div>\n" | ||
| 134 | + " <div class=\"meta\" id=\"kpiGeminiMeta\">Waiting for quota</div>\n" | ||
| 135 | + " </div>\n" | ||
| 136 | + " <div class=\"kpi\">\n" | ||
| 137 | + " <div class=\"lbl\">Best Claude</div>\n" | ||
| 138 | + " <div class=\"val\" id=\"kpiClaude\">-</div>\n" | ||
| 139 | + " <div class=\"meta\" id=\"kpiClaudeMeta\">Waiting for quota</div>\n" | ||
| 140 | + " </div>\n" | ||
| 141 | + " </div>\n" | ||
| 142 | + "\n" | ||
| 143 | + " <div class=\"bar-row\">\n" | ||
| 144 | + " <button class=\"btn\" id=\"btnRefresh\" type=\"button\">Refresh Quotas</button>\n" | ||
| 145 | + " <button class=\"btn ghost\" id=\"btnModels\" type=\"button\">Show Models</button>\n" | ||
| 146 | + " <span class=\"spacer\"></span>\n" | ||
| 147 | + " <span class=\"status-txt\" id=\"statusTxt\"></span>\n" | ||
| 148 | + " </div>\n" | ||
| 149 | + "\n" | ||
| 150 | + " <div class=\"note\" id=\"banner\"></div>\n" | ||
| 151 | + " <div id=\"accounts\"></div>\n" | ||
| 152 | + "\n" | ||
| 153 | + " <div class=\"card\">\n" | ||
| 154 | + " <h2>Node Paths</h2>\n" | ||
| 155 | + " <div class=\"kv\" id=\"paths\"></div>\n" | ||
| 156 | + " </div>\n" | ||
| 157 | + "</div>\n" | ||
| 158 | + "\n" | ||
| 159 | + "<div class=\"toast\" id=\"toast\"></div>\n" | ||
| 160 | + "\n" | ||
| 161 | + "<script>\n" | ||
| 162 | + "var q=new URLSearchParams(location.search);\n" | ||
| 163 | + "var node=q.get('node')||'';\n" | ||
| 164 | + "var sid=q.get('id')||'';\n" | ||
| 165 | + "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n" | ||
| 166 | + " localStorage.getItem('bot_active_pwd')||'';\n" | ||
| 167 | + "var HUB=q.get('plugin')||'';\n" | ||
| 168 | + "\n" | ||
| 169 | + "function url(action,extra){\n" | ||
| 170 | + " return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_google_quota')+\n" | ||
| 171 | + " '?action='+encodeURIComponent(action)+\n" | ||
| 172 | + " (extra?('&'+extra):'')+\n" | ||
| 173 | + " (node?'&node='+encodeURIComponent(node):'')+\n" | ||
| 174 | + " (sid?'&id='+encodeURIComponent(sid):'')+\n" | ||
| 175 | + " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n" | ||
| 176 | + "}\n" | ||
| 177 | + "function hdr(){\n" | ||
| 178 | + " var h={};\n" | ||
| 179 | + " if(pwd)h['X-Bot-Password']=pwd;\n" | ||
| 180 | + " return h;\n" | ||
| 181 | + "}\n" | ||
| 182 | + "function api(action,extra){\n" | ||
| 183 | + " return fetch(url(action,extra),{headers:hdr()}).then(function(r){\n" | ||
| 184 | + " return r.json().catch(function(){return {ok:false,error:'bad response'};});\n" | ||
| 185 | + " });\n" | ||
| 186 | + "}\n" | ||
| 187 | + "\n" | ||
| 188 | + "var $=function(id){return document.getElementById(id);};\n" | ||
| 189 | + "var state={selected:'',accounts:[],quotas:{},showModels:false,cliPresent:false,loading:false};\n" | ||
| 190 | + "\n" | ||
| 191 | + "function toast(msg){\n" | ||
| 192 | + " var t=$('toast');t.textContent=msg;t.classList.add('show');\n" | ||
| 193 | + " clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);\n" | ||
| 194 | + "}\n" | ||
| 195 | + "function setBanner(msg,kind){\n" | ||
| 196 | + " var el=$('banner');\n" | ||
| 197 | + " el.textContent=msg||'';\n" | ||
| 198 | + " el.className='note'+(msg?' show '+(kind||''):'');\n" | ||
| 199 | + "}\n" | ||
| 200 | + "function shortEmail(e){\n" | ||
| 201 | + " if(!e)return '-';\n" | ||
| 202 | + " var i=e.indexOf('@');\n" | ||
| 203 | + " return i>0?e.slice(0,i):e;\n" | ||
| 204 | + "}\n" | ||
| 205 | + "function pctClass(pct,exhausted){\n" | ||
| 206 | + " if(exhausted||pct===null||pct===undefined||pct<10)return 'bad';\n" | ||
| 207 | + " if(pct<50)return 'warn';\n" | ||
| 208 | + " return 'ok';\n" | ||
| 209 | + "}\n" | ||
| 210 | + "function fmtPct(pool){\n" | ||
| 211 | + " if(!pool)return '...';\n" | ||
| 212 | + " if(pool.exhausted||pool.pct===null||pool.pct===undefined)return 'EXHAUSTED';\n" | ||
| 213 | + " if(pool.pct<0)return 'N/A';\n" | ||
| 214 | + " return pool.pct.toFixed(1)+'%';\n" | ||
| 215 | + "}\n" | ||
| 216 | + "function fmtReset(iso){\n" | ||
| 217 | + " if(!iso)return 'Reset: -';\n" | ||
| 218 | + " var t=Date.parse(iso);\n" | ||
| 219 | + " if(isNaN(t))return 'Reset: '+iso;\n" | ||
| 220 | + " var diff=Math.floor((t-Date.now())/1000);\n" | ||
| 221 | + " if(diff<=0)return 'Resets soon';\n" | ||
| 222 | + " var d=Math.floor(diff/86400);\n" | ||
| 223 | + " var h=Math.floor((diff%86400)/3600);\n" | ||
| 224 | + " var m=Math.floor((diff%3600)/60);\n" | ||
| 225 | + " if(d>0)return 'Resets in '+d+'d '+h+'h';\n" | ||
| 226 | + " if(h>0)return 'Resets in '+h+'h '+m+'m';\n" | ||
| 227 | + " return 'Resets in '+Math.max(1,m)+'m';\n" | ||
| 228 | + "}\n" | ||
| 229 | + "function el(tag,cls,txt){\n" | ||
| 230 | + " var n=document.createElement(tag);\n" | ||
| 231 | + " if(cls)n.className=cls;\n" | ||
| 232 | + " if(txt!==undefined&&txt!==null)n.textContent=txt;\n" | ||
| 233 | + " return n;\n" | ||
| 234 | + "}\n" | ||
| 235 | + "\n" | ||
| 236 | + "function computeBest(){\n" | ||
| 237 | + " var bestG=null,bestGP=-1,bestC=null,bestCP=-1;\n" | ||
| 238 | + " state.accounts.forEach(function(a){\n" | ||
| 239 | + " var qd=state.quotas[a.email];\n" | ||
| 240 | + " if(!qd||!qd.ok)return;\n" | ||
| 241 | + " if(qd.gemini&&!qd.gemini.exhausted&&qd.gemini.pct>bestGP){\n" | ||
| 242 | + " bestGP=qd.gemini.pct;bestG=a.email;\n" | ||
| 243 | + " }\n" | ||
| 244 | + " if(qd.claude&&!qd.claude.exhausted&&qd.claude.pct>bestCP){\n" | ||
| 245 | + " bestCP=qd.claude.pct;bestC=a.email;\n" | ||
| 246 | + " }\n" | ||
| 247 | + " });\n" | ||
| 248 | + " return {gemini:bestG,geminiPct:bestGP,claude:bestC,claudePct:bestCP};\n" | ||
| 249 | + "}\n" | ||
| 250 | + "\n" | ||
| 251 | + "function renderPool(label,pool,loading){\n" | ||
| 252 | + " var box=el('div','pool');\n" | ||
| 253 | + " var hd=el('div','pool-hd');\n" | ||
| 254 | + " hd.appendChild(el('span','pool-name',label));\n" | ||
| 255 | + " var pctEl=el('span','pool-pct');\n" | ||
| 256 | + " var bar=el('div','meter');\n" | ||
| 257 | + " var fill=el('i');\n" | ||
| 258 | + " var rst=el('div','pool-reset');\n" | ||
| 259 | + "\n" | ||
| 260 | + " if(loading&&!pool){\n" | ||
| 261 | + " pctEl.className='pool-pct dim';\n" | ||
| 262 | + " pctEl.textContent='Checking...';\n" | ||
| 263 | + " fill.style.width='0%';\n" | ||
| 264 | + " rst.textContent='Querying quota CLI';\n" | ||
| 265 | + " }else if(!pool||pool.pct<0){\n" | ||
| 266 | + " pctEl.className='pool-pct dim';\n" | ||
| 267 | + " pctEl.textContent='N/A';\n" | ||
| 268 | + " fill.style.width='0%';\n" | ||
| 269 | + " rst.textContent='No buckets reported';\n" | ||
| 270 | + " }else{\n" | ||
| 271 | + " var cls=pctClass(pool.pct,pool.exhausted);\n" | ||
| 272 | + " pctEl.className='pool-pct '+cls;\n" | ||
| 273 | + " pctEl.textContent=fmtPct(pool);\n" | ||
| 274 | + " var w=pool.exhausted?0:Math.max(0,Math.min(100,pool.pct));\n" | ||
| 275 | + " fill.className=cls;\n" | ||
| 276 | + " fill.style.width=w.toFixed(1)+'%';\n" | ||
| 277 | + " rst.textContent=fmtReset(pool.reset_time);\n" | ||
| 278 | + " }\n" | ||
| 279 | + " hd.appendChild(pctEl);\n" | ||
| 280 | + " bar.appendChild(fill);\n" | ||
| 281 | + " box.appendChild(hd);\n" | ||
| 282 | + " box.appendChild(bar);\n" | ||
| 283 | + " box.appendChild(rst);\n" | ||
| 284 | + " return box;\n" | ||
| 285 | + "}\n" | ||
| 286 | + "\n" | ||
| 287 | + "function render(){\n" | ||
| 288 | + " var best=computeBest();\n" | ||
| 289 | + " $('kpiSelected').textContent=shortEmail(state.selected);\n" | ||
| 290 | + " $('kpiSelected').title=state.selected||'';\n" | ||
| 291 | + " $('kpiSelectedMeta').textContent=state.selected||'None selected';\n" | ||
| 292 | + "\n" | ||
| 293 | + " $('kpiGemini').textContent=best.gemini?shortEmail(best.gemini):'-';\n" | ||
| 294 | + " $('kpiGemini').title=best.gemini||'';\n" | ||
| 295 | + " $('kpiGeminiMeta').textContent=best.gemini?(best.geminiPct.toFixed(1)+'% remaining'):(state.loading?'Checking...':'No quota data');\n" | ||
| 296 | + "\n" | ||
| 297 | + " $('kpiClaude').textContent=best.claude?shortEmail(best.claude):'-';\n" | ||
| 298 | + " $('kpiClaude').title=best.claude||'';\n" | ||
| 299 | + " $('kpiClaudeMeta').textContent=best.claude?(best.claudePct.toFixed(1)+'% remaining'):(state.loading?'Checking...':'No quota data');\n" | ||
| 300 | + "\n" | ||
| 301 | + " var wrap=$('accounts');\n" | ||
| 302 | + " wrap.innerHTML='';\n" | ||
| 303 | + " if(!state.accounts.length){\n" | ||
| 304 | + " var empty=el('div','card empty','No accounts found in antigravity_accounts.json. Sign in with scorpiox-antigravity-login first.');\n" | ||
| 305 | + " wrap.appendChild(empty);\n" | ||
| 306 | + " return;\n" | ||
| 307 | + " }\n" | ||
| 308 | + "\n" | ||
| 309 | + " state.accounts.forEach(function(a){\n" | ||
| 310 | + " var isSel=(a.email===state.selected);\n" | ||
| 311 | + " var qd=state.quotas[a.email];\n" | ||
| 312 | + " var card=el('div','card'+(isSel?' selected':''));\n" | ||
| 313 | + "\n" | ||
| 314 | + " var top=el('div','acct-top');\n" | ||
| 315 | + " top.appendChild(el('div','acct-email',a.email));\n" | ||
| 316 | + "\n" | ||
| 317 | + " var badges=el('div','badges');\n" | ||
| 318 | + " if(isSel)badges.appendChild(el('span','tag sel','Selected'));\n" | ||
| 319 | + " if(best.gemini===a.email)badges.appendChild(el('span','tag best','Best Gemini'));\n" | ||
| 320 | + " if(best.claude===a.email)badges.appendChild(el('span','tag best','Best Claude'));\n" | ||
| 321 | + " if(!a.has_refresh)badges.appendChild(el('span','tag','No refresh token'));\n" | ||
| 322 | + " top.appendChild(badges);\n" | ||
| 323 | + "\n" | ||
| 324 | + " var sw=el('button','btn sm'+(isSel?' ghost':''),isSel?'Active':'Use');\n" | ||
| 325 | + " sw.type='button';\n" | ||
| 326 | + " sw.disabled=isSel;\n" | ||
| 327 | + " sw.onclick=function(){switchAccount(a.email,sw);};\n" | ||
| 328 | + " top.appendChild(sw);\n" | ||
| 329 | + " card.appendChild(top);\n" | ||
| 330 | + "\n" | ||
| 331 | + " if(qd&&!qd.ok){\n" | ||
| 332 | + " card.appendChild(el('div','err-msg','Error: '+(qd.detail||qd.error||'quota fetch failed')));\n" | ||
| 333 | + " }else{\n" | ||
| 334 | + " var pools=el('div','pools');\n" | ||
| 335 | + " pools.appendChild(renderPool('Gemini Pool',qd?qd.gemini:null,state.loading));\n" | ||
| 336 | + " pools.appendChild(renderPool('Claude Pool',qd?qd.claude:null,state.loading));\n" | ||
| 337 | + " card.appendChild(pools);\n" | ||
| 338 | + "\n" | ||
| 339 | + " if(qd&&qd.models&&qd.models.length){\n" | ||
| 340 | + " var mgrid=el('div','models'+(state.showModels?' show':''));\n" | ||
| 341 | + " qd.models.forEach(function(m){\n" | ||
| 342 | + " var row=el('div','mrow');\n" | ||
| 343 | + " row.appendChild(el('span','mid',m.id));\n" | ||
| 344 | + " var cls=pctClass(m.pct,m.exhausted);\n" | ||
| 345 | + " row.appendChild(el('span','mpct '+cls,m.exhausted?'EXH':(m.pct.toFixed(1)+'%')));\n" | ||
| 346 | + " mgrid.appendChild(row);\n" | ||
| 347 | + " });\n" | ||
| 348 | + " card.appendChild(mgrid);\n" | ||
| 349 | + " }\n" | ||
| 350 | + " }\n" | ||
| 351 | + " wrap.appendChild(card);\n" | ||
| 352 | + " });\n" | ||
| 353 | + "}\n" | ||
| 354 | + "\n" | ||
| 355 | + "function switchAccount(email,btn){\n" | ||
| 356 | + " btn.disabled=true;\n" | ||
| 357 | + " btn.textContent='Switching...';\n" | ||
| 358 | + " api('switch','account='+encodeURIComponent(email)).then(function(d){\n" | ||
| 359 | + " if(!d||!d.ok){\n" | ||
| 360 | + " toast((d&&(d.detail||d.error))||'Switch failed');\n" | ||
| 361 | + " render();\n" | ||
| 362 | + " return;\n" | ||
| 363 | + " }\n" | ||
| 364 | + " state.selected=d.selected||email;\n" | ||
| 365 | + " toast('Selected '+state.selected);\n" | ||
| 366 | + " render();\n" | ||
| 367 | + " }).catch(function(e){\n" | ||
| 368 | + " toast('Switch failed: '+e.message);\n" | ||
| 369 | + " render();\n" | ||
| 370 | + " });\n" | ||
| 371 | + "}\n" | ||
| 372 | + "\n" | ||
| 373 | + "function fetchQuotas(){\n" | ||
| 374 | + " if(!state.accounts.length||!state.cliPresent)return;\n" | ||
| 375 | + " state.loading=true;\n" | ||
| 376 | + " $('btnRefresh').disabled=true;\n" | ||
| 377 | + " $('btnRefresh').textContent='Refreshing...';\n" | ||
| 378 | + " $('statusTxt').textContent='Querying '+state.accounts.length+' account(s)...';\n" | ||
| 379 | + " render();\n" | ||
| 380 | + "\n" | ||
| 381 | + " var queue=state.accounts.slice();\n" | ||
| 382 | + " var done=0,total=queue.length;\n" | ||
| 383 | + " var workers=Math.min(4,total);\n" | ||
| 384 | + "\n" | ||
| 385 | + " function next(){\n" | ||
| 386 | + " if(!queue.length)return Promise.resolve();\n" | ||
| 387 | + " var acct=queue.shift();\n" | ||
| 388 | + " return api('quota','account='+encodeURIComponent(acct.email)).then(function(d){\n" | ||
| 389 | + " if(d&&d.ok&&d.account){\n" | ||
| 390 | + " state.quotas[acct.email]=d.account;\n" | ||
| 391 | + " }else{\n" | ||
| 392 | + " state.quotas[acct.email]={ok:false,error:(d&&d.error)||'failed',detail:d&&d.detail};\n" | ||
| 393 | + " }\n" | ||
| 394 | + " }).catch(function(e){\n" | ||
| 395 | + " state.quotas[acct.email]={ok:false,error:e.message};\n" | ||
| 396 | + " }).then(function(){\n" | ||
| 397 | + " done++;\n" | ||
| 398 | + " $('statusTxt').textContent='Loaded '+done+'/'+total;\n" | ||
| 399 | + " render();\n" | ||
| 400 | + " return next();\n" | ||
| 401 | + " });\n" | ||
| 402 | + " }\n" | ||
| 403 | + "\n" | ||
| 404 | + " var ps=[];\n" | ||
| 405 | + " for(var i=0;i<workers;i++)ps.push(next());\n" | ||
| 406 | + " Promise.all(ps).then(function(){\n" | ||
| 407 | + " state.loading=false;\n" | ||
| 408 | + " $('btnRefresh').disabled=false;\n" | ||
| 409 | + " $('btnRefresh').textContent='Refresh Quotas';\n" | ||
| 410 | + " $('statusTxt').textContent='Updated '+new Date().toLocaleTimeString();\n" | ||
| 411 | + " render();\n" | ||
| 412 | + " });\n" | ||
| 413 | + "}\n" | ||
| 414 | + "\n" | ||
| 415 | + "function load(){\n" | ||
| 416 | + " setBanner('');\n" | ||
| 417 | + " api('status').then(function(d){\n" | ||
| 418 | + " if(!d||!d.ok){\n" | ||
| 419 | + " setBanner((d&&(d.detail||d.error))||'Failed to read accounts','err');\n" | ||
| 420 | + " return;\n" | ||
| 421 | + " }\n" | ||
| 422 | + " state.selected=d.selected||'';\n" | ||
| 423 | + " state.accounts=d.accounts||[];\n" | ||
| 424 | + " state.cliPresent=!!d.cli_present;\n" | ||
| 425 | + "\n" | ||
| 426 | + " var pill=$('pill'),pt=$('pillText');\n" | ||
| 427 | + " if(!state.cliPresent){\n" | ||
| 428 | + " pill.className='pill bad';pt.textContent='CLI missing';\n" | ||
| 429 | + " setBanner('scorpiox-google-quota was not found on PATH. Install SCORPIOX CODE or set GOOGLE_QUOTA_BIN.','warn');\n" | ||
| 430 | + " }else if(!state.accounts.length){\n" | ||
| 431 | + " pill.className='pill warn';pt.textContent='0 accounts';\n" | ||
| 432 | + " }else{\n" | ||
| 433 | + " pill.className='pill ok';pt.textContent=state.accounts.length+' account'+(state.accounts.length===1?'':'s');\n" | ||
| 434 | + " }\n" | ||
| 435 | + "\n" | ||
| 436 | + " var paths=$('paths');\n" | ||
| 437 | + " paths.innerHTML='';\n" | ||
| 438 | + " [\n" | ||
| 439 | + " ['Accounts JSON',d.accounts_path||'-'],\n" | ||
| 440 | + " ['Selected file',d.selected_path||'-'],\n" | ||
| 441 | + " ['Quota CLI',d.cli_present?'found':'not found']\n" | ||
| 442 | + " ].forEach(function(r){\n" | ||
| 443 | + " paths.appendChild(el('div','k',r[0]));\n" | ||
| 444 | + " paths.appendChild(el('div','v',r[1]));\n" | ||
| 445 | + " });\n" | ||
| 446 | + "\n" | ||
| 447 | + " render();\n" | ||
| 448 | + " if(state.accounts.length&&state.cliPresent)fetchQuotas();\n" | ||
| 449 | + " }).catch(function(e){\n" | ||
| 450 | + " setBanner('Status failed: '+e.message,'err');\n" | ||
| 451 | + " });\n" | ||
| 452 | + "}\n" | ||
| 453 | + "\n" | ||
| 454 | + "$('btnRefresh').onclick=fetchQuotas;\n" | ||
| 455 | + "$('btnModels').onclick=function(){\n" | ||
| 456 | + " state.showModels=!state.showModels;\n" | ||
| 457 | + " $('btnModels').textContent=state.showModels?'Hide Models':'Show Models';\n" | ||
| 458 | + " render();\n" | ||
| 459 | + "};\n" | ||
| 460 | + "$('themeToggle').onclick=function(){\n" | ||
| 461 | + " if(window.sxApplyTheme&&window.sxTheme){\n" | ||
| 462 | + " window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');\n" | ||
| 463 | + " }\n" | ||
| 464 | + "};\n" | ||
| 465 | + "load();\n" | ||
| 466 | + "</script>\n" | ||
| 467 | + "\002</body></html>\n" | ||
| 468 | + ; | ||
| 469 | + | ||
| 470 | +#endif /* SX_GQUOTA_UI_HTML_H */ |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..1169c80 | index 0000000..1169c80 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/mock_quota.sh | +++ b/tests/mock_quota.sh | ||
| @@ -0,0 +1,68 @@ | @@ -0,0 +1,68 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# Deterministic mock for scorpiox-google-quota used by tests/run.sh. | ||
| 3 | +acct="" | ||
| 4 | +while [ $# -gt 0 ]; do | ||
| 5 | + case "$1" in | ||
| 6 | + --account) acct="$2"; shift 2 ;; | ||
| 7 | + --json) shift ;; | ||
| 8 | + *) shift ;; | ||
| 9 | + esac | ||
| 10 | +done | ||
| 11 | + | ||
| 12 | +# Verify the plugin sanitized inherited token/profile overrides. | ||
| 13 | +if [ -n "${GOOGLE_ACCESS_TOKEN:-}" ]; then | ||
| 14 | + echo "error: GOOGLE_ACCESS_TOKEN leaked into child env" >&2 | ||
| 15 | + exit 1 | ||
| 16 | +fi | ||
| 17 | +if [ "${GOOGLE_TOKEN_SOURCE:-}" != "local" ]; then | ||
| 18 | + echo "error: expected GOOGLE_TOKEN_SOURCE=local" >&2 | ||
| 19 | + exit 1 | ||
| 20 | +fi | ||
| 21 | + | ||
| 22 | +echo "INFO : ya29.MOCK-TOKEN-MUST-NOT-LEAK" >&2 | ||
| 23 | + | ||
| 24 | +case "$acct" in | ||
| 25 | + alpha@example.com) | ||
| 26 | + cat <<'EOF' | ||
| 27 | +{ | ||
| 28 | + "ok": true, | ||
| 29 | + "email": "alpha@example.com", | ||
| 30 | + "project": "proj-alpha", | ||
| 31 | + "endpoint": "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota", | ||
| 32 | + "buckets": [ | ||
| 33 | + {"tokenType": "WTUS", "modelId": "chat_20706", "remainingFraction": 1}, | ||
| 34 | + {"resetTime": "2026-11-25T06:00:00Z", "tokenType": "WTUS", "modelId": "claude-opus-4-6-thinking", "remainingFraction": 1}, | ||
| 35 | + {"resetTime": "2026-11-25T06:00:00Z", "tokenType": "WTUS", "modelId": "claude-sonnet-4-6", "remainingFraction": 1}, | ||
| 36 | + {"resetTime": "2026-11-25T03:00:00Z", "tokenType": "WTUS", "modelId": "gemini-3.8-flash-tiered", "remainingFraction": 0.855}, | ||
| 37 | + {"resetTime": "2026-11-25T03:00:00Z", "tokenType": "WTUS", "modelId": "gemini-4-hydrogen-sonar", "remainingFraction": 0.855}, | ||
| 38 | + {"tokenType": "WTUS", "modelId": "tab_flash_lite_preview", "remainingFraction": 1} | ||
| 39 | + ] | ||
| 40 | +} | ||
| 41 | +EOF | ||
| 42 | + exit 0 | ||
| 43 | + ;; | ||
| 44 | + beta@example.com) | ||
| 45 | + cat <<'EOF' | ||
| 46 | +{ | ||
| 47 | + "ok": true, | ||
| 48 | + "email": "beta@example.com", | ||
| 49 | + "project": "aicode-consumers", | ||
| 50 | + "endpoint": "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota", | ||
| 51 | + "buckets": [ | ||
| 52 | + {"resetTime": "2026-11-25T08:00:00Z", "tokenType": "WTUS", "modelId": "claude-sonnet-4-6", "remainingFraction": 0.42}, | ||
| 53 | + {"resetTime": "2026-11-25T04:00:00Z", "tokenType": "WTUS", "modelId": "gemini-3.8-flash-tiered", "remainingFraction": null}, | ||
| 54 | + {"resetTime": "2026-11-25T04:00:00Z", "tokenType": "WTUS", "modelId": "gemini-4-hydrogen-sonar"} | ||
| 55 | + ] | ||
| 56 | +} | ||
| 57 | +EOF | ||
| 58 | + exit 0 | ||
| 59 | + ;; | ||
| 60 | + broken@example.com) | ||
| 61 | + echo "error: invalid_grant" >&2 | ||
| 62 | + exit 1 | ||
| 63 | + ;; | ||
| 64 | + *) | ||
| 65 | + echo "error: unknown mock account $acct" >&2 | ||
| 66 | + exit 1 | ||
| 67 | + ;; | ||
| 68 | +esac |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..6de407f | index 0000000..6de407f | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,268 @@ | @@ -0,0 +1,268 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh - offline checks for plugin_google_quota across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Runs against ./plugin_google_quota with credential paths and the quota CLI | ||
| 5 | +# redirected at throwaway fixtures, proving the contract without network access. | ||
| 6 | + | ||
| 7 | +set -u | ||
| 8 | + | ||
| 9 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | ||
| 10 | +cd "$ROOT" || exit 1 | ||
| 11 | + | ||
| 12 | +BIN=./plugin_google_quota | ||
| 13 | +PASS=0 | ||
| 14 | +FAIL=0 | ||
| 15 | + | ||
| 16 | +if [ -t 1 ]; then | ||
| 17 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 18 | +else | ||
| 19 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 20 | +fi | ||
| 21 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 22 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 23 | + | ||
| 24 | +check() { | ||
| 25 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 26 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | ||
| 27 | + fi | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +check_not() { | ||
| 31 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 32 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | ||
| 33 | + fi | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 37 | + | ||
| 38 | +body() { | ||
| 39 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | ||
| 40 | + BEGIN { inhdr = 0 } | ||
| 41 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options):/) { inhdr = 1; next } | ||
| 42 | + inhdr && $0 == "" { inhdr = 0; next } | ||
| 43 | + inhdr { next } | ||
| 44 | + { print } | ||
| 45 | + ' | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +json_ok() { | ||
| 49 | + expr=${3:-True} | ||
| 50 | + if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then | ||
| 51 | + pass "$1" | ||
| 52 | + else | ||
| 53 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | ||
| 54 | + fi | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +api() { body "$(QUERY_STRING="$1" $BIN)"; } | ||
| 58 | +apiraw() { QUERY_STRING="$1" $BIN; } | ||
| 59 | + | ||
| 60 | +# ---------------------------------------------------------------- build | ||
| 61 | +section "build" | ||
| 62 | +if [ ! -x "$BIN" ]; then | ||
| 63 | + gcc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -Wno-format-truncation -I src -o "$BIN" src/plugin_google_quota.c || { | ||
| 64 | + fail "native build"; exit 1; } | ||
| 65 | +fi | ||
| 66 | +pass "native binary present" | ||
| 67 | + | ||
| 68 | +if python3 tools/gen_ui.py --check >/dev/null 2>&1; then | ||
| 69 | + pass "src/ui_html.h is in sync with src/ui.html" | ||
| 70 | +else | ||
| 71 | + fail "src/ui_html.h is stale - run tools/gen_ui.py" | ||
| 72 | +fi | ||
| 73 | + | ||
| 74 | +check "ui header is marked generated" "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)" | ||
| 75 | + | ||
| 76 | +# ---------------------------------------------------------------- fixtures | ||
| 77 | +FIX=$(mktemp -d 2>/dev/null || mktemp -d -t gqfix) | ||
| 78 | +trap 'rm -rf "$FIX"' EXIT | ||
| 79 | + | ||
| 80 | +mkdir -p "$FIX/none" "$FIX/empty" "$FIX/full" | ||
| 81 | +chmod +x "$ROOT/tests/mock_quota.sh" | ||
| 82 | +export GOOGLE_QUOTA_BIN="$ROOT/tests/mock_quota.sh" | ||
| 83 | +export GOOGLE_ACCESS_TOKEN="ya29.INHERITED-TOKEN-MUST-BE-CLEARED" | ||
| 84 | + | ||
| 85 | +: > "$FIX/empty/antigravity_accounts.json" | ||
| 86 | + | ||
| 87 | +cat > "$FIX/full/antigravity_accounts.json" <<'EOF' | ||
| 88 | +[ | ||
| 89 | + {"email": "alpha@example.com", "refresh_token": "1//MOCK-REFRESH-TOKEN-MUST-NOT-LEAK-A"}, | ||
| 90 | + {"email": "beta@example.com", "refresh_token": "1//MOCK-REFRESH-TOKEN-MUST-NOT-LEAK-B"}, | ||
| 91 | + {"email": "broken@example.com", "refresh_token": "1//MOCK-REFRESH-TOKEN-MUST-NOT-LEAK-C"} | ||
| 92 | +] | ||
| 93 | +EOF | ||
| 94 | +printf 'beta@example.com\n' > "$FIX/full/selected_account.txt" | ||
| 95 | + | ||
| 96 | +# ---------------------------------------------------------------- meta & auth | ||
| 97 | +section "meta & auth" | ||
| 98 | +META=$(BOT_PASSWORD=secret-pass $BIN --meta) | ||
| 99 | +check "--meta returns short name and desc without auth" '{"name":"google quota","desc":"Account quotas"}' "$META" | ||
| 100 | + | ||
| 101 | +META_ENV=$(BOT_PASSWORD=secret-pass SX_PLUGIN_META=1 $BIN) | ||
| 102 | +check "SX_PLUGIN_META=1 works without auth" '{"name":"google quota","desc":"Account quotas"}' "$META_ENV" | ||
| 103 | + | ||
| 104 | +VER=$($BIN --version) | ||
| 105 | +check "--version prints plugin id and version" "plugin_google_quota 1.0.0" "$VER" | ||
| 106 | + | ||
| 107 | +UNAUTH=$(BOT_PASSWORD=secret-pass QUERY_STRING="action=status" $BIN) | ||
| 108 | +check "missing password returns 401" "Status: 401 Unauthorized" "$UNAUTH" | ||
| 109 | + | ||
| 110 | +AUTH_HDR=$(BOT_PASSWORD=secret-pass HTTP_X_BOT_PASSWORD=secret-pass GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status") | ||
| 111 | +json_ok "X-Bot-Password header authorizes request" "$AUTH_HDR" "d['ok'] is True" | ||
| 112 | + | ||
| 113 | +AUTH_BEARER=$(BOT_PASSWORD=secret-pass HTTP_AUTHORIZATION="Bearer secret-pass" GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status") | ||
| 114 | +json_ok "Bearer header authorizes request" "$AUTH_BEARER" "d['ok'] is True" | ||
| 115 | + | ||
| 116 | +AUTH_QS=$(BOT_PASSWORD=secret-pass GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status&pwd=secret-pass") | ||
| 117 | +json_ok "?pwd= query param authorizes request" "$AUTH_QS" "d['ok'] is True" | ||
| 118 | + | ||
| 119 | +# ---------------------------------------------------------------- status | ||
| 120 | +section "status" | ||
| 121 | +ST_NONE=$(GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status") | ||
| 122 | +json_ok "missing accounts file returns count 0" "$ST_NONE" "d['ok'] is True and d['count'] == 0 and d['cli_present'] is True" | ||
| 123 | + | ||
| 124 | +ST_EMPTY=$(GOOGLE_ACCOUNTS_FILE="$FIX/empty/antigravity_accounts.json" api "action=status") | ||
| 125 | +json_ok "empty accounts file returns count 0" "$ST_EMPTY" "d['ok'] is True and d['count'] == 0" | ||
| 126 | + | ||
| 127 | +ST_FULL=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=status") | ||
| 128 | +json_ok "full accounts status lists 3 accounts and selected" "$ST_FULL" \ | ||
| 129 | + "d['ok'] is True and d['count'] == 3 and d['selected'] == 'beta@example.com' and d['accounts'][1]['selected'] is True and all(a['has_refresh'] for a in d['accounts'])" | ||
| 130 | +check_not "status never leaks refresh_token" "MOCK-REFRESH-TOKEN" "$ST_FULL" | ||
| 131 | + | ||
| 132 | +ST_NOCLI=$(GOOGLE_QUOTA_BIN="/nonexistent/scorpiox-google-quota" GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=status") | ||
| 133 | +json_ok "missing CLI sets cli_present false" "$ST_NOCLI" "d['ok'] is True and d['cli_present'] is False" | ||
| 134 | + | ||
| 135 | +# ---------------------------------------------------------------- quota | ||
| 136 | +section "quota" | ||
| 137 | +Q_ONE=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota&account=alpha@example.com") | ||
| 138 | +json_ok "single account quota parses gemini and claude pools" "$Q_ONE" \ | ||
| 139 | + "d['ok'] is True and d['account']['ok'] is True and abs(d['account']['gemini']['pct'] - 85.5) < 0.01 and abs(d['account']['claude']['pct'] - 100.0) < 0.01 and len(d['account']['models']) == 4" | ||
| 140 | +check_not "single quota never leaks token" "MOCK-TOKEN" "$Q_ONE" | ||
| 141 | +check_not "single quota never leaks refresh token" "MOCK-REFRESH-TOKEN" "$Q_ONE" | ||
| 142 | + | ||
| 143 | +Q_EXH=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota&account=beta@example.com") | ||
| 144 | +json_ok "null/missing remainingFraction marks gemini pool exhausted" "$Q_EXH" \ | ||
| 145 | + "d['ok'] is True and d['account']['gemini']['exhausted'] is True and d['account']['gemini']['pct'] == 0.0 and abs(d['account']['claude']['pct'] - 42.0) < 0.01" | ||
| 146 | + | ||
| 147 | +Q_ALL=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota") | ||
| 148 | +json_ok "all-accounts quota aggregates best_gemini, best_claude, and broken account" "$Q_ALL" \ | ||
| 149 | + "d['ok'] is True and d['count'] == 3 and d['best_gemini'] == 'alpha@example.com' and d['best_claude'] == 'alpha@example.com' and d['accounts'][2]['ok'] is False" | ||
| 150 | +check_not "all-accounts quota never leaks token" "MOCK-TOKEN" "$Q_ALL" | ||
| 151 | + | ||
| 152 | +Q_FMT=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "format=json") | ||
| 153 | +json_ok "?format=json returns full quota JSON" "$Q_FMT" "d['ok'] is True and d['count'] == 3 and 'best_gemini' in d" | ||
| 154 | + | ||
| 155 | +Q_UNK=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" apiraw "action=quota&account=nobody@example.com") | ||
| 156 | +check "unknown account returns 404" "Status: 404 Not Found" "$Q_UNK" | ||
| 157 | + | ||
| 158 | +Q_NOCLI=$(GOOGLE_QUOTA_BIN="/nonexistent/scorpiox-google-quota" GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota") | ||
| 159 | +json_ok "missing CLI returns cli_unavailable" "$Q_NOCLI" "d['ok'] is False and d['error'] == 'cli_unavailable'" | ||
| 160 | + | ||
| 161 | +# ---------------------------------------------------------------- switch | ||
| 162 | +section "switch" | ||
| 163 | +SW_OK=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=switch&account=alpha@example.com") | ||
| 164 | +json_ok "switch updates selected account" "$SW_OK" "d['ok'] is True and d['selected'] == 'alpha@example.com'" | ||
| 165 | +check "selected_account.txt persisted" "alpha@example.com" "$(cat "$FIX/full/selected_account.txt")" | ||
| 166 | + | ||
| 167 | +printf '{"account":"beta@example.com"}' > "$FIX/post.json" | ||
| 168 | +SW_PBF=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" POST_BODY_FILE="$FIX/post.json" api "action=switch") | ||
| 169 | +json_ok "switch accepts POST_BODY_FILE JSON" "$SW_PBF" "d['ok'] is True and d['selected'] == 'beta@example.com'" | ||
| 170 | + | ||
| 171 | +SW_BAD=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" apiraw "action=switch&account=bad;rm") | ||
| 172 | +check "invalid email rejected with 400" "Status: 400 Bad Request" "$SW_BAD" | ||
| 173 | + | ||
| 174 | +SW_UNK=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" apiraw "action=switch&account=nobody@example.com") | ||
| 175 | +check "unknown email rejected with 404" "Status: 404 Not Found" "$SW_UNK" | ||
| 176 | + | ||
| 177 | +# ---------------------------------------------------------------- HTML UI | ||
| 178 | +section "HTML UI" | ||
| 179 | +HTML=$(apiraw "") | ||
| 180 | +check "HTML emits Content-Type text/html" "Content-Type: text/html" "$HTML" | ||
| 181 | +check "HTML includes bot theme prepaint" "bot_theme" "$HTML" | ||
| 182 | +check "HTML includes theme handoff" "sx-theme-request" "$HTML" | ||
| 183 | +check "HTML uses two-route API helper" "plugin_google_quota" "$HTML" | ||
| 184 | +check "HTML hides theme toggle in embed mode" "embed-hide" "$HTML" | ||
| 185 | +check_not "HTML loads no CDN script" "<script src=" "$HTML" | ||
| 186 | +check_not "HTML references no external host script" "cdnjs" "$HTML" | ||
| 187 | +check_not "HTML makes no outbound fetch to googleapis" "googleapis.com" "$HTML" | ||
| 188 | + | ||
| 189 | +printf '%s' "$HTML" > "$FIX/page.html" | ||
| 190 | +if python3 - "$FIX/page.html" <<'PY' | ||
| 191 | +import re, sys | ||
| 192 | +html = open(sys.argv[1], encoding='utf-8').read() | ||
| 193 | +ids = set(re.findall(r'id="([^"]+)"', html)) | ||
| 194 | +missing = [i for i in re.findall(r"\$\('([^']+)'\)", html) if i not in ids] | ||
| 195 | +if missing: | ||
| 196 | + print("missing ids:", missing) | ||
| 197 | + sys.exit(1) | ||
| 198 | +PY | ||
| 199 | +then pass "every JS element id exists in the markup" | ||
| 200 | +else fail "JS references missing element id"; fi | ||
| 201 | + | ||
| 202 | +# ---------------------------------------------------------------- source hygiene | ||
| 203 | +section "source hygiene" | ||
| 204 | +check_not "source has no OAuth client secret" "GOCSPX" "$(cat src/plugin_google_quota.c)" | ||
| 205 | +check_not "source has no Google API key" "AIza" "$(cat src/plugin_google_quota.c)" | ||
| 206 | +check_not "source has no GitHub token" "ghp_" "$(cat src/plugin_google_quota.c)" | ||
| 207 | +check_not "source has no internal 192.168 address" "192.168." "$(cat src/plugin_google_quota.c src/ui.html)" | ||
| 208 | +check_not "source has no internal 10.0 address" "10.0." "$(cat src/plugin_google_quota.c src/ui.html)" | ||
| 209 | +check_not "source has no internal 172.16 address" "172.16" "$(cat src/plugin_google_quota.c src/ui.html)" | ||
| 210 | + | ||
| 211 | +if python3 - src/plugin_google_quota.c src/ui.html src/bot_theme_plugin.h <<'PY' | ||
| 212 | +import sys, unicodedata | ||
| 213 | +bad = [] | ||
| 214 | +for path in sys.argv[1:]: | ||
| 215 | + for n, line in enumerate(open(path, encoding='utf-8'), 1): | ||
| 216 | + for ch in line: | ||
| 217 | + o = ord(ch) | ||
| 218 | + if o < 0x2000: | ||
| 219 | + continue | ||
| 220 | + if 0x2190 <= o <= 0x21FF: | ||
| 221 | + continue | ||
| 222 | + if unicodedata.category(ch) in ('So', 'Sk') or 0x1F000 <= o <= 0x1FAFF: | ||
| 223 | + bad.append('%s:%d %r' % (path, n, ch)) | ||
| 224 | +if bad: | ||
| 225 | + print('\n'.join(bad[:10])) | ||
| 226 | + sys.exit(1) | ||
| 227 | +PY | ||
| 228 | +then pass "no emoji in source, page or theme header" | ||
| 229 | +else fail "emoji found in shipped sources"; fi | ||
| 230 | + | ||
| 231 | +# ---------------------------------------------------------------- cross-target builds | ||
| 232 | +section "cross-target builds" | ||
| 233 | +if command -v musl-gcc >/dev/null 2>&1; then | ||
| 234 | + if musl-gcc -O2 -std=c99 -static -I src -o "$FIX/musl-bin" src/plugin_google_quota.c 2>/dev/null; then | ||
| 235 | + pass "static musl build" | ||
| 236 | + check "musl binary reports --meta" '"name":"google quota"' "$("$FIX/musl-bin" --meta)" | ||
| 237 | + else fail "static musl build"; fi | ||
| 238 | +else | ||
| 239 | + echo " skip musl-gcc not installed" | ||
| 240 | +fi | ||
| 241 | + | ||
| 242 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | ||
| 243 | + if x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -o "$FIX/win-bin.exe" src/plugin_google_quota.c 2>/dev/null; then | ||
| 244 | + pass "MinGW-w64 build" | ||
| 245 | + if [ "$(head -c 2 "$FIX/win-bin.exe")" = "MZ" ]; then | ||
| 246 | + pass "Windows build has PE header" | ||
| 247 | + else fail "Windows build missing MZ header"; fi | ||
| 248 | + else fail "MinGW-w64 build"; fi | ||
| 249 | +else | ||
| 250 | + echo " skip x86_64-w64-mingw32-gcc not installed" | ||
| 251 | +fi | ||
| 252 | + | ||
| 253 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | ||
| 254 | + if aarch64-linux-gnu-gcc -O2 -std=c99 -static -I src -o "$FIX/arm-bin" src/plugin_google_quota.c 2>/dev/null; then | ||
| 255 | + pass "static arm64 build" | ||
| 256 | + else fail "static arm64 build"; fi | ||
| 257 | +else | ||
| 258 | + echo " skip aarch64-linux-gnu-gcc not installed" | ||
| 259 | +fi | ||
| 260 | + | ||
| 261 | +if gcc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$FIX/fortify-bin" src/plugin_google_quota.c 2>/dev/null; then | ||
| 262 | + pass "_FORTIFY_SOURCE=2 build" | ||
| 263 | +else | ||
| 264 | + fail "_FORTIFY_SOURCE=2 build" | ||
| 265 | +fi | ||
| 266 | + | ||
| 267 | +printf '\n%sSummary:%s %d passed, %d failed\n' "$C_B" "$C_0" "$PASS" "$FAIL" | ||
| 268 | +[ "$FAIL" -eq 0 ] |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..ab1822e | index 0000000..ab1822e | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tools/gen_ui.py | +++ b/tools/gen_ui.py | ||
| @@ -0,0 +1,105 @@ | @@ -0,0 +1,105 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tools/gen_ui.py - compile src/ui.html into src/ui_html.h. | ||
| 3 | + | ||
| 4 | +The page lives in one readable file (src/ui.html) so it can be diffed and | ||
| 5 | +reviewed like any other source. This script turns it into a single C string | ||
| 6 | +constant with two control-character placeholders: | ||
| 7 | + | ||
| 8 | + 0x01 -> the bot theme prepaint script + <style> + theme tokens | ||
| 9 | + 0x02 -> the bot theme handoff script (just before </body>) | ||
| 10 | + | ||
| 11 | +main() splits the constant on those bytes and emits the macros from | ||
| 12 | +src/bot_theme_plugin.h in their place, so the theme can never drift out of | ||
| 13 | +sync with the rest of the bot. | ||
| 14 | + | ||
| 15 | + python3 tools/gen_ui.py # write src/ui_html.h | ||
| 16 | + python3 tools/gen_ui.py --check # exit 1 when the header is stale | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +import os | ||
| 20 | +import sys | ||
| 21 | + | ||
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 23 | +SRC = os.path.join(ROOT, "src", "ui.html") | ||
| 24 | +OUT = os.path.join(ROOT, "src", "ui_html.h") | ||
| 25 | + | ||
| 26 | +TOKENS = "<!--TOKENS-->" | ||
| 27 | +MARK_TOKENS = "\u0001" | ||
| 28 | +MARK_HANDOFF = "\u0002" | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def c_literal(text): | ||
| 32 | + """Escape text for a C string literal, one line per source line.""" | ||
| 33 | + out = [] | ||
| 34 | + for line in text.splitlines(True): | ||
| 35 | + piece = [] | ||
| 36 | + for ch in line: | ||
| 37 | + if ch == "\\": | ||
| 38 | + piece.append("\\\\") | ||
| 39 | + elif ch == '"': | ||
| 40 | + piece.append('\\"') | ||
| 41 | + elif ch == "\n": | ||
| 42 | + piece.append("\\n") | ||
| 43 | + elif ch == "\r": | ||
| 44 | + piece.append("\\r") | ||
| 45 | + elif ch == "\t": | ||
| 46 | + piece.append("\\t") | ||
| 47 | + elif MARK_TOKENS: | ||
| 48 | + if ch == MARK_TOKENS: | ||
| 49 | + piece.append("\\001") | ||
| 50 | + elif ch == MARK_HANDOFF: | ||
| 51 | + piece.append("\\002") | ||
| 52 | + elif ord(ch) < 0x20: | ||
| 53 | + piece.append("\\%03o" % ord(ch)) | ||
| 54 | + else: | ||
| 55 | + piece.append(ch) | ||
| 56 | + out.append(' "%s"\n' % "".join(piece)) | ||
| 57 | + return "".join(out) | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def render(): | ||
| 61 | + with open(SRC, "r", encoding="utf-8") as f: | ||
| 62 | + html = f.read() | ||
| 63 | + | ||
| 64 | + if TOKENS not in html: | ||
| 65 | + raise SystemExit("src/ui.html has no %s placeholder" % TOKENS) | ||
| 66 | + html = html.replace(TOKENS, MARK_TOKENS) | ||
| 67 | + | ||
| 68 | + if "</body>" not in html: | ||
| 69 | + raise SystemExit("src/ui.html has no </body>") | ||
| 70 | + html = html.replace("</body>", MARK_HANDOFF + "</body>", 1) | ||
| 71 | + | ||
| 72 | + header = ( | ||
| 73 | + "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n" | ||
| 74 | + "#ifndef SX_GQUOTA_UI_HTML_H\n" | ||
| 75 | + "#define SX_GQUOTA_UI_HTML_H\n" | ||
| 76 | + "\n" | ||
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | ||
| 78 | + "\n" | ||
| 79 | + "#endif /* SX_GQUOTA_UI_HTML_H */\n" | ||
| 80 | + ) | ||
| 81 | + return header | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def main(): | ||
| 85 | + header = render() | ||
| 86 | + check = "--check" in sys.argv[1:] | ||
| 87 | + if check: | ||
| 88 | + try: | ||
| 89 | + with open(OUT, "r", encoding="utf-8") as f: | ||
| 90 | + cur = f.read() | ||
| 91 | + except OSError: | ||
| 92 | + cur = "" | ||
| 93 | + if cur != header: | ||
| 94 | + sys.stderr.write("src/ui_html.h is stale - run tools/gen_ui.py\n") | ||
| 95 | + return 1 | ||
| 96 | + print("src/ui_html.h is up to date") | ||
| 97 | + return 0 | ||
| 98 | + with open(OUT, "w", encoding="utf-8") as f: | ||
| 99 | + f.write(header) | ||
| 100 | + print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header))) | ||
| 101 | + return 0 | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +if __name__ == "__main__": | ||
| 105 | + sys.exit(main()) | ||
| 0 | 106 |