mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
* fix(usage): read OpenCode Go logins from the store the installed OpenCode uses The source treated a `credential` table in opencode.db as proof of OpenCode 2 and then ignored auth.json. OpenCode 1.17.5 and newer creates that table too and leaves it empty, and OpenCode 2 fills it once when it opens the same data directory. In both cases the Go key in auth.json was dropped and the source disappeared. The source no longer reads OpenCode's database. It asks the installed OpenCode for its version. OpenCode 2 lists its own logins with `opencode auth export --standalone`, with its own choice of the active one per integration. OpenCode 1 keeps logins in auth.json. A failed OpenCode 2 listing throws, so it never reads as "no login". An auth.json key is not used when OpenCode 2 is installed, because OpenCode 2 never reads that file after its one-time import. `--standalone` matters: without it the command starts OpenCode's background service and leaves it running. * chore(usage): request a review of the resolved threads * fix(usage): keep the OpenCode Go card when the version check is cut off A version check that reached its timeout was read as OpenCode 1. Discovery then read auth.json, and a login that only OpenCode 2 has was reported as removed. A check that is cut off does not show which store OpenCode uses, so discovery now fails and the daemon keeps the account it already knew. A missing OpenCode, or one that exits with an error, still reads auth.json: that file is the only store when OpenCode is not installed. * fix(usage): recognize OpenCode 2 when the daemon's environment forces colors With FORCE_COLOR set, OpenCode 2 writes its version with ANSI codes even into a pipe. The version did not parse, the source took OpenCode for version 1, and a login that only OpenCode 2 has disappeared. The source now runs OpenCode with NO_COLOR, which gives plain output for the version and the login listing. * fix(usage): read the auth.json Go key when OpenCode 2 has no Go login OpenCode 2 imports auth.json only once. A Go key that is saved in the file after that import is in no other place, so the card was still missing for the state in #10659 when the installed OpenCode is 2.x: the credential listing holds only an unrelated login and the Go key is in auth.json. The order is now: a login OpenCode 2 can serve Go with wins, so a stale key in the file never replaces it. Without one, the auth.json key is used. A failed listing still throws, because it does not show that OpenCode 2 has no Go login. * fix(usage): read the auth.json Go key behind an OpenCode 2 login without Go The auth.json fallback applied only when OpenCode 2 listed neither an `opencode` nor an `opencode-go` login. With an `opencode` login whose Console workspace has no Go, the card reported "No active OpenCode Go subscription" while a working Go key was in auth.json. The file's key now stands in for a missing `opencode-go` login. The existing order then decides: the `opencode` login is asked first, and the Go key is asked only when the Console refuses that login. A temporary failure still keeps the card on the `opencode` login.
134 lines
5.3 KiB
TypeScript
134 lines
5.3 KiB
TypeScript
import { z } from "zod";
|
|
import {
|
|
hashAccountKey,
|
|
unavailable,
|
|
type UsageAccount,
|
|
toneFromUsedPct,
|
|
windowFromUsedPct,
|
|
type UsageReport,
|
|
} from "@getpaseo/plugin/server/usage";
|
|
import type { Input } from "../shared/input.js";
|
|
import { NO_SUBSCRIPTION, readConsoleGo } from "./console.js";
|
|
import { installedOpenCode, loginStore, readLogins, type GoCredential } from "./opencode.js";
|
|
|
|
const windowSchema = z.object({
|
|
status: z.enum(["ok", "rate-limited"]),
|
|
percent: z.number().finite(),
|
|
resetsAt: z.iso.datetime(),
|
|
});
|
|
const responseSchema = z.object({
|
|
usage: z.object({ rolling: windowSchema, weekly: windowSchema, monthly: windowSchema }),
|
|
});
|
|
|
|
export async function discover(install = installedOpenCode()): Promise<UsageAccount[]> {
|
|
const store = await loginStore(install);
|
|
const logins = await readLogins(install, store);
|
|
if (!logins.opencode && !logins.go) return [];
|
|
// One OpenCode data directory holds one Go login, whichever store it lives in. Usage settings
|
|
// are saved per account, so a login OpenCode 2 imports keeps the identity it had in auth.json.
|
|
return [{ key: hashAccountKey(install.authFile), input: { store } }];
|
|
}
|
|
|
|
export async function fetchUsage(
|
|
input: Input,
|
|
fetchApi: typeof fetch = fetch,
|
|
install = installedOpenCode(),
|
|
): Promise<UsageReport> {
|
|
const logins = await readLogins(install, input.store);
|
|
const only = logins.opencode ?? logins.go;
|
|
if (!only) throw new Error("OpenCode Go login no longer exists");
|
|
if (logins.opencode && logins.go) return readEitherLogin(logins.opencode, logins.go, fetchApi);
|
|
return readCredential(only, fetchApi, { workspaceKey: only === logins.opencode });
|
|
}
|
|
|
|
/**
|
|
* OpenCode serves Go with the `opencode` credential whenever that Console workspace has Go, so
|
|
* the card follows it. The `opencode-go` key serves Go when the Console refuses that credential.
|
|
* A temporary failure keeps OpenCode on the `opencode` credential, so it throws instead.
|
|
*/
|
|
async function readEitherLogin(
|
|
opencode: GoCredential,
|
|
go: GoCredential,
|
|
fetchApi: typeof fetch,
|
|
): Promise<UsageReport> {
|
|
if (opencode.type === "console") {
|
|
const signIn = await readSignIn(opencode, fetchApi);
|
|
if (signIn.status !== "unavailable") return signIn;
|
|
const fallback = await readCredential(go, fetchApi);
|
|
// A connected Console account explains a rejected fallback key better than the key does.
|
|
return isRejected(fallback) ? signIn : fallback;
|
|
}
|
|
const primary = await readCredential(opencode, fetchApi, { workspaceKey: true });
|
|
return primary.status === "unavailable" ? readCredential(go, fetchApi) : primary;
|
|
}
|
|
|
|
function readCredential(
|
|
credential: GoCredential,
|
|
fetchApi: typeof fetch,
|
|
options: { workspaceKey?: boolean } = {},
|
|
): Promise<UsageReport> {
|
|
return credential.type === "console"
|
|
? readSignIn(credential, fetchApi)
|
|
: readKey(credential.key, fetchApi, options);
|
|
}
|
|
|
|
async function readSignIn(
|
|
signIn: Extract<GoCredential, { type: "console" }>,
|
|
fetchApi: typeof fetch,
|
|
): Promise<UsageReport> {
|
|
// OpenCode refreshes the sign-in itself; reading never competes with it.
|
|
if (signIn.expires > 0 && signIn.expires <= Date.now())
|
|
return unavailable({
|
|
kind: "expired",
|
|
expiresAt: new Date(signIn.expires).toISOString(),
|
|
refreshedBy: "opencode",
|
|
});
|
|
return readConsoleGo({ token: signIn.access, orgID: signIn.orgID }, fetchApi);
|
|
}
|
|
|
|
/**
|
|
* A key reads the Console meters first, since the usage API floors each percent. Any Console
|
|
* failure falls through to the usage API, which decides what the key's errors mean. The Console
|
|
* gets a short budget so the usage API still answers within the daemon's 20 second refresh.
|
|
*/
|
|
async function readKey(
|
|
key: string,
|
|
fetchApi: typeof fetch,
|
|
{ workspaceKey = false }: { workspaceKey?: boolean } = {},
|
|
): Promise<UsageReport> {
|
|
const fromConsole = await readConsoleGo({ token: key }, fetchApi, 3_000).catch(() => null);
|
|
if (fromConsole?.status === "available") return fromConsole;
|
|
const response = await fetchApi("https://opencode.ai/zen/go/v1/usage", {
|
|
headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
|
|
signal: AbortSignal.timeout(15_000),
|
|
});
|
|
// The usage API accepts any key of a Console workspace and refuses one without Go.
|
|
if (response.status === 403 && workspaceKey) return NO_SUBSCRIPTION;
|
|
if (response.status === 401 || response.status === 403)
|
|
return unavailable({ kind: "rejected", status: response.status, refreshedBy: "opencode" });
|
|
if (!response.ok) throw new Error(`OpenCode Go usage API returned ${response.status}`);
|
|
const data = responseSchema.parse(await response.json());
|
|
const windows = (
|
|
[
|
|
// The rolling window's length is not reported, so its percent stands without a name.
|
|
["rolling", "Rolling", "", data.usage.rolling],
|
|
["weekly", "Weekly", "wk", data.usage.weekly],
|
|
["monthly", "Monthly", "mo", data.usage.monthly],
|
|
] as const
|
|
).map(([id, label, shortLabel, value]) =>
|
|
windowFromUsedPct({
|
|
id,
|
|
label,
|
|
shortLabel,
|
|
utilizationPct: value.percent,
|
|
resetsAt: value.resetsAt,
|
|
tone: toneFromUsedPct(value.percent),
|
|
}),
|
|
);
|
|
return { status: "available", planLabel: "Go", windows };
|
|
}
|
|
|
|
function isRejected(report: UsageReport): boolean {
|
|
return report.status === "unavailable" && report.problem.kind === "rejected";
|
|
}
|