Files
Mohamed Boudra 792715e762 feat(usage): usage sources as built-in plugins, following the session's account (#5465)
* feat(server): run internal plugins in-process through the plugin runtime

* fix(server): harden internal plugin startup and boundary checks

* feat(usage): add plugin usage sources and Codex discovery

* fix(usage): share SDK helpers and bound source cache

* feat(usage): migrate usage fetchers to plugin sources

Serve the legacy usage RPC from discovered source reports so older apps retain the same host usage list while new clients use the source registry. Keep credential reads and normalization inside each source.

* refactor(usage): shape sources as fetch functions

Keep the plugin usage API limited to stable report and presentation helpers. Source-local parsers and timeout handling preserve credential and response parity while the cases move alongside each source.

* feat(usage): resolve reports from active session accounts

Resolve source inputs at fetch time so model and credential changes select the account each session spends. Keep the legacy discovered-account RPC for existing clients. Sync OpenCode model events outside foreground turns so usage follows model switches.

* fix usage source discovery and session report parity

* test adapter usage references through daemon RPC

* name usage reference contract across server

* refactor(usage): own usage RPCs and validate session auth

* feat(omp): resolve session usage from active OAuth credential

* fix(omp): match usage source input and valid credential fallback

* test(omp): use upstream credential database schema

* test(omp): verify live session usage references

* fix(usage): declare YAML parser and consolidate credential validation

* feat(app): show usage sources in the composer and a Usage screen

Replace the provider-matched usage in the context ring tooltip with a
composer pill driven by agent.get_usage_report, add a sidebar Usage
screen over usage.list_reports grouped by host, and move the host
settings Usage page to usage.list_reports. Hosts without
features.usageSources show an update message. Source icons come from
the report's catalog SVG. The app no longer calls provider.usage.list.

* fix(usage): declare the Paseo requirement on internal usage-source plugins

A manifest without requirements.paseo targets Paseo before 0.8, so the daemon
refused to start eight of the nine usage sources.

* fix(app): keep host connection statuses live under the React Compiler

The hook read a store version only as a memo trigger (void version); the
compiler dropped it, so pages that mounted before a host came online kept
showing it as connecting.

* fix(app): place the context ring slot before the usage pill

The ring reserves its slot before it has data. With the pill first, the empty
slot sat between the pill and the mic; now it falls in the flexible space.

* refactor(app): extract the settings page layout into PageLayout

Desktop puts the title in the page above a centered column; compact moves it
into a back header. Settings renders the same pixels through it.

* feat(app): lay out the Usage screen like a settings page

The title moves from the header bar into the page on desktop; compact gets the
settings back header, which returns home when the screen was opened by URL.

* refactor(app): drop the unused actions slot from PageLayout

* test(plugin): classify the usage source SDK entry

* fix(usage): preserve platform test contracts

* fix(settings): preserve page title test contract

* feat(usage): identify and cache reports by account ID

Keep report identity stable across input routes and token rotation, and make selective refresh operate on known account reports.

* feat(app): read usage reports through report IDs

Share report data between agent pills and host views while preserving the existing popover interaction for the next UI phase.

* fix(usage): keep account identity aligned with credentials

Read labels from local token claims and use one credential lookup for usage fetches and account identification. Bound cached profile identities across token rotation.

* fix(usage): isolate failure IDs and prune expired reports

Failure reports live outside the account-key namespace, and cache writes discard entries past the five-minute TTL.

* refactor(app): share the compact time-ago prose formatter

Move the tab tooltip's "3m" -> "3m ago" wording into utils/time so the
usage card can reuse it.

* feat(usage): show when each report was fetched

The usage card reads fetchedAt as "Updated 3m ago": a tooltip on the
card header where hover exists (web, desktop), printed in the card
footer on native and compact. Shared by the pill popover and the Usage
screen.

* feat(usage): open the pill popover from cache and refresh on demand

Opening the popover no longer forces a vendor fetch; it shows the cached
report. A Refresh control force-refreshes only this report
(usage.list_reports with its single ID and forceRefresh), shows
Refreshing... while it runs, keeps the previous report visible, and says
"Unable to refresh usage" if the request fails.

* feat(app): let ToolbarButton show a tooltip other than its label

An icon action can now say a status in its tooltip ("Updated 3m ago")
while keeping its label for accessibility.

* feat(usage): refresh a report from its card header

Refresh is an icon button at the right edge of every usage card header,
in the pill popover and on the Usage screen. It force-refreshes only that
report, writes the result to the report's cache and its host list, shows
a spinner and disables itself while pending, and prints "Unable to
refresh usage" in the card on failure. Its tooltip carries the
freshness; without hover the freshness stays in the card footer. The
status indicator sits just left of the button, and the popover's
separate refresh row is gone.

* fix(server): include internal plugin assets in built output

