diff --git a/packages/server/src/server/plugins/builtin/index.ts b/packages/server/src/server/plugins/builtin/index.ts index d51f6ee4d..c49eab905 100644 --- a/packages/server/src/server/plugins/builtin/index.ts +++ b/packages/server/src/server/plugins/builtin/index.ts @@ -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; diff --git a/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts b/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts index 23364d3fd..d58c8950a 100644 --- a/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts +++ b/packages/server/src/server/plugins/test-fixtures/usage-proxy-daemon.ts @@ -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({ diff --git a/packages/server/src/server/plugins/usage-sources.e2e.test.ts b/packages/server/src/server/plugins/usage-sources.e2e.test.ts index 7c680bda0..645eee625 100644 --- a/packages/server/src/server/plugins/usage-sources.e2e.test.ts +++ b/packages/server/src/server/plugins/usage-sources.e2e.test.ts @@ -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((resolve) => proxy.close(() => resolve())); diff --git a/plugins/openrouter-host-usage-source/LICENSE b/plugins/openrouter-host-usage-source/LICENSE new file mode 100644 index 000000000..3b93b1ab1 --- /dev/null +++ b/plugins/openrouter-host-usage-source/LICENSE @@ -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. diff --git a/plugins/openrouter-host-usage-source/icon.svg b/plugins/openrouter-host-usage-source/icon.svg new file mode 100644 index 000000000..16793e7b0 --- /dev/null +++ b/plugins/openrouter-host-usage-source/icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/plugins/openrouter-host-usage-source/index.server.ts b/plugins/openrouter-host-usage-source/index.server.ts new file mode 100644 index 000000000..fa68bc0c6 --- /dev/null +++ b/plugins/openrouter-host-usage-source/index.server.ts @@ -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 () => {}; +} diff --git a/plugins/openrouter-host-usage-source/paseo-plugin.json b/plugins/openrouter-host-usage-source/paseo-plugin.json new file mode 100644 index 000000000..da34ffbf5 --- /dev/null +++ b/plugins/openrouter-host-usage-source/paseo-plugin.json @@ -0,0 +1 @@ +{ "id": "openrouter-host-usage-source", "requirements": { "paseo": ">=0.11.0" } } diff --git a/plugins/openrouter-host-usage-source/server/usage.test.ts b/plugins/openrouter-host-usage-source/server/usage.test.ts new file mode 100644 index 000000000..1db1a45aa --- /dev/null +++ b/plugins/openrouter-host-usage-source/server/usage.test.ts @@ -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 } }); +}); diff --git a/plugins/openrouter-host-usage-source/server/usage.ts b/plugins/openrouter-host-usage-source/server/usage.ts new file mode 100644 index 000000000..78053e7e7 --- /dev/null +++ b/plugins/openrouter-host-usage-source/server/usage.ts @@ -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 { + 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 { + 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["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["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), + }, + ], + }; +} diff --git a/public-docs/cli.md b/public-docs/cli.md index 99e4d4c32..9ec7b659e 100644 --- a/public-docs/cli.md +++ b/public-docs/cli.md @@ -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