Show OpenRouter credits and spend in Usage (#10269)

Show remaining account credits and API-key spend for today, this week, and this month in the host Usage panel and CLI.
This commit is contained in:
Mohamed Boudra authored and GitHub committed 2026-11-20 12:13:01 +07:00
1 parent 1972864b19
commit 05fc260b96
10 files changed
+231 -2

No files matched your search

@@ -15,6 +15,7 @@ export const builtinPlugins = [
"minimax-usage-source",
"muse-provider",
"opencode-go-usage-source",
"openrouter-host-usage-source",
"worktree-include",
"zai-usage-source",
] as const;
@@ -2,11 +2,17 @@ import path from "node:path";
import { initializeEnvironmentProxy } from "../../network/index.js";
import { DaemonClient } from "../../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../../test-utils/paseo-daemon.js";
import { BuiltinPluginLoader, resolveBuiltinPluginsRoot } from "../builtin/index.js";
import {
builtinPlugins,
BuiltinPluginLoader,
resolveBuiltinPluginsRoot,
} from "../builtin/index.js";
const mode = process.argv[2];
if (mode !== "builtin" && mode !== "directory") throw new Error("Expected builtin or directory");
const sources = ["claude-usage-source", "codex-usage-source"];
const sources = builtinPlugins.filter((id) =>
["claude-usage-source", "codex-usage-source", "openrouter-host-usage-source"].includes(id),
);
// Built-ins run inside the daemon; directory plugins initialize their own subprocess network.
if (mode === "builtin") initializeEnvironmentProxy();
const daemon = await createTestPaseoDaemon({
@@ -392,6 +392,8 @@ dns.lookup = function(host, ...args) {
HOME: root,
USERPROFILE: root,
CODEX_HOME: path.join(root, ".codex"),
OPENROUTER_API_KEY: "fixture-openrouter",
OPENROUTER_MANAGEMENT_KEY: "fixture-openrouter-management",
CLAUDE_CONFIG_DIR: path.join(root, ".claude"),
NODE_OPTIONS: `--require=${JSON.stringify(guard.replaceAll("\\", "/"))}`,
https_proxy: `http://127.0.0.1:${address.port}`,
@@ -402,6 +404,7 @@ dns.lookup = function(host, ...args) {
);
expect(tunnels).toContain("api.anthropic.com:443");
expect(tunnels).toContain("chatgpt.com:443");
expect(tunnels.filter((target) => target === "openrouter.ai:443")).toHaveLength(2);
} finally {
proxy.closeAllConnections();
await new Promise<void>((resolve) => proxy.close(() => resolve()));
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Sian Lerk Lau
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
<path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M3 12h4c4 0 5-6 9-6h3M7 12c4 0 5 6 9 6h3M17 3l3 3-3 3M17 15l3 3-3 3"/>
</svg>

After

Width:  |  Height:  |  Size: 271 B

@@ -0,0 +1,15 @@
import type { PluginServerContext } from "@getpaseo/plugin/server";
import { discover, fetchUsage, inputSchema } from "./server/usage.js";
export default function contribute(server: PluginServerContext) {
server.registerUsageSource({
// The marketplace plugin already registers "openrouter".
id: "openrouter-host",
label: "OpenRouter",
icon: "icon.svg",
input: inputSchema,
discover,
fetch: fetchUsage,
});
return () => {};
}
@@ -0,0 +1 @@
{ "id": "openrouter-host-usage-source", "requirements": { "paseo": ">=0.11.0" } }
@@ -0,0 +1,73 @@
import { expect, test } from "vitest";
import { discover, fetchUsage, inputSchema } from "./usage.js";
const scope = { kind: "global" } as const;
const env = {
OPENROUTER_API_KEY: " api-key ",
OPENROUTER_MANAGEMENT_KEY: " management-key ",
};
const spend = {
usage: 32,
usage_daily: 0.0123,
usage_weekly: 1,
usage_monthly: 8,
};
test("discovers only host credentials and returns credential-free inputs", async () => {
expect(await discover(scope, env)).toEqual([
{ key: "key", label: "API key spend", input: { meter: "key" } },
{ key: "credits", label: "Account credits", input: { meter: "credits" } },
]);
expect(await discover(scope, { OPENROUTER_API_KEY: " " })).toEqual([]);
expect(await discover({ kind: "session", provider: "pi", env }, env)).toEqual([]);
expect(inputSchema.safeParse({ meter: "key", token: "secret" }).success).toBe(false);
});
test("reports spend for the three UTC periods", async () => {
const report = await fetchUsage(
{ meter: "key" },
async (url, init) => {
expect(url).toBe("https://openrouter.ai/api/v1/key");
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer api-key");
expect(init?.redirect).toBe("error");
return Response.json({ data: spend });
},
env,
);
expect(report).toEqual({
status: "available",
windows: [],
details: [
{ id: "spend_daily", label: "Spent today (UTC)", value: "$0.0123" },
{ id: "spend_weekly", label: "Spent this week (UTC)", value: "$1.00" },
{ id: "spend_monthly", label: "Spent this month (UTC)", value: "$8.00" },
],
});
});
test("uses the management key exclusively for account credits", async () => {
const report = await fetchUsage(
{ meter: "credits" },
async (url, init) => {
expect(url).toBe("https://openrouter.ai/api/v1/credits");
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer management-key");
return Response.json({ data: { total_credits: 15, total_usage: 4 } });
},
env,
);
expect(report).toEqual({
status: "available",
windows: [],
balances: [{ id: "credits", label: "Credits", remaining: 11, unit: "usd", tone: "ok" }],
});
});
test("reports rejected credentials without including the upstream body", async () => {
const report = await fetchUsage(
{ meter: "credits" },
async () => new Response("sensitive upstream error", { status: 403 }),
env,
);
expect(report).toEqual({ status: "unavailable", problem: { kind: "rejected", status: 403 } });
});
@@ -0,0 +1,104 @@
// Adapted from kiawin/paseo-openrouter-usage. See LICENSE.
import {
balanceToneFromRemaining,
unavailable,
type UsageAccount,
type UsageReport,
type UsageScope,
} from "@getpaseo/plugin/server/usage";
import { z } from "zod";
const meters = {
key: { env: "OPENROUTER_API_KEY", label: "API key spend" },
credits: { env: "OPENROUTER_MANAGEMENT_KEY", label: "Account credits" },
} as const;
export const inputSchema = z.strictObject({ meter: z.enum(["key", "credits"]) });
const keyResponse = z.object({
data: z.object({
usage_daily: z.number(),
usage_weekly: z.number(),
usage_monthly: z.number(),
}),
});
const creditsResponse = z.object({
data: z.object({ total_credits: z.number(), total_usage: z.number() }),
});
export async function discover(
scope: UsageScope,
env: NodeJS.ProcessEnv = process.env,
): Promise<UsageAccount[]> {
if (scope.kind !== "global") return [];
return inputSchema.shape.meter.options.flatMap((meter) => {
const { env: variable, label } = meters[meter];
return env[variable]?.trim() ? [{ key: meter, label, input: { meter } }] : [];
});
}
export async function fetchUsage(
value: unknown,
fetchApi: typeof fetch = fetch,
env: NodeJS.ProcessEnv = process.env,
): Promise<UsageReport> {
const { meter } = inputSchema.parse(value);
const variable = meters[meter].env;
const token = env[variable]?.trim();
if (!token) throw new Error(`OpenRouter usage requires ${variable}`);
const response = await fetchApi(`https://openrouter.ai/api/v1/${meter}`, {
headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
redirect: "error",
signal: AbortSignal.timeout(15_000),
});
if (response.status === 401 || response.status === 403) {
return unavailable({ kind: "rejected", status: response.status });
}
if (!response.ok) throw new Error(`OpenRouter usage API returned ${response.status}`);
const body: unknown = await response.json();
return meter === "key"
? keyReport(keyResponse.parse(body).data)
: creditsReport(creditsResponse.parse(body).data);
}
const usd = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 4,
});
function keyReport(key: z.infer<typeof keyResponse>["data"]): UsageReport {
return {
status: "available",
windows: [],
details: [
{ id: "spend_daily", label: "Spent today (UTC)", value: usd.format(key.usage_daily) },
{ id: "spend_weekly", label: "Spent this week (UTC)", value: usd.format(key.usage_weekly) },
{
id: "spend_monthly",
label: "Spent this month (UTC)",
value: usd.format(key.usage_monthly),
},
],
};
}
function creditsReport(credits: z.infer<typeof creditsResponse>["data"]): UsageReport {
const remaining = credits.total_credits - credits.total_usage;
return {
status: "available",
windows: [],
balances: [
{
id: "credits",
label: "Credits",
remaining,
unit: "usd",
tone: balanceToneFromRemaining(remaining),
},
],
};
}
+2
View File
@@ -44,6 +44,8 @@ Copy the full report ID from the list into `inspect` to see reset times, balance
Queries use the host's five-minute cache when available. Add `--refresh` to bypass it. Use `--host` or `--home` to [select a daemon](#select-one-daemon). Hosts without usage-source support return an update message.
For OpenRouter, set `OPENROUTER_API_KEY` in the daemon’s environment to show what the key spent today, this week, and this month in UTC. Set `OPENROUTER_MANAGEMENT_KEY` to show the remaining account credits. Each variable adds its own report to the host’s Usage panel and `paseo usage`.
### Usage in scripts
```bash