gcp-ai 0.1.1: a Windows sign-in reaches gcloud by its own path, and an expiring credit is spendable (#409)

gcp-ai 0.1.1: on Windows, gcloud.cmd is started by its own path (CLOUDSDK_ROOT_DIR, then PATH, quoted entries included), so the batch file's %~dp0 is its own directory and gcloud finds its library. A credit whose status reads "Expiring in N days" counts as spendable until its end date.

Run at 66279e97 (macOS): node --test packages/gcp-ai/test: 44 pass, 3 skipped (Windows-only); origin/main 40 pass. bun scripts/check.mjs gcp-ai ok. The earlier review reproduced the %~dp0 cause and fix on Windows 11 with a fake gcloud.cmd.
Not tried: the new Windows-only tests on Windows at this head (the box was unreachable); the author ran them on Windows 11 with real gcloud 589.0.0.
This commit is contained in:
tianyuanwang989-prog
2026-10-26 18:05:06 +08:00
committed by GitHub
parent 0ea458b4a5
commit 60a2d6e2e2
4 changed files with 144 additions and 9 deletions
+41 -3
View File
@@ -1,8 +1,9 @@
import { execFile, spawn } from "node:child_process"
import { createHash } from "node:crypto"
import { existsSync } from "node:fs"
import { mkdir, mkdtemp, readFile, readdir, rename, rm, stat } from "node:fs/promises"
import { homedir } from "node:os"
import { dirname, join } from "node:path"
import { delimiter, dirname, join } from "node:path"
import { promisify } from "node:util"
import { configRoot, expandPath, home, openSignInWindow, validateProject } from "./browser.mjs"
@@ -50,12 +51,49 @@ function gcloudEnvironment(options = {}) {
// argument that could not be carried is refused rather than handed over.
const WINDOWS = process.platform === "win32"
function command(name, args) {
// The command line for cmd.exe. The program and every argument are quoted,
// and the whole line is quoted once more: cmd's /s takes the outer pair off,
// and what is left is the program and its arguments as separate tokens.
export function windowsCommand(program, args) {
const quoted = [program, ...args].map((value) => `"${value}"`).join(" ")
return ["/d", "/s", "/c", `"${quoted}"`]
}
// Where gcloud.cmd is, as the command line has to name it.
//
// The program is named by its own path, not by the name it happens to have on
// PATH. A batch file takes the Cloud SDK root from the directory it was
// started in (%~dp0); started by name, it has no directory of its own there,
// and that is the caller's, so gcloud looks for its own library under the
// caller's directory and fails to start, with nothing in its output to say
// why.
//
// CLOUDSDK_ROOT_DIR is the variable the Cloud SDK itself sets, so it names the
// same installation the SDK reports. A PATH entry may be quoted
// ("C:\Program Files\..."), and the quotes are not part of the directory. The
// environment is an argument so that this can be read on any platform.
export function gcloudProgram(env = process.env) {
const root = env.CLOUDSDK_ROOT_DIR
if (root) {
const candidate = join(root, "bin", "gcloud.cmd")
if (existsSync(candidate)) return candidate
}
for (const entry of (env.PATH || "").split(delimiter)) {
const dir = entry.trim().replace(/^"(.*)"$/, "$1")
if (!dir) continue
const candidate = join(dir, "gcloud.cmd")
if (existsSync(candidate)) return candidate
}
return "gcloud"
}
export function command(name, args) {
if (!WINDOWS) return { file: name, args, options: {} }
for (const value of [name, ...args]) {
if (/["\r\n]/.test(value)) throw new Error(`Cannot run ${name} on Windows: an argument contains a quote or a line break`)
}
return { file: process.env.ComSpec || "cmd.exe", args: ["/d", "/s", "/c", `"${[name, ...args].map((value) => `"${value}"`).join(" ")}"`], options: { windowsVerbatimArguments: true } }
const program = name.toLowerCase() === "gcloud" ? gcloudProgram() : name
return { file: process.env.ComSpec || "cmd.exe", args: windowsCommand(program, args), options: { windowsVerbatimArguments: true } }
}
export async function runGcloud(args, options = {}) {
+14 -3
View File
@@ -30,6 +30,16 @@ const isoDate = (value) => {
export function parseCreditTables(tables, { now = Date.now() } = {}) {
const credits = new Map()
let recognized = false
// A credit's status is a small vocabulary that Google grows over time: a
// credit that reads "Active" a month before its end date reads "Expiring in
// 24 days" in the month of it. That wording is a fact about time rather
// than about the money, so it is recognized as the state it means (still
// spendable, with the end date deciding eligibility) instead of being
// refused as a status this parser has never seen. "Expired" stays a
// different state.
const spent = ["exhausted", "used up", "used"]
const usable = ["available", "active", ...spent]
const known = [...usable, "expired", "pending"]
for (const table of tables) {
const headers = table.headers.map(normalize)
const indices = Object.fromEntries(["credit name", "status", "remaining value", "original value", "credit id", "start date", "end date", "usage scope"].map((name) => [name, column(headers, name)]))
@@ -38,16 +48,17 @@ export function parseCreditTables(tables, { now = Date.now() } = {}) {
for (const row of table.rows) {
const cell = (name) => normalize(row[indices[name]])
const status = cell("status").toLowerCase()
if (!["available", "active", "exhausted", "used up", "used", "expired", "pending"].includes(status)) throw new Error(`Unknown Google Cloud credit status: ${cell("status")}`)
const expiring = /^(?:expiring|expires)\b/.test(status)
if (!known.includes(status) && !expiring) throw new Error(`Unknown Google Cloud credit status: ${cell("status")}`)
const id = cell("credit id")
if (!id || credits.has(id)) continue
const reported = money(cell("remaining value"))
const original = money(cell("original value"))
if (!Number.isSafeInteger(reported) || !Number.isSafeInteger(original) || reported < 0 || reported > original) throw new Error("Invalid Google Cloud credit amounts")
const remaining = ["exhausted", "used up", "used"].includes(status) ? 0 : reported
const remaining = spent.includes(status) ? 0 : reported
const start = isoDate(cell("start date"))
const end = isoDate(cell("end date"))
const eligible = ["available", "active", "exhausted", "used up", "used"].includes(status) && !(start && Date.parse(start) > now) && !(end && Date.parse(end) <= now)
const eligible = (usable.includes(status) || expiring) && !(start && Date.parse(start) > now) && !(end && Date.parse(end) <= now)
credits.set(id, { id, name: cell("credit name"), status: cell("status"), remaining: remaining / 100, original: original / 100, start, end, scope: cell("usage scope"), eligible })
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-gcp-ai-auth",
"version": "0.1.0",
"version": "0.1.1",
"description": "Vertex AI models and Google Cloud promotional credits, signed with your own gcloud / ADC login",
"type": "module",
"main": "./index.mjs",
+88 -2
View File
@@ -3,11 +3,13 @@ import assert from "node:assert/strict"
import test from "node:test"
import plugin from "../index.mjs"
import { createHash } from "node:crypto"
import { execFile } from "node:child_process"
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { dirname, join } from "node:path"
import { delimiter, dirname, join } from "node:path"
import { EventEmitter } from "node:events"
import { accountOf, adcDirectoryFor, adcDirectoryOwnedBy, adcDirectoryToCreate, adcFile, adcSlug, beginAdcLogin, effectiveAuthMode, hasAdc, resolveAccount, resolveIdentity, resolveProject, runGcloud, startLogin, tokenProvider } from "../lib/credentials.mjs"
import { promisify } from "node:util"
import { accountOf, adcDirectoryFor, adcDirectoryOwnedBy, adcDirectoryToCreate, adcFile, adcSlug, beginAdcLogin, command, effectiveAuthMode, gcloudProgram, hasAdc, resolveAccount, resolveIdentity, resolveProject, runGcloud, startLogin, tokenProvider, windowsCommand } from "../lib/credentials.mjs"
import { fakeGcloud } from "./gcloud.mjs"
import { parseCreditTables, usageOf } from "../lib/credits.mjs"
import { availableModels, toProviderModels } from "../lib/models.mjs"
@@ -52,6 +54,90 @@ test("credits fail closed on missing layout, unknown statuses, unsupported curre
assert.equal(parseCreditTables([{ headers, rows: [row("a", "$10.00", "$10.00", "Expired")] }], { now }).remaining, 0)
})
test("a credit near its end date reads as expiring, and is still spendable", () => {
const result = parseCreditTables([{ headers, rows: [row("expiring", "$229.42", "$300.00", "Expiring in 24 days", "August 20, 2026", "November 20, 2026")] }], { now })
assert.equal(result.remaining, 229.42)
assert.equal(result.original, 300)
assert.equal(result.runsOutAt, "2026-11-20T00:00:00.000Z")
assert.equal(result.credits[0].eligible, true)
assert.equal(result.credits[0].status, "Expiring in 24 days")
})
test("a credit whose end date has passed is not spendable whatever its status says", () => {
const result = parseCreditTables([{ headers, rows: [row("gone", "$10.00", "$10.00", "Expiring in 1 day", "August 20, 2025", "November 20, 2025")] }], { now })
assert.equal(result.credits[0].eligible, false)
assert.equal(result.remaining, 0)
})
test("the Windows command line quotes the program and every argument", () => {
const program = "C:\\Program Files\\Google\\Cloud SDK\\google-cloud-sdk\\bin\\gcloud.cmd"
assert.deepEqual(windowsCommand(program, ["auth", "application-default", "login"]), ["/d", "/s", "/c", `""${program}" "auth" "application-default" "login""`])
})
test("gcloud is found on PATH and named by its own path", async () => {
const root = await mkdtemp(join(tmpdir(), "magpie-gcloud-path-"))
const bin = join(root, "Cloud SDK")
const sdk = join(root, "sdk")
try {
await mkdir(bin, { recursive: true })
await writeFile(join(bin, "gcloud.cmd"), "@echo off\r\n")
await mkdir(join(sdk, "bin"), { recursive: true })
await writeFile(join(sdk, "bin", "gcloud.cmd"), "@echo off\r\n")
// A PATH entry may be quoted, and the quotes are not part of the directory.
assert.equal(gcloudProgram({ PATH: `"${bin}"` }), join(bin, "gcloud.cmd"))
assert.equal(gcloudProgram({ PATH: [bin, root].join(delimiter) }), join(bin, "gcloud.cmd"))
// The SDK's own root variable names the same installation the SDK reports.
assert.equal(gcloudProgram({ CLOUDSDK_ROOT_DIR: sdk }), join(sdk, "bin", "gcloud.cmd"))
// Nothing to find: the name is left to the shell.
assert.equal(gcloudProgram({ PATH: root }), "gcloud")
assert.equal(gcloudProgram({}), "gcloud")
} finally {
await rm(root, { recursive: true, force: true })
}
})
test("a Windows sign-in names gcloud by its own path, so the batch file finds its Cloud SDK root", { skip: process.platform !== "win32" }, async () => {
const root = await mkdtemp(join(tmpdir(), "magpie-gcloud-cwd-"))
const bin = join(root, "Cloud SDK")
const elsewhere = join(root, "somewhere else")
await mkdir(bin, { recursive: true })
await mkdir(elsewhere, { recursive: true })
// A batch file prints the directory it was started in, and gcloud takes its
// Cloud SDK root from there.
await writeFile(join(bin, "gcloud.cmd"), "@echo off\r\necho dp0=%~dp0\r\n")
const path = process.env.PATH
const sdkRoot = process.env.CLOUDSDK_ROOT_DIR
process.env.PATH = bin
delete process.env.CLOUDSDK_ROOT_DIR
try {
// The batch file sees its own directory. Started by name it would see the
// caller's, which is where gcloud looks for its library and finds nothing.
const stdout = await runGcloud(["version"])
assert.ok(stdout.includes(bin), `expected the script's own directory, got ${stdout}`)
assert.ok(!stdout.includes(elsewhere), `expected not the caller's directory, got ${stdout}`)
// And the command line that got there names the file, not the name it has
// on PATH.
const started = command("gcloud", ["version"])
assert.ok(started.args[3].includes(bin), `the command line names ${started.args[3]}`)
} finally {
if (path === undefined) delete process.env.PATH
else process.env.PATH = path
if (sdkRoot !== undefined) process.env.CLOUDSDK_ROOT_DIR = sdkRoot
await rm(root, { recursive: true, force: true })
}
})
test("a Windows command line built this way starts the program it names", { skip: process.platform !== "win32" }, async () => {
const script = join(tmpdir(), `magpie-windows-command-${process.pid}.cmd`)
await writeFile(script, "@echo off\r\necho started\r\n")
try {
const { stdout } = await promisify(execFile)(process.env.ComSpec || "cmd.exe", windowsCommand(script, []), { windowsVerbatimArguments: true })
assert.match(stdout, /started/)
} finally {
await rm(script, { force: true })
}
})
test("session checking recovers from navigation context loss within the same deadline", async () => {
let attempts = 0
let disposed = false