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 ona02d5912: `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 (e90d6f01base): 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.
This commit is contained in:
@@ -189,10 +189,18 @@ magpie quota refresh agy-cli --json
|
||||
```
|
||||
|
||||
The numbers come from agy's own `/usage` report for whichever account is signed
|
||||
in to the CLI, broken down by model group. The plugin does not read or write
|
||||
Google tokens; it always reports the account agy is signed in to. A window with no
|
||||
in to the CLI, broken down by model group. The plugin never writes Google tokens
|
||||
or sends them anywhere; it always reports the account agy is signed in to. A window with no
|
||||
measurable data shows "Limits not available" rather than a fake 0% or 100%.
|
||||
|
||||
A signed-out agy opens Google's sign-in page in the browser when it runs, so
|
||||
before running agy for usage or the model list, the plugin looks at agy's stored
|
||||
sign-in in the system keychain (macOS) or Credential Manager (Windows) and only
|
||||
reads whether one is there and when it ends. With none, with one that has ended
|
||||
and can't be renewed, or with one agy already failed on, agy is not run: the
|
||||
account shows its sign-in has expired until you sign in again. Other failed
|
||||
usage reads wait 10 minutes before the next try, doubling up to 6 hours.
|
||||
|
||||
## Environment variables
|
||||
|
||||
| Name | Default value | What it does |
|
||||
@@ -210,6 +218,7 @@ measurable data shows "Limits not available" rather than a fake 0% or 100%.
|
||||
| `AGY_BRIDGE_DETACHED_EVICT_MS` | 30000 | How long a suspended tool turn whose client disconnected may keep its pool slot |
|
||||
| `AGY_BRIDGE_MAX_PROMPT_BYTES` | 114688 (112 KiB) | Byte budget for the replayed history prompt |
|
||||
| `AGY_BRIDGE_USAGE_TIMEOUT_MS` | 15000 | Total time budget for a usage query, capped at 18000 |
|
||||
| `AGY_BRIDGE_STORED_SIGNIN` | unset | `skip` stops the plugin from reading agy's stored sign-in |
|
||||
| `AGY_BRIDGE_MCP_TRACE` | unset | Writes MCP channel traffic to the given file; for debugging only |
|
||||
| `AGY_CLI_DISABLE_AUTO_UPDATE` | `true` for the plugin's agy processes | agy's own variable. When you set it, agy gets your value; see "Requirements" |
|
||||
| `AGY_BRIDGE_PREFILL` | on | Set to `0` to restore the stock 400 reject for assistant prefill tails; see "Assistant prefill" |
|
||||
|
||||
@@ -139,9 +139,14 @@ magpie quota refresh agy-cli --json
|
||||
```
|
||||
|
||||
额度数据来自 agy 自己的 `/usage` 报告,显示的是当前 agy 登录账号的订阅窗口,按模型组
|
||||
分别列出。插件不读写 Google 令牌,查询的始终是 agy 当前登录的账号。没有可测量数据的窗口会显示
|
||||
分别列出。插件不写 Google 令牌,也不把它发往任何地方,查询的始终是 agy 当前登录的账号。没有可测量数据的窗口会显示
|
||||
"Limits not available",而不是 0% 或 100%。
|
||||
|
||||
未登录的 agy 一运行就会在浏览器里打开 Google 登录页,所以插件在为额度或模型列表运行 agy 之前,
|
||||
先看系统钥匙串(macOS)或凭据管理器(Windows)里 agy 存的登录,只读有没有、何时到期。没有登录、
|
||||
登录已过期且无法续期、或 agy 已在这份登录上失败过时,不运行 agy,账号显示登录已过期,直到重新登录。
|
||||
其他失败的额度查询等 10 分钟再试,每次翻倍,最长 6 小时。
|
||||
|
||||
## 环境变量
|
||||
|
||||
| 变量 | 默认值 | 作用 |
|
||||
@@ -159,6 +164,7 @@ magpie quota refresh agy-cli --json
|
||||
| `AGY_BRIDGE_DETACHED_EVICT_MS` | 30000 | 客户端已断开的挂起工具回合,最多占用进程池槽位这么久 |
|
||||
| `AGY_BRIDGE_MAX_PROMPT_BYTES` | 114688(112 KiB) | 重放历史提示词的字节预算 |
|
||||
| `AGY_BRIDGE_USAGE_TIMEOUT_MS` | 15000 | 额度查询的总时间预算,最高 18000 |
|
||||
| `AGY_BRIDGE_STORED_SIGNIN` | 未设置 | 设为 `skip` 时插件不读 agy 存的登录 |
|
||||
| `AGY_BRIDGE_MCP_TRACE` | 未设置 | 把 MCP 通道流量写入指定文件,仅用于排查 |
|
||||
| `AGY_CLI_DISABLE_AUTO_UPDATE` | 插件启动的 agy 设为 `true` | agy 自己的变量。你设置了就原样传给 agy,见「环境要求」 |
|
||||
| `AGY_BRIDGE_PREFILL` | 开启 | 设为 `0` 恢复对 assistant 预填尾巴的原生 400 拒绝,见「助手预填」 |
|
||||
|
||||
@@ -8,7 +8,7 @@ const dir = path.join(import.meta.dir, "test")
|
||||
const hook = path.join(dir, "cp-hook.mjs")
|
||||
|
||||
function run(args, timeout) {
|
||||
const result = Bun.spawnSync({ cmd: [process.execPath, ...args], cwd: dir, env: { ...process.env }, stdout: "pipe", stderr: "pipe", timeout })
|
||||
const result = Bun.spawnSync({ cmd: [process.execPath, ...args], cwd: dir, env: { ...process.env, AGY_BRIDGE_STORED_SIGNIN: "skip" }, stdout: "pipe", stderr: "pipe", timeout })
|
||||
const output = result.stdout.toString() + result.stderr.toString()
|
||||
if (result.exitCode !== 0) console.error(output)
|
||||
return { code: result.exitCode, output }
|
||||
@@ -19,6 +19,7 @@ for (const [name, mocks] of [
|
||||
["compat.mjs", true],
|
||||
["prefill.mjs", false],
|
||||
["usage.mjs", true],
|
||||
["signin.mjs", false],
|
||||
["catalog.mjs", false],
|
||||
["step-usage.mjs", false],
|
||||
["tool-schema.mjs", false],
|
||||
|
||||
@@ -8,6 +8,7 @@ import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import { createUsageReader } from "./usage.mjs"
|
||||
import { backgroundBlocked, cannotSignIn, forgetStoredSignIn, storedSignInNow } from "./signin.mjs"
|
||||
import { sanitizePatternFields } from "./re2-pattern.mjs"
|
||||
import { startLogin } from "./login.mjs"
|
||||
import { ensureGeminiArrayItems } from "./array-items.mjs"
|
||||
@@ -219,6 +220,9 @@ function execOnce(file, args, opts = {}) {
|
||||
}
|
||||
|
||||
async function listAgyModels(agyPath) {
|
||||
// a listing nobody asked for doesn't run an agy that would start its own
|
||||
// Google sign-in (signin.mjs); the catalog it has stays
|
||||
if (await backgroundBlocked()) return null
|
||||
const { err, stdout, code, timedOut } = await execOnce(agyPath, ["models"], { timeoutMs: 15_000, unrefTimer: true })
|
||||
// null, not FALLBACK_MODELS: a failed listing must not overwrite a dynamic catalog.
|
||||
if (err || timedOut || code !== 0) return null
|
||||
@@ -249,6 +253,11 @@ function parseAgyModels(stdout) {
|
||||
const OFFERED_SIGNIN_WAIT_MS = 3_000
|
||||
|
||||
async function probeSignedIn(agy) {
|
||||
// no sign-in stored, or one agy failed with: `agy models` would start
|
||||
// agy's own Google sign-in (on Windows, a browser no shim stops), so the
|
||||
// caller goes on to magpie's own sign-in link instead
|
||||
const blocked = await backgroundBlocked({ fresh: true })
|
||||
if (blocked) return { ok: false, why: blocked }
|
||||
const probe = await execOnce(agy, ["models"], { timeoutMs: 15_000 })
|
||||
const listed = !probe.err && !probe.timedOut && probe.code === 0 &&
|
||||
probe.stdout.split("\n").some(line => /^\S+\s+\S/.test(line.trim()))
|
||||
@@ -5325,6 +5334,9 @@ export const AntigravityBridgePlugin = async () => {
|
||||
callback: async (code, opts = {}) => {
|
||||
const done = await login.finish(code, { signal: opts.signal })
|
||||
if (done.error) return { type: "failed", error: done.error }
|
||||
// agy stored a new sign-in: read it again, and let what
|
||||
// failed with the old one run again
|
||||
forgetStoredSignIn({ dead: true })
|
||||
// A new account: what agy offered the last one, or refused
|
||||
// before the sign-in, is asked again.
|
||||
forgetOffered()
|
||||
@@ -5366,6 +5378,14 @@ export const AntigravityBridgePlugin = async () => {
|
||||
|
||||
const agy = findAgy()
|
||||
if (!agy) return jsonError(503, "agy CLI not found on this machine")
|
||||
// nothing stored to sign agy in with: agy would only start its
|
||||
// own Google sign-in, so the account is told to sign in again
|
||||
// (from the last read; a request doesn't wait for a new one)
|
||||
const notSignedIn = cannotSignIn(storedSignInNow())
|
||||
if (notSignedIn) {
|
||||
return jsonError(401, `${notSignedIn}: sign in again in magpie, or run \`agy\` in a terminal`, undefined,
|
||||
{ headers: { "X-Magpie-Sign-In": "expired" } })
|
||||
}
|
||||
let body
|
||||
try {
|
||||
const raw = typeof init.body === "string" ? init.body : new TextDecoder().decode(init.body)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-agy-cli-auth",
|
||||
"version": "0.1.33",
|
||||
"version": "0.1.34",
|
||||
"description": "Magpie/OpenCode model provider that connects your local agy CLI through the Agent Client Protocol (agy acp), so Antigravity subscription models run through the real CLI",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
@@ -17,6 +17,7 @@
|
||||
"step-usage.mjs",
|
||||
"tool-schema.mjs",
|
||||
"usage.mjs",
|
||||
"signin.mjs",
|
||||
"README.md",
|
||||
"README.en.md",
|
||||
"LICENSE",
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { execFile } from "node:child_process"
|
||||
import { createHash } from "node:crypto"
|
||||
|
||||
// What agy's own sign-in looks like on this computer, read without running
|
||||
// agy. agy keeps its Google token in the system keyring through go-keyring,
|
||||
// under service "gemini" and user "antigravity": on macOS a generic
|
||||
// password `security` wrote (so `security` reads it back without a prompt),
|
||||
// on Windows the generic credential "gemini:antigravity" in Credential
|
||||
// Manager. The value is JSON (on macOS behind "go-keyring-base64:"):
|
||||
// {"token":{"access_token","refresh_token","expiry","expires_in","token_type"},
|
||||
// "auth_method":"consumer","id_token_email":…}
|
||||
//
|
||||
// Why this exists: an agy that isn't signed in, or whose sign-in Google no
|
||||
// longer takes, starts its own Google sign-in when it runs, and on Windows
|
||||
// it opens the browser through ShellExecuteW, which no BROWSER or PATH
|
||||
// shim can stop. The usage refresh ran agy every few minutes, and a
|
||||
// signed-out agy opened the browser 235 times in one day
|
||||
// (JZGiVvkSOA75376 on X). So agy is not run for background work while
|
||||
// this says it can't be signed in.
|
||||
//
|
||||
// state:
|
||||
// "missing" no sign-in is stored: agy is not signed in.
|
||||
// "present" one is: fp tells this sign-in from the next (a hash, never
|
||||
// the token), canRenew whether it has a refresh token, and
|
||||
// expiresAt when its access token ends (0: not said).
|
||||
// "unknown" it couldn't be read (another OS, a locked keychain, a
|
||||
// format agy may change to): nothing is concluded from it.
|
||||
|
||||
const SERVICE = "gemini"
|
||||
const USER = "antigravity"
|
||||
const READ_TIMEOUT_MS = 10_000
|
||||
// A sign-in is read again after this long; reading it on Windows starts
|
||||
// PowerShell, so a burst of requests and listings shares one read.
|
||||
const CACHE_MS = 30_000
|
||||
// Sign-ins agy takes from its environment rather than the keyring: a Gemini
|
||||
// or Google API key, Application Default Credentials, Vertex AI.
|
||||
const ENV_SIGN_INS = ["GEMINI_API_KEY", "GOOGLE_API_KEY", "AGY_ADC_AUTH", "GOOGLE_GENAI_USE_VERTEXAI"]
|
||||
|
||||
// PowerShell reads the credential through CredReadW. CREDENTIALW is
|
||||
// Flags, Type, TargetName, Comment, LastWritten (8 bytes),
|
||||
// CredentialBlobSize, CredentialBlob: the blob's size and pointer offsets
|
||||
// follow the pointer size.
|
||||
export const WINDOWS_SCRIPT = `
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -Namespace MagpieAgy -Name Cred -MemberDefinition @'
|
||||
[DllImport("advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
public static extern bool CredRead(string target, int type, int flags, out IntPtr cred);
|
||||
[DllImport("advapi32.dll", EntryPoint = "CredFree")]
|
||||
public static extern void CredFree(IntPtr cred);
|
||||
'@
|
||||
$p = [IntPtr]::Zero
|
||||
if (-not [MagpieAgy.Cred]::CredRead('${SERVICE}:${USER}', 1, 0, [ref]$p)) {
|
||||
$e = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
|
||||
if ($e -eq 1168) { 'MISSING' } else { "ERROR $e" }
|
||||
exit 0
|
||||
}
|
||||
try {
|
||||
$ptr = [IntPtr]::Size
|
||||
$sizeAt = 8 + 2 * $ptr + 8
|
||||
$blobAt = $sizeAt + 4
|
||||
if ($blobAt % $ptr) { $blobAt += $ptr - ($blobAt % $ptr) }
|
||||
$size = [Runtime.InteropServices.Marshal]::ReadInt32($p, $sizeAt)
|
||||
$blob = [Runtime.InteropServices.Marshal]::ReadIntPtr($p, $blobAt)
|
||||
$bytes = New-Object byte[] $size
|
||||
if ($size -gt 0) { [Runtime.InteropServices.Marshal]::Copy($blob, $bytes, 0, $size) }
|
||||
'OK ' + [Convert]::ToBase64String($bytes)
|
||||
} finally { [MagpieAgy.Cred]::CredFree($p) }
|
||||
`
|
||||
|
||||
function run(file, args) {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
execFile(file, args, { timeout: READ_TIMEOUT_MS, windowsHide: true, maxBuffer: 1024 * 1024, encoding: "utf8" },
|
||||
(error, stdout) => resolve({ code: error ? (typeof error.code === "number" ? error.code : -1) : 0, stdout: String(stdout ?? "") }))
|
||||
} catch {
|
||||
resolve({ code: -1, stdout: "" })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// parseStored is what a stored value says, "unknown" when it isn't the
|
||||
// shape agy writes.
|
||||
export function parseStored(raw, now = Date.now()) {
|
||||
let value = String(raw ?? "").trim()
|
||||
const fp = createHash("sha256").update(value).digest("hex").slice(0, 32)
|
||||
if (value.startsWith("go-keyring-base64:")) {
|
||||
value = Buffer.from(value.slice("go-keyring-base64:".length), "base64").toString("utf8")
|
||||
} else if (value.startsWith("go-keyring-encoded:")) {
|
||||
value = Buffer.from(value.slice("go-keyring-encoded:".length), "hex").toString("utf8")
|
||||
}
|
||||
let stored
|
||||
try { stored = JSON.parse(value) } catch { return { state: "unknown" } }
|
||||
// a Gemini API key needs no Google sign-in
|
||||
if (typeof stored?.api_key === "string" && stored.api_key !== "") return { state: "unknown" }
|
||||
const token = stored?.token
|
||||
if (!token || typeof token !== "object") return { state: "unknown" }
|
||||
const canRenew = typeof token.refresh_token === "string" && token.refresh_token !== ""
|
||||
const hasAccess = typeof token.access_token === "string" && token.access_token !== ""
|
||||
if (!canRenew && !hasAccess) return { state: "missing" }
|
||||
const at = Date.parse(token.expiry ?? "")
|
||||
// Go's zero time (0001-01-01) is "doesn't end"
|
||||
const expiresAt = Number.isFinite(at) && at > 0 ? at : 0
|
||||
return { state: "present", fp, canRenew, expiresAt, expired: expiresAt > 0 && now >= expiresAt }
|
||||
}
|
||||
|
||||
// readStoredSignIn reads agy's stored sign-in on this computer.
|
||||
export async function readStoredSignIn({ platform = process.platform, exec = run, now = Date.now(), env = process.env } = {}) {
|
||||
// tests, and setups this reading doesn't fit, turn it off
|
||||
if (env.AGY_BRIDGE_STORED_SIGNIN === "skip") return { state: "unknown" }
|
||||
// agy signs in with these instead of a stored Google sign-in
|
||||
if (ENV_SIGN_INS.some((name) => env[name])) return { state: "unknown" }
|
||||
if (platform === "darwin") {
|
||||
const r = await exec("/usr/bin/security", ["find-generic-password", "-s", SERVICE, "-a", USER, "-w"])
|
||||
// 44: errSecItemNotFound
|
||||
if (r.code === 44) return { state: "missing" }
|
||||
if (r.code !== 0) return { state: "unknown" }
|
||||
return parseStored(r.stdout, now)
|
||||
}
|
||||
if (platform === "win32") {
|
||||
const r = await exec("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", WINDOWS_SCRIPT])
|
||||
// the answer is the last line; anything PowerShell said before it isn't
|
||||
const out = r.stdout.trim().split(/\r?\n/).at(-1)?.trim() ?? ""
|
||||
if (r.code !== 0) return { state: "unknown" }
|
||||
if (out === "MISSING") return { state: "missing" }
|
||||
if (!out.startsWith("OK ")) return { state: "unknown" }
|
||||
// go-keyring on Windows stores the value's bytes as they are (UTF-8)
|
||||
return parseStored(Buffer.from(out.slice(3), "base64").toString("utf8"), now)
|
||||
}
|
||||
return { state: "unknown" }
|
||||
}
|
||||
|
||||
// cannotSignIn is why a stored sign-in can't serve agy without a new
|
||||
// Google sign-in, or "" when it may.
|
||||
export function cannotSignIn(s) {
|
||||
if (s?.state === "missing") return "agy isn't signed in"
|
||||
if (s?.state === "present" && !s.canRenew && s.expired) return "agy's sign-in has expired"
|
||||
return ""
|
||||
}
|
||||
|
||||
// Sign-ins agy was found unable to use (a run it failed in a way only a
|
||||
// new sign-in mends), by fp: agy isn't run in the background for them
|
||||
// again; signing in again stores another and so another fp.
|
||||
const dead = new Set()
|
||||
|
||||
export function noteDead(s) {
|
||||
if (s?.state === "present" && s.fp) dead.add(s.fp)
|
||||
}
|
||||
|
||||
export function isDead(s) {
|
||||
return s?.state === "present" && dead.has(s.fp)
|
||||
}
|
||||
|
||||
let cached = null
|
||||
let reading = null
|
||||
|
||||
// storedSignIn is readStoredSignIn, shared for CACHE_MS and while one read
|
||||
// is under way.
|
||||
export async function storedSignIn({ read = readStoredSignIn, fresh = false } = {}) {
|
||||
if (!fresh && cached && Date.now() - cached.at < CACHE_MS) return cached.value
|
||||
if (!reading) {
|
||||
const r = Promise.resolve().then(() => read()).catch(() => ({ state: "unknown" })).then((value) => {
|
||||
if (reading === r) {
|
||||
cached = { at: Date.now(), value }
|
||||
reading = null
|
||||
}
|
||||
return value
|
||||
})
|
||||
reading = r
|
||||
}
|
||||
return reading
|
||||
}
|
||||
|
||||
// storedSignInNow is the last read without waiting for one (null before
|
||||
// the first), starting a new read when it is old: a request isn't held up
|
||||
// by a keyring read (on Windows, PowerShell).
|
||||
export function storedSignInNow({ read = readStoredSignIn } = {}) {
|
||||
if (!cached || Date.now() - cached.at >= CACHE_MS) storedSignIn({ read }).catch(() => {})
|
||||
return cached?.value ?? null
|
||||
}
|
||||
|
||||
// backgroundBlocked is why agy must not be run for work nobody asked for
|
||||
// (a usage read, a model listing): its sign-in can't serve it and running
|
||||
// it would start a Google sign-in. "" when it may run.
|
||||
export async function backgroundBlocked(opts) {
|
||||
const s = await storedSignIn(opts)
|
||||
return cannotSignIn(s) || (isDead(s) ? "agy's sign-in no longer works" : "")
|
||||
}
|
||||
|
||||
// forgetStoredSignIn drops the cached read (after a sign-in, and in tests).
|
||||
export function forgetStoredSignIn({ dead: clearDead = false } = {}) {
|
||||
cached = null
|
||||
reading = null
|
||||
if (clearDead) dead.clear()
|
||||
}
|
||||
@@ -63,6 +63,34 @@ test("没有 agy 时直接给静态目录,不起子进程", async () => {
|
||||
})
|
||||
})
|
||||
|
||||
// JZGiVvkSOA75376 on X: a signed-out agy opens Google's sign-in in the browser
|
||||
// whenever it runs (on Windows through ShellExecuteW, past any BROWSER shim).
|
||||
test("agy 没存登录时不在后台跑 agy models、不起探测会话,请求答需要重新登录", async () => {
|
||||
await withKit({ platform: "darwin", storedSignIn: "missing", modelsBehavior: DYNAMIC_OK }, async (kit) => {
|
||||
assertFallbackPresent(await kit.models())
|
||||
const warming = kit.plugin.provider.warming?.()
|
||||
if (warming) await warming
|
||||
await settle(kit)
|
||||
assert.equal(kit.modelsSpawns.length, 0, "没登录也跑了 agy models")
|
||||
assert.equal(kit.acpSpawns.length, 0, "没登录也起了探测会话")
|
||||
assert.ok(kit.execFiles.some(c => c.file === "/usr/bin/security" && c.args.includes("antigravity")))
|
||||
const response = await kit.request(baseBody())
|
||||
assert.equal(response.status, 401)
|
||||
assert.equal(response.headers.get("X-Magpie-Sign-In"), "expired")
|
||||
assert.match(await response.text(), /isn't signed in/)
|
||||
assert.equal(kit.acpSpawns.length, 0, "没登录也为请求起了 agy")
|
||||
})
|
||||
// 存着能续期的登录(access token 过期也一样):照常列目录
|
||||
const value = "go-keyring-base64:" + Buffer.from(JSON.stringify({ token: { access_token: "a", refresh_token: "r", expiry: "2020-01-01T00:00:00Z" } })).toString("base64")
|
||||
await withKit({ platform: "darwin", storedSignIn: value + "\n", modelsBehavior: DYNAMIC_OK }, async (kit) => {
|
||||
await kit.models()
|
||||
const warming = kit.plugin.provider.warming?.()
|
||||
if (warming) await warming
|
||||
await settle(kit)
|
||||
assert.ok(kit.modelsSpawns.length >= 1, "有登录却没跑 agy models")
|
||||
})
|
||||
})
|
||||
|
||||
test("首次 agy models 卡死时 750ms 内返回非空静态目录", async () => {
|
||||
await withKit({ modelsBehavior: { hang: true } }, async (kit) => {
|
||||
const { value, ms } = await timed(() => kit.models())
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { backgroundBlocked, cannotSignIn, forgetStoredSignIn, isDead, noteDead, parseStored, readStoredSignIn, storedSignIn, storedSignInNow } from "../signin.mjs"
|
||||
|
||||
const NOW = Date.parse("2026-11-13T00:00:00Z")
|
||||
const stored = (token, extra = {}) => JSON.stringify({ token, auth_method: "consumer", id_token_email: "someone@example.com", ...extra })
|
||||
const b64 = (s) => "go-keyring-base64:" + Buffer.from(s).toString("base64")
|
||||
|
||||
test("reads what agy's keyring value says, on macOS (base64) and Windows (raw JSON)", () => {
|
||||
const renewable = stored({ access_token: "a", refresh_token: "r", expiry: "2026-11-12T13:00:00Z", token_type: "Bearer" })
|
||||
for (const raw of [b64(renewable), renewable]) {
|
||||
const s = parseStored(raw, NOW)
|
||||
assert.equal(s.state, "present")
|
||||
assert.equal(s.canRenew, true)
|
||||
assert.equal(s.expired, true)
|
||||
assert.match(s.fp, /^[0-9a-f]{32}$/)
|
||||
assert.doesNotMatch(JSON.stringify(s), /someone|"a"|"r"/)
|
||||
// an ended access token with a refresh token is how a working agy looks
|
||||
assert.equal(cannotSignIn(s), "")
|
||||
}
|
||||
assert.notEqual(parseStored(renewable, NOW).fp, parseStored(stored({ refresh_token: "r2" }), NOW).fp)
|
||||
})
|
||||
|
||||
test("an ended sign-in with nothing to renew it, or no token at all, can't sign agy in", () => {
|
||||
const ended = parseStored(b64(stored({ access_token: "a", expiry: "2026-11-12T00:00:00Z" })), NOW)
|
||||
assert.equal(ended.state, "present")
|
||||
assert.match(cannotSignIn(ended), /expired/)
|
||||
const live = parseStored(stored({ access_token: "a", expiry: "2026-11-14T00:00:00Z" }), NOW)
|
||||
assert.equal(cannotSignIn(live), "")
|
||||
// Go's zero time: doesn't end
|
||||
const zero = parseStored(stored({ access_token: "a", expiry: "0001-01-01T00:00:00Z" }), NOW)
|
||||
assert.equal(zero.expired, false)
|
||||
assert.equal(cannotSignIn(zero), "")
|
||||
assert.equal(parseStored(stored({ access_token: "", refresh_token: "" }), NOW).state, "missing")
|
||||
assert.match(cannotSignIn({ state: "missing" }), /isn't signed in/)
|
||||
})
|
||||
|
||||
test("a value of another shape, or an API key, concludes nothing", () => {
|
||||
for (const raw of ["", "garbage", b64("not json"), JSON.stringify({ hello: 1 }), stored(undefined, { api_key: "k" }), stored({}, { api_key: "k" })]) {
|
||||
const s = parseStored(raw, NOW)
|
||||
assert.equal(s.state, "unknown", raw)
|
||||
assert.equal(cannotSignIn(s), "")
|
||||
}
|
||||
})
|
||||
|
||||
test("readStoredSignIn asks each system's keyring the way go-keyring stores it", async () => {
|
||||
const value = stored({ access_token: "a", refresh_token: "r", expiry: "2026-11-12T00:00:00Z" })
|
||||
const calls = []
|
||||
const mac = (code, stdout = "") => async (file, args) => { calls.push([file, ...args]); return { code, stdout } }
|
||||
assert.equal((await readStoredSignIn({ platform: "darwin", exec: mac(44), env: {} })).state, "missing")
|
||||
assert.deepEqual(calls[0], ["/usr/bin/security", "find-generic-password", "-s", "gemini", "-a", "antigravity", "-w"])
|
||||
assert.equal((await readStoredSignIn({ platform: "darwin", exec: mac(51), env: {} })).state, "unknown")
|
||||
assert.equal((await readStoredSignIn({ platform: "darwin", exec: mac(0, b64(value) + "\n"), now: NOW, env: {} })).state, "present")
|
||||
const win = (stdout, code = 0) => async (file, args) => { calls.push([file, ...args]); return { code, stdout } }
|
||||
assert.equal((await readStoredSignIn({ platform: "win32", exec: win("MISSING\r\n"), env: {} })).state, "missing")
|
||||
assert.match(calls.at(-1).at(-1), /CredReadW[\s\S]*'gemini:antigravity'/)
|
||||
assert.equal((await readStoredSignIn({ platform: "win32", exec: win("WARNING: something\r\nMISSING\r\n"), env: {} })).state, "missing")
|
||||
assert.equal((await readStoredSignIn({ platform: "win32", exec: win("ERROR 5\r\n"), env: {} })).state, "unknown")
|
||||
assert.equal((await readStoredSignIn({ platform: "win32", exec: win("", 1), env: {} })).state, "unknown")
|
||||
const w = await readStoredSignIn({ platform: "win32", exec: win("OK " + Buffer.from(value).toString("base64") + "\r\n"), now: NOW, env: {} })
|
||||
assert.equal(w.state, "present")
|
||||
assert.equal(w.canRenew, true)
|
||||
assert.equal((await readStoredSignIn({ platform: "linux", exec: mac(0), env: {} })).state, "unknown")
|
||||
const before = calls.length
|
||||
for (const env of [{ AGY_BRIDGE_STORED_SIGNIN: "skip" }, { GEMINI_API_KEY: "k" }, { AGY_ADC_AUTH: "1" }]) {
|
||||
assert.equal((await readStoredSignIn({ platform: "darwin", exec: mac(44), env })).state, "unknown")
|
||||
}
|
||||
assert.equal(calls.length, before)
|
||||
})
|
||||
|
||||
test("one read serves a burst; a dead sign-in blocks background runs until another is stored", async () => {
|
||||
forgetStoredSignIn({ dead: true })
|
||||
let reads = 0
|
||||
let value = { state: "present", fp: "one", canRenew: true, expiresAt: 0, expired: false }
|
||||
const read = async () => { reads++; return value }
|
||||
await Promise.all([storedSignIn({ read }), storedSignIn({ read }), storedSignIn({ read })])
|
||||
assert.equal(reads, 1)
|
||||
assert.equal(await backgroundBlocked({ read }), "")
|
||||
noteDead(value)
|
||||
assert.ok(isDead(value))
|
||||
assert.match(await backgroundBlocked({ read }), /no longer works/)
|
||||
value = { ...value, fp: "two" }
|
||||
assert.equal(await backgroundBlocked({ read, fresh: true }), "")
|
||||
value = { state: "missing" }
|
||||
assert.match(await backgroundBlocked({ read, fresh: true }), /isn't signed in/)
|
||||
forgetStoredSignIn({ dead: true })
|
||||
assert.equal(isDead({ state: "present", fp: "one" }), false)
|
||||
})
|
||||
|
||||
test("storedSignInNow answers from the last read without waiting, and reads again when it is old", async () => {
|
||||
forgetStoredSignIn({ dead: true })
|
||||
let reads = 0
|
||||
let release
|
||||
const read = () => { reads++; return new Promise((r) => { release = r }) }
|
||||
assert.equal(storedSignInNow({ read }), null)
|
||||
assert.equal(storedSignInNow({ read }), null)
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
assert.equal(reads, 1)
|
||||
release({ state: "missing" })
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
assert.deepEqual(storedSignInNow({ read }), { state: "missing" })
|
||||
assert.equal(reads, 1)
|
||||
forgetStoredSignIn({ dead: true })
|
||||
})
|
||||
@@ -36,6 +36,7 @@ export const CLOAK_FILE = path.join(REPO_DIR, "cloak.mjs")
|
||||
export const LOGIN_FILE = path.join(REPO_DIR, "login.mjs")
|
||||
export const RE2_PATTERN_FILE = path.join(REPO_DIR, "re2-pattern.mjs")
|
||||
export const STEP_USAGE_FILE = path.join(REPO_DIR, "step-usage.mjs")
|
||||
export const SIGNIN_FILE = path.join(REPO_DIR, "signin.mjs")
|
||||
export const TOOL_SCHEMA_FILE = path.join(REPO_DIR, "tool-schema.mjs")
|
||||
export const MESSAGES_URL = "agy://local/v1/messages"
|
||||
export const COUNT_TOKENS_URL = "agy://local/v1/messages/count_tokens"
|
||||
@@ -418,6 +419,7 @@ export async function createBridgeKit(options = {}) {
|
||||
acpSpawns: [],
|
||||
otherSpawns: [],
|
||||
spawnSyncs: [],
|
||||
execFiles: [],
|
||||
modelsBehavior: options.modelsBehavior ?? { stdout: modelsOutput(BASE_MODEL_ROWS) },
|
||||
prompts: [],
|
||||
promptSerial: 0,
|
||||
@@ -445,6 +447,9 @@ export async function createBridgeKit(options = {}) {
|
||||
LOCALAPPDATA: path.join(tmp, "localappdata"),
|
||||
XDG_STATE_HOME: path.join(tmp, "state"),
|
||||
AGY_PATH: options.agyPath === undefined ? kit.agyPath : options.agyPath,
|
||||
// agy's stored sign-in is read only when a test says what it is
|
||||
// (options.storedSignIn, macOS keychain output or "missing")
|
||||
...(options.storedSignIn === undefined ? { AGY_BRIDGE_STORED_SIGNIN: "skip" } : {}),
|
||||
...(options.env || {}),
|
||||
}
|
||||
for (const [key, value] of Object.entries(kit.env)) {
|
||||
@@ -479,6 +484,15 @@ export async function createBridgeKit(options = {}) {
|
||||
kit.spawnSyncs.push({ file, args, opts })
|
||||
return { status: 0, signal: null, stdout: "", stderr: "", pid: 0, output: [] }
|
||||
}
|
||||
// signin.mjs's keyring read; never the real keychain
|
||||
const execFile = (file, args = [], opts, callback) => {
|
||||
if (typeof opts === "function") callback = opts
|
||||
kit.execFiles.push({ file, args })
|
||||
const stored = options.storedSignIn
|
||||
setImmediate(() => stored === "missing" || stored === undefined
|
||||
? callback(Object.assign(new Error("not found (test)"), { code: 44 }), "", "")
|
||||
: callback(null, stored, ""))
|
||||
}
|
||||
const fakeServer = {
|
||||
once() { return fakeServer },
|
||||
on() { return fakeServer },
|
||||
@@ -488,7 +502,7 @@ export async function createBridgeKit(options = {}) {
|
||||
address() { return { address: "127.0.0.1", family: "IPv4", port: 45999 } },
|
||||
}
|
||||
const overrides = {
|
||||
"node:child_process": { spawn, spawnSync },
|
||||
"node:child_process": { spawn, spawnSync, execFile },
|
||||
"node:net": {
|
||||
createServer(handler) {
|
||||
kit.controlHandler = handler
|
||||
@@ -514,6 +528,7 @@ export async function createBridgeKit(options = {}) {
|
||||
const loginUrl = pathToFileURL(LOGIN_FILE).href
|
||||
const re2Url = pathToFileURL(RE2_PATTERN_FILE).href
|
||||
const stepUsageUrl = pathToFileURL(STEP_USAGE_FILE).href
|
||||
const signinUrl = pathToFileURL(SIGNIN_FILE).href
|
||||
const toolSchemaUrl = pathToFileURL(TOOL_SCHEMA_FILE).href
|
||||
const linker = (specifier) => {
|
||||
const key = specifier.startsWith("node:") || specifier.startsWith("./") || specifier === RUNTIME_SPECIFIER
|
||||
@@ -528,6 +543,7 @@ export async function createBridgeKit(options = {}) {
|
||||
else if (key === "./login.mjs") module = sourceModule(LOGIN_FILE, "", loginUrl)
|
||||
else if (key === "./re2-pattern.mjs") module = sourceModule(RE2_PATTERN_FILE, "", re2Url)
|
||||
else if (key === "./step-usage.mjs") module = sourceModule(STEP_USAGE_FILE, "", stepUsageUrl)
|
||||
else if (key === "./signin.mjs") module = sourceModule(SIGNIN_FILE, "", signinUrl)
|
||||
else if (key === "./tool-schema.mjs") module = sourceModule(TOOL_SCHEMA_FILE, "", toolSchemaUrl)
|
||||
else if (key.startsWith("node:")) module = builtinModule(key, overrides[key])
|
||||
else throw new Error(`testkit: 未登记的依赖 ${specifier}`)
|
||||
|
||||
+110
-11
@@ -7,6 +7,7 @@ import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { test } from "node:test"
|
||||
import { createUsageReader, fetchUsage, parseUsageReport } from "../usage.mjs"
|
||||
import { forgetStoredSignIn } from "../signin.mjs"
|
||||
|
||||
const report = groups => ({ status: "SUCCESS", command: { name: "usage", data: { groups } } })
|
||||
const group = (buckets, name = "Gemini Models") => ({ name, buckets })
|
||||
@@ -211,7 +212,8 @@ else if (version) {
|
||||
const env = { ...process.env, TEST_LOG: logPath, TEST_REPORT: JSON.stringify(report([group([bucket()])])), TEST_DESCENDANT: path.join(directory, "descendant"), ...extraEnv }
|
||||
return {
|
||||
executable, env,
|
||||
options: { env, tempRoot: directory },
|
||||
// agy's stored sign-in can't be read here (signin.mjs is tested on its own)
|
||||
options: { env, tempRoot: directory, signIn: async () => ({ state: "unknown" }) },
|
||||
async logs() { return (await fs.readFile(logPath, "utf8")).trim().split("\n").map(line => JSON.parse(line)) },
|
||||
// Every pid to see gone after a kill: the spawned children, and the agy
|
||||
// each one ran that got as far as logging (on Windows a grandchild under
|
||||
@@ -476,27 +478,124 @@ test("only concurrent refreshes share work, and callers cannot mutate each other
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("reports sanitized failures and preserves the bridge sign-in; failures are retryable", async t => {
|
||||
for (const [message, expected] of [
|
||||
["Not logged in secret@example.com https://secret.invalid/token", /sign in again/],
|
||||
["Eligibility check failed: EOF secret@example.com", /eligibility check failed on a network/],
|
||||
["not eligible secret@example.com", /not eligible/],
|
||||
["connection refused: secret@example.com https://secret.invalid", /network or proxy/],
|
||||
["unrecognized secret@example.com", /could not read usage/],
|
||||
test("reports sanitized failures and preserves the bridge sign-in; failures back off, then are retried", async t => {
|
||||
for (const [message, expected, signIn] of [
|
||||
["Not logged in secret@example.com https://secret.invalid/token", /sign in again/, "expired"],
|
||||
["Eligibility check failed: EOF secret@example.com", /eligibility check failed on a network/, "kept"],
|
||||
["not eligible secret@example.com", /not eligible/, "kept"],
|
||||
["connection refused: secret@example.com https://secret.invalid", /network or proxy/, "kept"],
|
||||
["unrecognized secret@example.com", /could not read usage/, "kept"],
|
||||
]) {
|
||||
const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: message })
|
||||
const read = createUsageReader(() => f.executable, f.options)
|
||||
let clock = 1_000_000
|
||||
const read = createUsageReader(() => f.executable, { ...f.options, now: () => clock })
|
||||
const result = await read()
|
||||
assert.deepEqual(result.windows, [])
|
||||
assert.equal(result.signIn, "kept")
|
||||
assert.equal(result.signIn, signIn)
|
||||
assert.match(result.error, expected)
|
||||
assert.doesNotMatch(result.error, /secret|https:/)
|
||||
const runs = (await f.logs()).length
|
||||
f.env.TEST_MODE = ""
|
||||
assert.equal((await read()).windows.length, 1)
|
||||
// held: agy isn't run again until the backoff ends
|
||||
const again = await read()
|
||||
assert.deepEqual(again.windows, [])
|
||||
assert.equal(again.error, result.error)
|
||||
assert.equal((await f.logs()).length, runs)
|
||||
clock += 10 * 60 * 1000
|
||||
const ok = await read()
|
||||
assert.equal(ok.windows.length, 1)
|
||||
assert.equal(ok.signIn, signIn === "expired" ? "renewed" : "kept")
|
||||
await f.assertClean()
|
||||
}
|
||||
})
|
||||
|
||||
test("backoff doubles per failure up to six hours", async t => {
|
||||
const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: "unrecognized" })
|
||||
let clock = 0
|
||||
const read = createUsageReader(() => f.executable, { ...f.options, now: () => clock })
|
||||
const minute = 60 * 1000
|
||||
const runs = async () => (await f.logs()).filter(l => l.args[0] !== "--version").length
|
||||
await read()
|
||||
for (const wait of [10, 20, 40, 80, 160, 320, 360, 360]) {
|
||||
const before = await runs()
|
||||
clock += (wait - 1) * minute
|
||||
await read()
|
||||
assert.equal(await runs(), before, `run again before ${wait} minutes`)
|
||||
clock += minute
|
||||
await read()
|
||||
assert.equal(await runs(), before + 1, `not run again after ${wait} minutes`)
|
||||
}
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("never runs agy while it has no stored sign-in, or one that ended with nothing to renew it", async t => {
|
||||
const f = await fixture(t)
|
||||
const ended = { state: "present", fp: "a", canRenew: false, expiresAt: 1, expired: true }
|
||||
for (const stored of [{ state: "missing" }, ended]) {
|
||||
let reads = 0
|
||||
const read = createUsageReader(() => f.executable, { ...f.options, signIn: async () => { reads++; return stored } })
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const result = await read()
|
||||
assert.deepEqual(result.windows, [])
|
||||
assert.equal(result.signIn, "expired")
|
||||
assert.match(result.error, /sign in again|Sign in again/i)
|
||||
}
|
||||
assert.equal(reads, 3)
|
||||
}
|
||||
await assert.rejects(f.logs(), { code: "ENOENT" })
|
||||
// signing in again: agy runs, and the sign-in reads as renewed
|
||||
let stored = { state: "missing" }
|
||||
const read = createUsageReader(() => f.executable, { ...f.options, signIn: async () => stored })
|
||||
assert.equal((await read()).signIn, "expired")
|
||||
stored = { state: "present", fp: "b", canRenew: true, expiresAt: 1, expired: true }
|
||||
const back = await read()
|
||||
assert.equal(back.windows.length, 1)
|
||||
assert.equal(back.signIn, "renewed")
|
||||
assert.equal((await read()).signIn, "kept")
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("a sign-in agy failed on isn't run again in the background until another is stored", async t => {
|
||||
forgetStoredSignIn({ dead: true })
|
||||
t.after(() => forgetStoredSignIn({ dead: true }))
|
||||
const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: "You are not logged in. Please sign in." })
|
||||
let clock = 0
|
||||
let stored = { state: "present", fp: "old", canRenew: true, expiresAt: 1, expired: true }
|
||||
const read = createUsageReader(() => f.executable, { ...f.options, now: () => clock, signIn: async () => stored })
|
||||
assert.equal((await read()).signIn, "expired")
|
||||
const runs = (await f.logs()).length
|
||||
f.env.TEST_MODE = ""
|
||||
clock += 7 * 60 * 60 * 1000
|
||||
const held = await read()
|
||||
assert.equal(held.signIn, "expired")
|
||||
assert.equal((await f.logs()).length, runs)
|
||||
stored = { ...stored, fp: "new", expired: false }
|
||||
const back = await read()
|
||||
assert.equal(back.windows.length, 1)
|
||||
assert.equal(back.signIn, "renewed")
|
||||
await f.assertClean()
|
||||
})
|
||||
|
||||
test("a run that hangs with an ended access token and says nothing marks the sign-in dead", async t => {
|
||||
forgetStoredSignIn({ dead: true })
|
||||
t.after(() => forgetStoredSignIn({ dead: true }))
|
||||
const f = await fixture(t, { TEST_MODE: "hang" })
|
||||
const stored = { state: "present", fp: "hung", canRenew: true, expiresAt: 1, expired: true }
|
||||
const read = createUsageReader(() => f.executable, { ...f.options, timeoutMs: 3000, signIn: async () => stored })
|
||||
const result = await read()
|
||||
assert.equal(result.signIn, "expired")
|
||||
const runs = (await f.logs()).length
|
||||
assert.equal((await read()).signIn, "expired")
|
||||
assert.equal((await f.logs()).length, runs)
|
||||
// a hang with a live access token is a hang, not a sign-in
|
||||
const g = await fixture(t, { TEST_MODE: "hang" })
|
||||
const live = { state: "present", fp: "live", canRenew: true, expiresAt: Date.now() + 3600_000, expired: false }
|
||||
const other = await createUsageReader(() => g.executable, { ...g.options, timeoutMs: 3000, signIn: async () => live })()
|
||||
assert.equal(other.signIn, "kept")
|
||||
await f.assertClean()
|
||||
await g.assertClean()
|
||||
})
|
||||
|
||||
test("invalid and oversized stdout/stderr reports fail within the output budget", async t => {
|
||||
for (const [mode, expected, maxOutputBytes] of [
|
||||
["malformed", /invalid usage report/, undefined],
|
||||
|
||||
@@ -3,19 +3,31 @@ 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
|
||||
|
||||
class UsageError extends Error {}
|
||||
// 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.")
|
||||
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)
|
||||
@@ -165,7 +177,10 @@ function run(file, args, { cwd, env, deadline, signal, maxOutputBytes, onTreeKil
|
||||
if (error) reject(error)
|
||||
else resolve(result)
|
||||
}
|
||||
const abort = () => finish(new UsageError("agy usage query was cancelled."))
|
||||
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 {
|
||||
@@ -183,7 +198,7 @@ function run(file, args, { cwd, env, deadline, signal, maxOutputBytes, onTreeKil
|
||||
return
|
||||
}
|
||||
signal?.addEventListener("abort", abort, { once: true })
|
||||
timer = setTimeout(() => finish(new UsageError("agy usage query timed out.")), Math.max(1, deadline - Date.now()))
|
||||
timer = setTimeout(late, Math.max(1, deadline - Date.now()))
|
||||
const collect = chunks => chunk => {
|
||||
if (settled) return
|
||||
bytes += chunk.length
|
||||
@@ -245,7 +260,11 @@ export async function fetchUsage(agy, {
|
||||
BROWSER: path.join(directory, process.platform === "win32" ? "open.cmd" : "open"),
|
||||
})
|
||||
const options = { cwd: directory, env: childEnv, deadline, signal, maxOutputBytes, onTreeKill: p => { pendingTreeKill = p } }
|
||||
const version = await run(agy, ["--version"], { ...options, deadline: Math.min(deadline, Date.now() + 3000) })
|
||||
// --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)
|
||||
@@ -269,21 +288,72 @@ export async function fetchUsage(agy, {
|
||||
}
|
||||
}
|
||||
|
||||
// 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, options).finally(() => {
|
||||
const query = fetchUsage(agy, fetchOptions).finally(() => {
|
||||
if (pending.get(agy) === query) pending.delete(agy)
|
||||
})
|
||||
pending.set(agy, query)
|
||||
}
|
||||
return { ...structuredClone(await pending.get(agy)), signIn: "kept" }
|
||||
const result = { ...structuredClone(await pending.get(agy)), signIn: saidExpired ? "renewed" : "kept" }
|
||||
held = null
|
||||
saidExpired = false
|
||||
return result
|
||||
} catch (error) {
|
||||
return { windows: [], error: error instanceof UsageError ? error.message : "agy usage query failed. Check the CLI and temporary-directory permissions.", signIn: "kept" }
|
||||
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" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user