* feat(server): built-in plugins in /plugins (#5544)

* feat(server): load compiled built-in Codex plugin

* test(server): guard built-in plugin loading and installs

* test(server): verify built-in plugins from dist in CI

* refactor(server): migrate remaining usage sources to built-in plugins

* test(server): guard all packaged usage source registrations

* docs: describe usage validation across plugin hosts

* test(ci): include built-in plugins in routing contract

* test(server): import moved Codex usage source

* fix(server): retain ACP updates received with session creation
2026-09-28 16:36:34 +01:00

290 lines
9.3 KiB
TypeScript

import type { UsageInput } from "../shared/input.js";
import { existsSync, promises as fs } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { z } from "zod";
import {
unavailableUsage,
windowFromUsedPct,
type UsageReport,
type UsageWindow,
} from "@getpaseo/plugin/server/usage";
const ApiNumberSchema = z.coerce.number().finite();
const ApiOptionalStringSchema = z.preprocess(
(value) => (value == null ? undefined : value),
z.coerce.string().optional(),
);
const MINIMAX_GLOBAL_BASE_URL = "https://api.minimax.io";
const MINIMAX_CN_BASE_URL = "https://api.minimaxi.com";
const MiniMaxModelRemainSchema = z.object({
model_name: ApiOptionalStringSchema,
start_time: ApiNumberSchema.optional(),
end_time: ApiNumberSchema.optional(),
remains_time: ApiNumberSchema.optional(),
current_interval_total_count: ApiNumberSchema.optional(),
current_interval_usage_count: ApiNumberSchema.optional(),
current_interval_remaining_percent: ApiNumberSchema.optional(),
current_weekly_total_count: ApiNumberSchema.optional(),
current_weekly_usage_count: ApiNumberSchema.optional(),
current_weekly_remaining_percent: ApiNumberSchema.optional(),
current_interval_status: ApiNumberSchema.optional(),
current_weekly_status: ApiNumberSchema.optional(),
weekly_start_time: ApiNumberSchema.optional(),
weekly_end_time: ApiNumberSchema.optional(),
weekly_remains_time: ApiNumberSchema.optional(),
weekly_boost_permille: ApiNumberSchema.optional(),
});
/**
* MiniMax reports application-level failures inside a 200 response: `base_resp.status_code`
* is non-zero and `model_remains` comes back as null. An account with no token plan
* subscription is the common case (status 2062), so both shapes are normal input here.
*/
const MiniMaxBaseRespSchema = z.object({
status_code: ApiNumberSchema.optional(),
status_msg: ApiOptionalStringSchema,
});
const MiniMaxQuotaResponseSchema = z.object({
model_remains: z.array(MiniMaxModelRemainSchema).nullish(),
base_resp: MiniMaxBaseRespSchema.nullish(),
});
const MiniMaxCredentialsSchema = z.object({
access_token: z.string().optional(),
refresh_token: z.string().optional(),
expires_at: ApiOptionalStringSchema,
resource_url: ApiOptionalStringSchema,
});
const MiniMaxConfigSchema = z.object({
api_key: z.string().optional(),
region: z.string().optional(),
base_url: ApiOptionalStringSchema,
oauth: MiniMaxCredentialsSchema.optional(),
});
type MiniMaxModelRemain = z.infer<typeof MiniMaxModelRemainSchema>;
interface MiniMaxResolvedAuth {
token: string;
baseUrl: string;
}
function resolveBaseUrl(input: { baseUrl?: string; region?: string }): string {
const explicit = input.baseUrl;
if (explicit && explicit.startsWith("http")) return explicit;
if (input.region === "cn") return MINIMAX_CN_BASE_URL;
return MINIMAX_GLOBAL_BASE_URL;
}
function computeUsedPct(
remaining: number | null | undefined,
total: number | null | undefined,
): number | null {
if (typeof remaining !== "number" || typeof total !== "number") return null;
if (!Number.isFinite(total) || total <= 0) return null;
if (!Number.isFinite(remaining)) return null;
const used = total - remaining;
return Math.max(0, Math.min(100, (used / total) * 100));
}
function epochMsToIso(value: number | null | undefined): string | null {
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return null;
return new Date(value).toISOString();
}
function toneForStatus(status: number | null | undefined): UsageWindow["tone"] {
if (status === 2) return "danger";
if (status === 3) return "default";
return "ok";
}
function toIntervalWindow(modelName: string, model: MiniMaxModelRemain): UsageWindow | null {
const total = model.current_interval_total_count ?? null;
const used = model.current_interval_usage_count ?? null;
const remainingPercent = model.current_interval_remaining_percent ?? null;
const usedPct =
typeof remainingPercent === "number" && Number.isFinite(remainingPercent)
? Math.max(0, Math.min(100, 100 - remainingPercent))
: computeUsedPct(
typeof total === "number" && typeof used === "number" ? total - used : null,
total,
);
if (usedPct === null) return null;
return windowFromUsedPct({
id: `interval_${modelName}`,
label: `${modelName} · Interval`,
utilizationPct: usedPct,
resetsAt: epochMsToIso(model.end_time),
tone: toneForStatus(model.current_interval_status),
});
}
function toWeeklyWindow(modelName: string, model: MiniMaxModelRemain): UsageWindow | null {
const total = model.current_weekly_total_count ?? null;
const used = model.current_weekly_usage_count ?? null;
const remainingPercent = model.current_weekly_remaining_percent ?? null;
let usedPct: number | null = null;
if (typeof remainingPercent === "number" && Number.isFinite(remainingPercent)) {
usedPct = Math.max(0, Math.min(100, 100 - remainingPercent));
} else if (typeof total === "number" && typeof used === "number") {
usedPct = computeUsedPct(total - used, total);
}
if (usedPct === null) return null;
return windowFromUsedPct({
id: `weekly_${modelName}`,
label: `${modelName} · Weekly`,
utilizationPct: usedPct,
resetsAt: epochMsToIso(model.weekly_end_time),
tone: toneForStatus(model.current_weekly_status),
});
}
export async function fetchUsage(
input: UsageInput,
fetchApi: typeof fetch = fetch,
): Promise<UsageReport> {
void input;
const configPath = join(homedir(), ".mmx", "config.json");
const credentialsPath = join(homedir(), ".mmx", "credentials.json");
const env = process.env;
const now = Date.now;
async function resolveAuth(): Promise<MiniMaxResolvedAuth | null> {
const envToken = env["MINIMAX_API_KEY"];
if (envToken) {
const envBase = env["MINIMAX_BASE_URL"];
return {
token: envToken,
baseUrl: resolveBaseUrl({ baseUrl: envBase }),
};
}
const credentials = await readCredentials();
if (credentials?.access_token && !isExpired(credentials.expires_at)) {
return {
token: credentials.access_token,
baseUrl: resolveBaseUrl({ baseUrl: credentials.resource_url }),
};
}
const config = await readConfig();
if (config?.api_key) {
return {
token: config.api_key,
baseUrl: resolveBaseUrl({
baseUrl: config.base_url,
region: config.region,
}),
};
}
if (config?.oauth?.access_token && !isExpired(config.oauth.expires_at)) {
return {
token: config.oauth.access_token,
baseUrl: resolveBaseUrl({
baseUrl: config.oauth.resource_url ?? config.base_url,
region: config.region,
}),
};
}
return null;
}
function isExpired(expiresAt: string | null | undefined): boolean {
if (!expiresAt) return false;
const parsed = Date.parse(expiresAt);
if (!Number.isFinite(parsed)) return false;
return parsed <= now();
}
async function readCredentials(): Promise<z.infer<typeof MiniMaxCredentialsSchema> | null> {
if (!existsSync(credentialsPath)) return null;
try {
const raw = JSON.parse(await fs.readFile(credentialsPath, "utf8"));
return MiniMaxCredentialsSchema.parse(raw);
} catch {
return null;
}
}
async function readConfig(): Promise<z.infer<typeof MiniMaxConfigSchema> | null> {
if (!existsSync(configPath)) return null;
try {
const raw = JSON.parse(await fs.readFile(configPath, "utf8"));
return MiniMaxConfigSchema.parse(raw);
} catch {
return null;
}
}
const auth = await resolveAuth();
if (!auth) return unavailableUsage();
const res = await fetchApi(`${auth.baseUrl}/v1/token_plan/remains`, {
signal: AbortSignal.timeout(15_000),
headers: {
Authorization: `Bearer ${auth.token}`,
Accept: "application/json",
},
});
if (!res.ok) {
return unavailableUsage();
}
const resp = MiniMaxQuotaResponseSchema.parse(await res.json());
const statusCode = resp.base_resp?.status_code;
if (typeof statusCode === "number" && statusCode !== 0) {
return unavailableUsage();
}
const models = resp.model_remains ?? [];
const windows: UsageWindow[] = [];
for (const model of models) {
const name = model.model_name ?? "token-plan";
const intervalWindow = toIntervalWindow(name, model);
if (intervalWindow) windows.push(intervalWindow);
const weeklyWindow = toWeeklyWindow(name, model);
if (weeklyWindow) windows.push(weeklyWindow);
}
if (windows[0]) windows[0].headline = true;
return {
status: windows.length > 0 ? "available" : "unavailable",
planLabel: undefined,
windows,
balances: [],
details: [],
};
}
export async function identify() {
if (process.env["MINIMAX_API_KEY"]) return { key: "default" };
const home = join(homedir(), ".mmx");
try {
const credentials = MiniMaxCredentialsSchema.parse(
JSON.parse(await fs.readFile(join(home, "credentials.json"), "utf8")),
);
if (credentials.access_token) return { key: "default" };
} catch {
/* Check config next. */
}
try {
const config = MiniMaxConfigSchema.parse(
JSON.parse(await fs.readFile(join(home, "config.json"), "utf8")),
);
if (config.api_key || config.oauth?.access_token) return { key: "default" };
} catch {
/* No configured account. */
}
return null;
}