Files
plugins/packages/agy-cli/usage.mjs
T
yetone b40a853c20 agy-cli 0.1.34: agy isn't run in the background without a sign-in, so it stops opening the browser (JZGiVvkSOA75376 on X)
On Windows 11, a signed-out agy opened Google's sign-in page 235 times
in one day. The usage refresh ran `agy` about every 3 minutes, and agy
opens the browser through ShellExecuteW, so the BROWSER=open.cmd guard
can't stop it.

New signin.mjs reads agy's stored sign-in without running agy. agy keeps
it through go-keyring, service "gemini" and user "antigravity":
- macOS: `security find-generic-password`;
- Windows: CredReadW from PowerShell, on the credential
  "gemini:antigravity".
It reads only whether a sign-in is stored, whether it has a refresh
token, and when the access token ends. The token itself never leaves
the function; a hash tells one sign-in from the next. Setting
GEMINI_API_KEY, GOOGLE_API_KEY, AGY_ADC_AUTH or GOOGLE_GENAI_USE_VERTEXAI
means agy signs in some other way, so nothing is concluded from the
keyring. AGY_BRIDGE_STORED_SIGNIN=skip turns the read off.

An access token that has ended is not "needs sign-in". The owner's
working agy has one that ended 11 hours ago and is renewed from its
refresh token. agy counts as unable to sign in when:
- no sign-in is stored;
- the access token has ended and there is no refresh token;
- or agy already failed on this stored sign-in: it said it needs a
  sign-in, or it hung with an ended token and printed nothing or
  sign-in talk, the way an agy waiting on its browser does. This holds
  until another sign-in is stored.

What changes:
- Usage: in those cases agy isn't run. The read says signIn "expired",
  and magpie shows the account's sign-in as expired. After the next good
  read it says "renewed", and magpie clears that.
- Other usage failures wait 10 minutes before the next run, doubling up
  to 6 hours. Before, they ran again on every refresh.
- The model listing (`agy models`) isn't run in the background in those
  cases either. The catalog it has stays.
- Signing in from magpie skips the `agy models` probe and goes straight
  to magpie's own sign-in link. A finished sign-in clears what was
  marked dead.
- A request answers 401 with X-Magpie-Sign-In: expired when no sign-in
  is stored. This uses the last read, so a request never waits for
  PowerShell.
- `agy --version` hanging is never read as a sign-in wait.

Run:
- mote, rebased on a02d5912: `bun scripts/check.mjs` ok and
  `bun test` in packages/agy-cli (20 pass, 0 fail).
- mote, root `HOME=<temp> bun test` at the pre-rebase head (e90d6f01
  base): 7588 pass, 427 fail, none in agy-cli. The reds named in the
  kept tail are OAuth callback-port and loopback page-service tests
  (mote at load ~35-40); main's own CI test job passes them, so this
  push's CI test job is the record for the whole suite.
- win-run on xiaomi-gpu: test/signin.mjs and test/usage.mjs (21 pass,
  3 skip on Windows), plus the PowerShell script for real. Over SSH,
  CredReadW answers 1312 (no logon session), which the script turns into
  "unknown". So the struct read was tried on a CREDENTIALW built in
  memory with a UTF-8 blob: the bytes round-trip and the sign-in parses.
Broken by hand:
- with the usage gate, the backoff hold and the dead mark removed, 5
  usage tests go red;
- with listAgyModels' gate and the request gate removed, the new catalog
  test goes red;
- with the request gate alone removed, it goes red too.
Not tried:
- a real signed-out agy, by the rule against running a real agy sign-in
  or a browser;
- CredReadW in an interactive Windows session (none was logged on);
- agy on Windows at all (xiaomi-gpu has no agy).
On Linux the keyring isn't read ("unknown"): agy runs as before, with
the backoff, and the xdg-open shim already stops the browser there.
2026-11-13 13:45:25 +08:00

360 lines
16 KiB
JavaScript

