mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Show OpenCode Go usage for the credential OpenCode serves Go with (#10612)
* fix(usage): follow the OpenCode credential that serves Go OpenCode 2 serves OpenCode Go with the active credential on the opencode integration when that Console workspace has Go, and uses the opencode-go key only otherwise. The usage card now reads the same credential: a Console sign-in (with its organization) first, then a key on opencode, then the opencode-go key. Keys read the Console Go status before the usage API, which floors each percent. Refs #6428 * fix(usage): keep OpenCode Go usage on the sign-in through outages A Console outage no longer shows the fallback key's usage, and a slow Console probe no longer uses up the refresh deadline for a working key. * fix(usage): skip OpenCode keys saved for another Console A key on the opencode integration can name its own Console server. Usage now leaves it alone instead of sending it to opencode.ai.
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
toneFromUsedPct,
|
||||
unavailable,
|
||||
windowFromUsedPct,
|
||||
type UsageReport,
|
||||
type UsageWindow,
|
||||
} from "@getpaseo/plugin/server/usage";
|
||||
|
||||
// The endpoint the Console's own Go page reads. It is not publicly documented.
|
||||
const STATUS_URL = "https://opencode.ai/console/api/go/status";
|
||||
const GO_PRODUCTS = new Set(["go", "go-plus", "go-teams"]);
|
||||
export const NO_SUBSCRIPTION = unavailable({
|
||||
kind: "no_quota",
|
||||
detail: "No active OpenCode Go subscription",
|
||||
});
|
||||
|
||||
const amount = z.union([z.string(), z.number()]).transform(Number);
|
||||
const meterSchema = z.object({
|
||||
limitMicroCents: amount,
|
||||
usedMicroCents: amount,
|
||||
resetsAt: z.iso.datetime(),
|
||||
});
|
||||
const statusSchema = z.object({
|
||||
product: z.string().nullish(),
|
||||
// An ended or refunded subscription keeps its product and sends no access.
|
||||
access: z
|
||||
.object({
|
||||
meters: z.object({
|
||||
fiveHour: z.unknown().optional(),
|
||||
week: z.unknown().optional(),
|
||||
month: z.unknown().optional(),
|
||||
}),
|
||||
})
|
||||
.nullish(),
|
||||
});
|
||||
|
||||
const METERS = [
|
||||
["fiveHour", "rolling", "Rolling", ""],
|
||||
["week", "weekly", "Weekly", "wk"],
|
||||
["month", "monthly", "Monthly", "mo"],
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Reads the Go meters the Console shows. A sign-in names its organization; an API key belongs to
|
||||
* one workspace and sends none. Throws on failures that say nothing about the login.
|
||||
*/
|
||||
export async function readConsoleGo(
|
||||
login: { token: string; orgID?: string },
|
||||
fetchApi: typeof fetch,
|
||||
timeoutMs = 15_000,
|
||||
): Promise<UsageReport> {
|
||||
const response = await fetchApi(STATUS_URL, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${login.token}`,
|
||||
Accept: "application/json",
|
||||
...(login.orgID ? { "x-org-id": login.orgID } : {}),
|
||||
},
|
||||
// The token goes to the Console origin only.
|
||||
redirect: "error",
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (response.status === 401 || response.status === 403)
|
||||
return unavailable({ kind: "rejected", status: response.status, refreshedBy: "opencode" });
|
||||
if (!response.ok) throw new Error(`OpenCode Console Go status returned ${response.status}`);
|
||||
const status = statusSchema.parse(await response.json());
|
||||
if (!status.product || !GO_PRODUCTS.has(status.product) || !status.access) return NO_SUBSCRIPTION;
|
||||
const windows = METERS.flatMap(([meter, id, label, shortLabel]): UsageWindow[] => {
|
||||
const parsed = meterSchema.safeParse(status.access?.meters[meter]);
|
||||
if (!parsed.success) return [];
|
||||
const { limitMicroCents: limit, usedMicroCents: used, resetsAt } = parsed.data;
|
||||
if (!(limit > 0) || !(used >= 0)) return [];
|
||||
const usedPct = Math.min(100, (used / limit) * 100);
|
||||
return [
|
||||
windowFromUsedPct({
|
||||
id,
|
||||
label,
|
||||
shortLabel,
|
||||
utilizationPct: usedPct,
|
||||
resetsAt,
|
||||
tone: toneFromUsedPct(usedPct),
|
||||
}),
|
||||
];
|
||||
});
|
||||
if (!windows.length) throw new Error("OpenCode Console Go status has no readable meters");
|
||||
return { status: "available", planLabel: "Go", windows };
|
||||
}
|
||||
@@ -11,19 +11,42 @@ interface Database {
|
||||
interface Sqlite {
|
||||
DatabaseSync: new (path: string, options: { readOnly: boolean }) => Database;
|
||||
}
|
||||
interface DatabaseLogin {
|
||||
key: string | null;
|
||||
}
|
||||
export interface StorePaths {
|
||||
file: string;
|
||||
database: string;
|
||||
}
|
||||
|
||||
/** A credential OpenCode can serve Go with. Anything else on the integration is ignored. */
|
||||
export type GoCredential =
|
||||
| { type: "key"; key: string }
|
||||
| { type: "console"; access: string; expires: number; orgID: string };
|
||||
|
||||
/** The selected credential on each integration that can carry OpenCode Go. */
|
||||
export interface DatabaseLogins {
|
||||
/** OpenCode binds Go to this integration when the Console workspace has Go. */
|
||||
opencode: GoCredential | null;
|
||||
go: GoCredential | null;
|
||||
}
|
||||
|
||||
const CONSOLE_SERVER = "https://opencode.ai/console";
|
||||
const ORGANIZATION_ID = /^(?:org|wrk)_[A-Za-z0-9]+$/;
|
||||
|
||||
const fileSchema = z.object({
|
||||
"opencode-go": z.object({ type: z.literal("api"), key: z.string().min(1) }).optional(),
|
||||
});
|
||||
const rowSchema = z.object({ value: z.string() });
|
||||
const keySchema = z.object({ type: z.literal("key"), key: z.string().min(1) });
|
||||
const metadataSchema = z
|
||||
.object({ server: z.string().optional(), orgID: z.string().optional() })
|
||||
.optional();
|
||||
const credentialSchema = z.discriminatedUnion("type", [
|
||||
z.object({ type: z.literal("key"), key: z.string().min(1), metadata: metadataSchema }),
|
||||
z.object({
|
||||
type: z.literal("oauth"),
|
||||
access: z.string().min(1),
|
||||
expires: z.number(),
|
||||
metadata: metadataSchema,
|
||||
}),
|
||||
]);
|
||||
|
||||
export function defaultStorePaths(env: NodeJS.ProcessEnv = process.env): StorePaths {
|
||||
const dataHome = env.XDG_DATA_HOME || join(env.HOME || homedir(), ".local", "share");
|
||||
@@ -41,7 +64,8 @@ export async function readFileKey(path: string): Promise<string | null> {
|
||||
}
|
||||
}
|
||||
|
||||
export function readDatabaseLogin(path: string): DatabaseLogin | null {
|
||||
/** Null when the path is not an OpenCode v2 credential store. */
|
||||
export function readDatabaseLogins(path: string): DatabaseLogins | null {
|
||||
// Keep the legacy source loadable on Node versions without node:sqlite.
|
||||
const sqlite = z
|
||||
.object({
|
||||
@@ -56,24 +80,43 @@ export function readDatabaseLogin(path: string): DatabaseLogin | null {
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'credential'")
|
||||
.all();
|
||||
if (!tables.length) return null;
|
||||
const [value] = db
|
||||
.prepare(
|
||||
// OpenCode also selects migrated rows with no active flag, ordered by creation time.
|
||||
"SELECT value FROM credential WHERE integration_id = ? ORDER BY active DESC, time_created DESC, id DESC LIMIT 1",
|
||||
)
|
||||
.all("opencode-go");
|
||||
const row = rowSchema.safeParse(value);
|
||||
if (!row.success) return { key: null };
|
||||
let credential: unknown;
|
||||
try {
|
||||
credential = JSON.parse(row.data.value);
|
||||
} catch (error) {
|
||||
if (error instanceof SyntaxError) return { key: null };
|
||||
throw error;
|
||||
}
|
||||
const parsed = keySchema.safeParse(credential);
|
||||
return { key: parsed.success ? parsed.data.key : null };
|
||||
return { opencode: selected(db, "opencode"), go: selected(db, "opencode-go") };
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
function selected(db: Database, integrationID: string): GoCredential | null {
|
||||
const [value] = db
|
||||
.prepare(
|
||||
// OpenCode also selects migrated rows with no active flag, ordered by creation time.
|
||||
"SELECT value FROM credential WHERE integration_id = ? ORDER BY active DESC, time_created DESC, id DESC LIMIT 1",
|
||||
)
|
||||
.all(integrationID);
|
||||
const row = rowSchema.safeParse(value);
|
||||
if (!row.success) return null;
|
||||
let credential: unknown;
|
||||
try {
|
||||
credential = JSON.parse(row.data.value);
|
||||
} catch (error) {
|
||||
if (error instanceof SyntaxError) return null;
|
||||
throw error;
|
||||
}
|
||||
const parsed = credentialSchema.safeParse(credential);
|
||||
if (!parsed.success) return null;
|
||||
const { data } = parsed;
|
||||
// A credential for another Console never goes to opencode.ai.
|
||||
if (consoleServer(data.metadata?.server) !== CONSOLE_SERVER) return null;
|
||||
if (data.type === "key") return { type: "key", key: data.key };
|
||||
const orgID = data.metadata?.orgID;
|
||||
if (integrationID !== "opencode" || !orgID || !ORGANIZATION_ID.test(orgID)) return null;
|
||||
return { type: "console", access: data.access, expires: data.expires, orgID };
|
||||
}
|
||||
|
||||
// OpenCode defaults a missing server to the Console and maps the retired host onto it.
|
||||
function consoleServer(server: string | undefined): string {
|
||||
return (server ?? CONSOLE_SERVER).replace(
|
||||
/^https:\/\/console\.opencode\.ai(?=\/|$)/,
|
||||
CONSOLE_SERVER,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -40,6 +40,8 @@ test("discovery input rejects an explicit API key", () => {
|
||||
expect(() => inputSchema.parse({})).toThrow();
|
||||
});
|
||||
|
||||
const CONSOLE_STATUS_URL = "https://opencode.ai/console/api/go/status";
|
||||
const USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
|
||||
const upstreamResponse = {
|
||||
usage: {
|
||||
rolling: { status: "ok", percent: 21, resetsAt: "2026-09-26T20:00:00.000Z" },
|
||||
@@ -56,7 +58,6 @@ test("uses the active v2 Go key instead of a stale legacy key without writing ei
|
||||
);
|
||||
insert.run("inactive", "opencode-go", JSON.stringify({ type: "key", key: "inactive-key" }), 0, 3);
|
||||
insert.run("active", "opencode-go", JSON.stringify({ type: "key", key: "active-key" }), 1, 1);
|
||||
insert.run("zen", "opencode", JSON.stringify({ type: "key", key: "zen-key" }), 1, 4);
|
||||
db.close();
|
||||
const beforeDatabase = await readFile(databasePath);
|
||||
const beforeFile = await readFile(fixturePath);
|
||||
@@ -175,7 +176,28 @@ test("selects the newest created Go key when no explicit active key exists", asy
|
||||
});
|
||||
|
||||
test.each([
|
||||
["other provider", "opencode", 1, JSON.stringify({ type: "key", key: "zen-key" })],
|
||||
["unrelated provider", "anthropic", 1, JSON.stringify({ type: "key", key: "other-key" })],
|
||||
[
|
||||
"Console sign-in on another server",
|
||||
"opencode",
|
||||
1,
|
||||
JSON.stringify({
|
||||
type: "oauth",
|
||||
access: "staging-token",
|
||||
expires: 0,
|
||||
metadata: { server: "https://staging.example.com/console", orgID: "org_TEST" },
|
||||
}),
|
||||
],
|
||||
[
|
||||
"Console key on another server",
|
||||
"opencode",
|
||||
1,
|
||||
JSON.stringify({
|
||||
type: "key",
|
||||
key: "staging-key",
|
||||
metadata: { server: "https://staging.example.com/console" },
|
||||
}),
|
||||
],
|
||||
["Console OAuth", "opencode-go", 1, JSON.stringify({ type: "oauth", access: "oauth-token" })],
|
||||
["malformed credential", "opencode-go", 1, "invalid JSON"],
|
||||
["empty key", "opencode-go", 1, JSON.stringify({ type: "key", key: "" })],
|
||||
@@ -269,7 +291,8 @@ test("discovers and fetches the default key from read-only auth.json", async ()
|
||||
};
|
||||
const report = await fetchUsage({ store: "file", path }, fetchApi);
|
||||
expect(requests).toEqual([
|
||||
{ url: "https://opencode.ai/zen/go/v1/usage", authorization: "Bearer fixture-key" },
|
||||
{ url: CONSOLE_STATUS_URL, authorization: "Bearer fixture-key" },
|
||||
{ url: USAGE_URL, authorization: "Bearer fixture-key" },
|
||||
]);
|
||||
expect(report.status).toBe("available");
|
||||
expect(report.windows.map((window) => [window.id, window.usedPct, window.resetsAt])).toEqual([
|
||||
@@ -333,3 +356,231 @@ test("keeps the account identity when OpenCode v2 imports the legacy Go login",
|
||||
// Usage settings are saved per account, so the card keeps its visibility and position.
|
||||
expect(migrated!.key).toBe(legacy!.key);
|
||||
});
|
||||
|
||||
const consoleSignIn = (overrides: { expires?: number; server?: string } = {}) =>
|
||||
JSON.stringify({
|
||||
type: "oauth",
|
||||
methodID: "device",
|
||||
access: "console-token",
|
||||
refresh: "console-refresh",
|
||||
expires: overrides.expires ?? Date.now() + 3_600_000,
|
||||
metadata: {
|
||||
...(overrides.server ? { server: overrides.server } : {}),
|
||||
orgID: "org_TESTORG123",
|
||||
orgName: "Team",
|
||||
},
|
||||
});
|
||||
const goStatus = (
|
||||
access: unknown = {
|
||||
meters: {
|
||||
fiveHour: {
|
||||
resetsAt: "2026-08-12T12:00:00.000Z",
|
||||
limitMicroCents: "1000000000",
|
||||
usedMicroCents: "250000000",
|
||||
},
|
||||
week: {
|
||||
resetsAt: "2026-08-19T12:00:00.000Z",
|
||||
limitMicroCents: "2000000000",
|
||||
usedMicroCents: "800000000",
|
||||
},
|
||||
month: {
|
||||
resetsAt: "2026-09-01T00:00:00.000Z",
|
||||
limitMicroCents: "6000000000",
|
||||
usedMicroCents: "3000000000",
|
||||
},
|
||||
},
|
||||
},
|
||||
) => ({ product: "go", access });
|
||||
|
||||
interface Request {
|
||||
url: string;
|
||||
authorization: string | null;
|
||||
orgID: string | null;
|
||||
redirect?: RequestRedirect;
|
||||
}
|
||||
/** Answers each URL and bearer token pair, recording what was asked. */
|
||||
function upstream(answers: Record<string, () => Response>) {
|
||||
const requests: Request[] = [];
|
||||
const fetchApi = async (url: string | URL | Request, init?: RequestInit) => {
|
||||
const headers = new Headers(init?.headers);
|
||||
const authorization = headers.get("Authorization");
|
||||
requests.push({
|
||||
url: String(url),
|
||||
authorization,
|
||||
orgID: headers.get("x-org-id"),
|
||||
...(init?.redirect ? { redirect: init.redirect } : {}),
|
||||
});
|
||||
const answer = answers[`${String(url)} ${authorization}`];
|
||||
return answer ? answer() : new Response(null, { status: 401 });
|
||||
};
|
||||
return { requests, fetchApi: fetchApi as typeof fetch };
|
||||
}
|
||||
async function storeWith(rows: Array<[string, string]>) {
|
||||
const db = await database();
|
||||
const insert = db.prepare(
|
||||
"INSERT INTO credential (id, integration_id, value, active, time_updated) VALUES (?, ?, ?, ?, ?)",
|
||||
);
|
||||
for (const [integration, value] of rows) insert.run(integration, integration, value, 1, 1);
|
||||
db.close();
|
||||
await rm(fixturePath);
|
||||
const [account] = await discover(stores(fixturePath));
|
||||
return inputSchema.parse(account!.input);
|
||||
}
|
||||
|
||||
test("reads Go from the Console sign-in OpenCode serves it with, ahead of the opencode-go key", async () => {
|
||||
const input = await storeWith([
|
||||
["opencode", consoleSignIn()],
|
||||
["opencode-go", JSON.stringify({ type: "key", key: "go-key" })],
|
||||
]);
|
||||
const { requests, fetchApi } = upstream({
|
||||
[`${CONSOLE_STATUS_URL} Bearer console-token`]: () => Response.json(goStatus()),
|
||||
});
|
||||
const report = await fetchUsage(input, fetchApi);
|
||||
expect(requests).toEqual([
|
||||
{
|
||||
url: CONSOLE_STATUS_URL,
|
||||
authorization: "Bearer console-token",
|
||||
orgID: "org_TESTORG123",
|
||||
redirect: "error",
|
||||
},
|
||||
]);
|
||||
expect(report.status === "available" && report.windows.map((w) => [w.id, w.usedPct])).toEqual([
|
||||
["rolling", 25],
|
||||
["weekly", 40],
|
||||
["monthly", 50],
|
||||
]);
|
||||
});
|
||||
|
||||
test("discovers a Console sign-in on its own, including one saved for the retired host", async () => {
|
||||
const input = await storeWith([
|
||||
["opencode", consoleSignIn({ server: "https://console.opencode.ai" })],
|
||||
]);
|
||||
const { fetchApi } = upstream({
|
||||
[`${CONSOLE_STATUS_URL} Bearer console-token`]: () => Response.json(goStatus()),
|
||||
});
|
||||
expect((await fetchUsage(input, fetchApi)).status).toBe("available");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["another product", { product: "zen", access: null }],
|
||||
["an ended subscription", goStatus(null)],
|
||||
])("falls back to the opencode-go key when the sign-in's workspace has %s", async (_, body) => {
|
||||
const input = await storeWith([
|
||||
["opencode", consoleSignIn()],
|
||||
["opencode-go", JSON.stringify({ type: "key", key: "go-key" })],
|
||||
]);
|
||||
const { fetchApi } = upstream({
|
||||
[`${CONSOLE_STATUS_URL} Bearer console-token`]: () => Response.json(body),
|
||||
[`${USAGE_URL} Bearer go-key`]: () => Response.json(upstreamResponse),
|
||||
});
|
||||
const report = await fetchUsage(input, fetchApi);
|
||||
expect(report.status === "available" && report.windows.map((w) => w.usedPct)).toEqual([
|
||||
21, 42, 100,
|
||||
]);
|
||||
});
|
||||
|
||||
test("reports the absent subscription for a Console sign-in without Go", async () => {
|
||||
const input = await storeWith([["opencode", consoleSignIn()]]);
|
||||
const { fetchApi } = upstream({
|
||||
[`${CONSOLE_STATUS_URL} Bearer console-token`]: () => Response.json(goStatus(null)),
|
||||
});
|
||||
expect(await fetchUsage(input, fetchApi)).toEqual({
|
||||
status: "unavailable",
|
||||
problem: { kind: "no_quota", detail: "No active OpenCode Go subscription" },
|
||||
});
|
||||
});
|
||||
|
||||
test("reports an expired sign-in without a request, and keeps it over a rejected fallback key", async () => {
|
||||
const expires = Date.now() - 1000;
|
||||
const alone = await storeWith([["opencode", consoleSignIn({ expires })]]);
|
||||
const { requests, fetchApi } = upstream({});
|
||||
const expired = {
|
||||
status: "unavailable",
|
||||
problem: {
|
||||
kind: "expired",
|
||||
expiresAt: new Date(expires).toISOString(),
|
||||
refreshedBy: "opencode",
|
||||
},
|
||||
};
|
||||
expect(await fetchUsage(alone, fetchApi)).toEqual(expired);
|
||||
expect(requests).toEqual([]);
|
||||
await rm(join(fixtureDirectory, "opencode.db"));
|
||||
await writeFile(fixturePath, "{}");
|
||||
const withKey = await storeWith([
|
||||
["opencode", consoleSignIn({ expires })],
|
||||
["opencode-go", JSON.stringify({ type: "key", key: "expired-go-key" })],
|
||||
]);
|
||||
expect(await fetchUsage(withKey, fetchApi)).toEqual(expired);
|
||||
});
|
||||
|
||||
test("reads Go with a key on the opencode integration and falls back when its workspace lacks Go", async () => {
|
||||
const input = await storeWith([
|
||||
["opencode", JSON.stringify({ type: "key", key: "workspace-key" })],
|
||||
["opencode-go", JSON.stringify({ type: "key", key: "go-key" })],
|
||||
]);
|
||||
const served = upstream({
|
||||
[`${CONSOLE_STATUS_URL} Bearer workspace-key`]: () => Response.json(goStatus()),
|
||||
});
|
||||
const report = await fetchUsage(input, served.fetchApi);
|
||||
expect(report.status).toBe("available");
|
||||
expect(served.requests.map((request) => [request.authorization, request.orgID])).toEqual([
|
||||
["Bearer workspace-key", null],
|
||||
]);
|
||||
const refused = upstream({
|
||||
[`${USAGE_URL} Bearer workspace-key`]: () => new Response(null, { status: 403 }),
|
||||
[`${USAGE_URL} Bearer go-key`]: () => Response.json(upstreamResponse),
|
||||
});
|
||||
expect((await fetchUsage(input, refused.fetchApi)).status).toBe("available");
|
||||
expect(refused.requests.at(-1)).toMatchObject({ url: USAGE_URL, authorization: "Bearer go-key" });
|
||||
});
|
||||
|
||||
test("reports a key on the opencode integration without Go as the absent subscription", async () => {
|
||||
const input = await storeWith([["opencode", JSON.stringify({ type: "key", key: "zen-key" })]]);
|
||||
const { fetchApi } = upstream({
|
||||
[`${USAGE_URL} Bearer zen-key`]: () => new Response(null, { status: 403 }),
|
||||
});
|
||||
expect(await fetchUsage(input, fetchApi)).toEqual({
|
||||
status: "unavailable",
|
||||
problem: { kind: "no_quota", detail: "No active OpenCode Go subscription" },
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps the card on the opencode key through a temporary failure", async () => {
|
||||
const input = await storeWith([
|
||||
["opencode", JSON.stringify({ type: "key", key: "workspace-key" })],
|
||||
["opencode-go", JSON.stringify({ type: "key", key: "go-key" })],
|
||||
]);
|
||||
const { requests, fetchApi } = upstream({
|
||||
[`${USAGE_URL} Bearer workspace-key`]: () => new Response(null, { status: 503 }),
|
||||
});
|
||||
await expect(fetchUsage(input, fetchApi)).rejects.toThrow("returned 503");
|
||||
expect(requests.some((request) => request.authorization === "Bearer go-key")).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps the card on the Console sign-in through a temporary failure", async () => {
|
||||
const input = await storeWith([
|
||||
["opencode", consoleSignIn()],
|
||||
["opencode-go", JSON.stringify({ type: "key", key: "go-key" })],
|
||||
]);
|
||||
const { requests, fetchApi } = upstream({
|
||||
[`${CONSOLE_STATUS_URL} Bearer console-token`]: () => new Response(null, { status: 503 }),
|
||||
[`${USAGE_URL} Bearer go-key`]: () => Response.json(upstreamResponse),
|
||||
});
|
||||
await expect(fetchUsage(input, fetchApi)).rejects.toThrow("returned 503");
|
||||
expect(requests.some((request) => request.authorization === "Bearer go-key")).toBe(false);
|
||||
});
|
||||
|
||||
test("reads a key's usage within the refresh deadline when the Console does not answer", async () => {
|
||||
const fetchApi = (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
if (String(url) === USAGE_URL) return Response.json(upstreamResponse);
|
||||
// The Console holds the request open until the caller gives up on it.
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason));
|
||||
});
|
||||
}) as typeof fetch;
|
||||
const started = Date.now();
|
||||
const report = await fetchUsage({ store: "file", path: fixturePath }, fetchApi);
|
||||
expect(report.status).toBe("available");
|
||||
// The daemon gives a usage refresh 20 seconds, and the usage API keeps 15 of them.
|
||||
expect(Date.now() - started).toBeLessThan(5_000);
|
||||
}, 20_000);
|
||||
|
||||
@@ -8,7 +8,9 @@ import {
|
||||
type UsageReport,
|
||||
} from "@getpaseo/plugin/server/usage";
|
||||
import type { Input } from "../shared/input.js";
|
||||
import { defaultStorePaths, readDatabaseLogin, readFileKey } from "./stores.js";
|
||||
import { NO_SUBSCRIPTION, readConsoleGo } from "./console.js";
|
||||
import { defaultStorePaths, readDatabaseLogins, readFileKey, type GoCredential } from "./stores.js";
|
||||
|
||||
const windowSchema = z.object({
|
||||
status: z.enum(["ok", "rate-limited"]),
|
||||
percent: z.number().finite(),
|
||||
@@ -22,9 +24,9 @@ export async function discover(paths = defaultStorePaths()): Promise<UsageAccoun
|
||||
// One OpenCode data directory holds one Go login, whichever store it lives in. Usage settings
|
||||
// are saved per account, so a login OpenCode v2 imports keeps the identity it had in auth.json.
|
||||
const key = hashAccountKey(paths.file);
|
||||
const login = readDatabaseLogin(paths.database);
|
||||
if (login) {
|
||||
return login.key
|
||||
const logins = readDatabaseLogins(paths.database);
|
||||
if (logins) {
|
||||
return logins.opencode || logins.go
|
||||
? [
|
||||
{
|
||||
key,
|
||||
@@ -42,13 +44,81 @@ export async function fetchUsage(
|
||||
input: Input,
|
||||
fetchApi: typeof fetch = fetch,
|
||||
): Promise<UsageReport> {
|
||||
const apiKey =
|
||||
input.store === "database" ? readDatabaseLogin(input.path)?.key : await readFileKey(input.path);
|
||||
if (!apiKey) throw new Error("OpenCode Go login store no longer exists");
|
||||
if (input.store === "file") {
|
||||
const key = await readFileKey(input.path);
|
||||
if (!key) throw new Error("OpenCode Go login store no longer exists");
|
||||
return readKey(key, fetchApi);
|
||||
}
|
||||
const logins = readDatabaseLogins(input.path);
|
||||
const only = logins?.opencode ?? logins?.go;
|
||||
if (!logins || !only) throw new Error("OpenCode Go login store 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 ${apiKey}`, Accept: "application/json" },
|
||||
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}`);
|
||||
@@ -72,3 +142,7 @@ export async function fetchUsage(
|
||||
);
|
||||
return { status: "available", planLabel: "Go", windows };
|
||||
}
|
||||
|
||||
function isRejected(report: UsageReport): boolean {
|
||||
return report.status === "unavailable" && report.problem.kind === "rejected";
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user