import { spawn } from "node:child_process"
import fs from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { agySpawnSpec, childEnv as agyChildEnv } from "./platform.mjs"
import { cannotSignIn, isDead, noteDead, storedSignIn } from "./signin.mjs"
const DEFAULT_TIMEOUT_MS = 15_000
const MAX_TIMEOUT_MS = 18_000 // Magpie bounds an auth.usage call to 20 seconds.
const MAX_OUTPUT_BYTES = 1024 * 1024
// kind: "auth" (agy says it needs a sign-in), "timeout" (output: what agy
// had printed by then, never shown), "cancel", or none.
class UsageError extends Error {
constructor(message, { kind = "", output = "" } = {}) {
super(message)
this.kind = kind
this.output = output
}
}
// What agy prints when it starts its own Google sign-in.
const SIGN_IN_TALK = /accounts\.google\.com|oauth|sign[ -]?in|log[ -]?in|authenticat|browser/i
const text = value => typeof value === "string" ? value.trim() : ""
const field = (value, camel, snake) => value?.[camel] ?? value?.[snake]
function commandFailure(output) {
if (/not (?:logged|signed) in|unauthenticated|authentication required|login required|please (?:log|sign) in|sign in again/i.test(output)) {
return new UsageError("agy usage needs authentication. Run `agy` in a terminal to sign in again.", { kind: "auth" })
}
const eligibility = /eligibility check failed|not eligible|unsupported (?:country|region)|does not support google tos/i.test(output)
const network = /\b(?:eof|timeout|timed out|deadline exceeded|no such host|connection (?:refused|reset)|network|proxy|tls|ssl|certificate)\b/i.test(output)
if (network) return new UsageError(`agy usage ${eligibility ? "eligibility check " : ""}failed on a network request. Check network or proxy settings.`)
if (eligibility) return new UsageError("agy reports that this account is not eligible for Antigravity.")
return new UsageError("agy could not read usage. Run `agy` in a terminal to check its status.")
}
function resetTime(value) {
if (value == null || value === "" || typeof value === "boolean") return undefined
const raw = String(value)
let ms
if (/^\d+(?:\.\d+)?$/.test(raw)) ms = Number(raw) * (Number(raw) < 1e11 ? 1000 : 1)
else if (/^\d{4}-\d{2}-\d{2}T/.test(raw)) ms = Date.parse(raw)
if (!Number.isFinite(ms) || ms <= 0 || ms > 253402300799999) return undefined
return new Date(ms).toISOString()
}
function cadence(bucket, id, name) {
// An explicit, unfamiliar window must not be overridden by an older ID/label.
const value = text(bucket.window) || `${id} ${name}`
if (/^(?:5h|five[_ -]?hours?|five_hour|session)$/i.test(value) || !text(bucket.window) && /(?:5h|five[ _-]hour|session)/i.test(value)) {
return { name: "5 hours", span: 5 * 60 * 60 }
}
if (/^(?:weekly|week|7d|seven[_ -]?days?)$/i.test(value) || !text(bucket.window) && /(?:weekly|week|7d)/i.test(value)) {
return { name: "7 days", span: 7 * 24 * 60 * 60 }
}
return { name: name || id }
}
// agy's command report is not its token-usage object or a model-availability list.
// Unknown quota is not evidence of exhaustion or a full allowance.
export function parseUsageReport(value) {
let report
try { report = typeof value === "string" ? JSON.parse(value) : value } catch {
throw new UsageError("agy returned an invalid usage report.")
}
if (report?.status !== "SUCCESS" || report?.command?.name !== "usage") {
throw commandFailure(`${text(report?.error)} ${text(report?.response)}`)
}
const groups = report.command.data?.groups
const windows = []
for (const group of Array.isArray(groups) ? groups : []) {
const pool = (text(field(group, "displayName", "display_name")) || text(group?.name) || "Quota")
.replace(/\s+models$/i, "").replace(/\s+and\s+/gi, " & ")
for (const bucket of Array.isArray(group?.buckets) ? group.buckets : []) {
const id = text(field(bucket, "bucketId", "bucket_id")) || text(bucket?.id)
if (!id || bucket?.disabled === true) continue
const label = text(field(bucket, "displayName", "display_name")) || text(bucket?.name)
const period = cadence(bucket, id, label)
const remaining = bucket.remaining
const fraction = field(bucket, "remainingFraction", "remaining_fraction")
?? field(remaining, "remainingFraction", "remaining_fraction")
?? (remaining?.case === "remainingFraction" ? remaining.value : undefined)
const known = typeof fraction === "number" && Number.isFinite(fraction) && fraction >= 0 && fraction <= 1
const resetsAt = resetTime(field(bucket, "resetTime", "reset_time"))
windows.push({
name: `${pool} · ${period.name}`,
// This feature displays quota only; it must not change model routing.
aside: true,
...(known ? { used: Math.round((1 - fraction) * 1e8) / 1e6 } : { display: "Limits not available" }),
...(period.span ? { span: period.span } : {}),
...(resetsAt ? { resetsAt } : {}),
})
}
}
if (!windows.some(w => w.used !== undefined)) {
throw new UsageError("Limits not available: agy returned no enabled, measured quota buckets.")
}
// /usage has no verified account or plan identity. Do not borrow one elsewhere.
return { windows }
}
function timeout(value) {
const n = Number(value)
return Number.isFinite(n) && n > 0 ? Math.min(n, MAX_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS
}
function run(file, args, { cwd, env, deadline, signal, maxOutputBytes, onTreeKill }) {
return new Promise((resolve, reject) => {
let child
let settled = false
let stopped = false
let bytes = 0
const stdout = []
const stderr = []
let timer
let treeKillTimer
let fallbackKillTimer
const killWindowsTree = () => {
let spawned = false
try {
const killer = spawn("taskkill", ["/T", "/F", "/PID", String(child.pid)], { stdio: "ignore", windowsHide: true })
killer?.unref?.()
spawned = Boolean(killer)
if (typeof killer?.once === "function") {
const done = new Promise(r => {
killer.once("error", () => { try { child.kill("SIGKILL") } catch {}; r() })
killer.once("close", code => { if (code !== 0) try { child.kill("SIGKILL") } catch {}; r() })
})
onTreeKill?.(done)
}
} catch {}
if (!spawned) {
try { child.kill("SIGKILL") } catch {}
} else {
fallbackKillTimer = setTimeout(() => { try { child.kill("SIGKILL") } catch {} }, 500)
fallbackKillTimer.unref?.()
}
}
const stop = (fromExit = false) => {
if (!child?.pid || stopped) return
if (process.platform === "win32") {
if (fromExit && child.exitCode !== null) {
treeKillTimer = setTimeout(() => {
if (!settled && !stopped) {
stopped = true
killWindowsTree()
}
}, 30)
treeKillTimer.unref?.()
return
}
stopped = true
clearTimeout(treeKillTimer)
killWindowsTree()
return
}
stopped = true
// Only this detached child/group is ours, never an existing user agy.
try { process.kill(-child.pid, "SIGKILL") } catch {
try { child.kill("SIGKILL") } catch {}
}
}
const finish = (error, result) => {
if (settled) return
settled = true
clearTimeout(timer)
clearTimeout(treeKillTimer)
clearTimeout(fallbackKillTimer)
signal?.removeEventListener("abort", abort)
if (process.platform !== "win32" || error || child?.exitCode === null) {
stop() // Also stop MCP descendants if the parent exited first.
}
child?.stdout?.destroy()
child?.stderr?.destroy()
if (error) reject(error)
else resolve(result)
}
const abort = () => finish(new UsageError("agy usage query was cancelled.", { kind: "cancel" }))
const late = () => finish(new UsageError("agy usage query timed out.", {
kind: "timeout", output: Buffer.concat(stdout).toString("utf8") + "\n" + Buffer.concat(stderr).toString("utf8"),
}))
if (signal?.aborted) return abort()
if (Date.now() >= deadline) return finish(new UsageError("agy usage query timed out."))
try {
const command = agySpawnSpec(file, args)
child = spawn(command.file, command.args, {
cwd,
env,
detached: process.platform !== "win32",
...command.options,
windowsHide: true,
stdio: ["ignore", "pipe", "pipe"],
})
} catch {
finish(new UsageError("agy usage could not start the CLI."))
return
}
signal?.addEventListener("abort", abort, { once: true })
timer = setTimeout(late, Math.max(1, deadline - Date.now()))
const collect = chunks => chunk => {
if (settled) return
bytes += chunk.length
if (bytes > maxOutputBytes) return finish(new UsageError("agy usage output exceeded the size limit."))
chunks.push(chunk)
}
child.stdout.on("data", collect(stdout))
child.stderr.on("data", collect(stderr))
child.on("error", () => finish(new UsageError("agy usage could not start the CLI.")))
// exit, not close: a descendant may inherit the pipe and keep it open.
// Drain the already-written output through close for a normal parent exit.
child.on("exit", () => stop(true))
child.on("close", code => finish(null, {
code, stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8"),
}))
})
}
function supportedVersion(output) {
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(output.trim())
if (!match) return false
const [major, minor, patch] = match.slice(1).map(Number)
return major > 1 || major === 1 && (minor > 1 || minor === 1 && patch >= 11)
}
export async function fetchUsage(agy, {
env = process.env,
timeoutMs = env.AGY_BRIDGE_USAGE_TIMEOUT_MS,
maxOutputBytes = MAX_OUTPUT_BYTES,
signal,
tempRoot = os.tmpdir(),
} = {}) {
if (!agy) throw new UsageError("agy CLI not found. Install it and run `agy` once to sign in.")
const deadline = Date.now() + timeout(timeoutMs)
const directory = await fs.mkdtemp(path.join(tempRoot, "magpie-agy-usage-"))
let pendingTreeKill = null
try {
await fs.chmod(directory, 0o700)
const agentDir = path.join(directory, ".agents", "agents", "magpie-usage")
await fs.mkdir(agentDir, { recursive: true })
await fs.writeFile(path.join(agentDir, "agent.md"), [
"---", "name: magpie-usage", "description: Read CLI usage only", "mainAgent: true", "subagent: false",
"tools: []", "mcpServers: []", "---", "Do not run model prompts or tools.", "",
].join("\n"), { mode: 0o600 })
if (process.platform === "win32") {
await fs.writeFile(path.join(directory, "open.cmd"), "@exit /b 1\r\n")
} else {
for (const name of ["open", "xdg-open"]) {
await fs.writeFile(path.join(directory, name), "#!/bin/sh\nexit 1\n", { mode: 0o700 })
}
}
const baseEnv = { ...env }
const inheritedPath = env.PATH || baseEnv.Path || (process.platform === "win32" ? "" : "/usr/bin:/bin")
for (const key of Object.keys(baseEnv)) {
if (/^path$/i.test(key) && key !== "PATH") delete baseEnv[key]
}
const childEnv = agyChildEnv(baseEnv, {
PATH: directory + path.delimiter + inheritedPath,
BROWSER: path.join(directory, process.platform === "win32" ? "open.cmd" : "open"),
})
const options = { cwd: directory, env: childEnv, deadline, signal, maxOutputBytes, onTreeKill: p => { pendingTreeKill = p } }
// --version needs no sign-in, so its hang is never read as one
const version = await run(agy, ["--version"], { ...options, deadline: Math.min(deadline, Date.now() + 3000) }).catch((error) => {
if (error?.kind === "timeout") throw new UsageError(error.message)
throw error
})
if (version.code !== 0) throw commandFailure(version.stderr)
if (!supportedVersion(version.stdout)) throw new UsageError("agy usage reports require a verified agy version 1.1.11 or later. Update the CLI.")
const result = await run(agy, ["-p", "/usage", "--output-format", "json", "--agent", "magpie-usage", "--print-timeout", `${Math.max(1, Math.ceil((deadline - Date.now()) / 1000))}s`], options)
if (result.code !== 0) throw commandFailure(result.stderr + "\n" + result.stdout)
return parseUsageReport(result.stdout)
} finally {
for (let attempt = 0; attempt < 4; attempt++) {
try {
await fs.rm(directory, { recursive: true, force: true })
break
} catch (error) {
if (attempt === 3 || !["EBUSY", "EPERM", "ENOTEMPTY"].includes(error?.code)) break
if (pendingTreeKill) {
const waitKill = pendingTreeKill
pendingTreeKill = null
await Promise.race([waitKill, new Promise(resolve => setTimeout(resolve, 800))])
}
await new Promise(resolve => setTimeout(resolve, 50 * (attempt + 1)))
}
}
}
}
// A read that failed isn't run again for this long, doubled for each
// failure in a row, up to BACKOFF_MOST: agy is a process of its own, and one
// that fails every few minutes all day helps nobody.
const BACKOFF_FIRST_MS = 10 * 60 * 1000
const BACKOFF_MOST_MS = 6 * 60 * 60 * 1000
function backoff(n) {
return Math.min(BACKOFF_FIRST_MS * 2 ** Math.max(0, Math.min(n, 20) - 1), BACKOFF_MOST_MS)
}
const NEEDS_SIGN_IN = "Sign in again from this account's Sign in in magpie, or run `agy` in a terminal; magpie doesn't run agy for usage until then."
// No completed-result cache: sequential refreshes must see account/allowance changes.
// What is kept is what keeps agy from being run when it can't answer:
// - agy's stored sign-in is read first (signin.mjs), and agy isn't run when
// there is none, or it has ended with nothing to renew it: the read says
// the sign-in has expired (signIn "expired"), which magpie shows on the
// account, and nothing starts a Google sign-in in the background.
// - a run agy failed for want of a sign-in (it said so, or it hung with an
// ended access token, as an agy waiting on its browser sign-in does) marks
// that stored sign-in dead: agy isn't run again until another is stored.
// - any other failure isn't run again for backoff(n).
export function createUsageReader(resolveAgy, options = {}) {
const { signIn = () => storedSignIn(), now = () => Date.now(), ...fetchOptions } = options
const pending = new Map()
let held = null
let saidExpired = false
const expired = (why) => {
saidExpired = true
return { windows: [], error: `${why}. ${NEEDS_SIGN_IN}`, signIn: "expired" }
}
return async () => {
let stored
try { stored = await signIn() } catch { stored = { state: "unknown" } }
const why = cannotSignIn(stored)
if (why) return expired(why)
if (isDead(stored)) return expired("agy's sign-in no longer works")
const key = stored?.state === "present" ? stored.fp : "unknown"
if (held && held.key === key && now() < held.until) {
return { windows: [], error: held.error, signIn: held.auth ? "expired" : "kept" }
}
try {
const agy = resolveAgy()
if (!pending.has(agy)) {
const query = fetchUsage(agy, fetchOptions).finally(() => {
if (pending.get(agy) === query) pending.delete(agy)
})
pending.set(agy, query)
}
const result = { ...structuredClone(await pending.get(agy)), signIn: saidExpired ? "renewed" : "kept" }
held = null
saidExpired = false
return result
} catch (error) {
const message = error instanceof UsageError ? error.message : "agy usage query failed. Check the CLI and temporary-directory permissions."
if (error?.kind === "cancel") return { windows: [], error: message, signIn: "kept" }
const auth = error?.kind === "auth" || error?.kind === "timeout" && stored?.state === "present" && stored.expired &&
(!String(error.output ?? "").trim() || SIGN_IN_TALK.test(error.output))
if (auth && stored?.state === "present") {
noteDead(stored)
return expired("agy's sign-in no longer works")
}
const n = held?.key === key ? held.n + 1 : 1
held = { key, n, until: now() + backoff(n), error: message, auth }
if (auth) saidExpired = true
return { windows: [], error: message, signIn: auth ? "expired" : "kept" }
}
}
}