Files
openclaw/extensions/clawrouter/usage.ts
Peter Steinberger deac98eb72 fix: harden small runtime and installer edge cases (#100258)
* fix(media): preserve dollar sequences in transcript echoes

Co-authored-by: uditDewan <udit.dewan21@gmail.com>

* fix(mcp): catch rejected gateway event handlers

Co-authored-by: 陈宪彪0668000387 <chen.xianbiao@xydigit.com>

* fix(auto-reply): support punctuated silent token prefixes

Co-authored-by: simon-w <weng.qimeng@xydigit.com>

* fix(discord): keep voice log previews UTF-16 safe

Co-authored-by: sunlit-deng <yang.jiajun1@xydigit.com>

* fix(clawrouter): bound usage response reads

Co-authored-by: 杨浩宇0668001029 <yang.haoyu@xydigit.com>

* fix(browser): bound CDP JSON response reads

Co-authored-by: hailory <hailory@xydigit.com>

* fix(status): include current time in session status

Co-authored-by: connermo <conner.mo@gmail.com>

* fix(installer): require Arch detection before pacman

Co-authored-by: Iliya Abolghasemi <gfaerny@gmail.com>

* fix(apps): default TLS gateway deep links to port 443

Co-authored-by: ben.li <li.yang6@xydigit.com>

* fix(infra): keep Undici terminated exceptions nonfatal

Co-authored-by: harjoth <harjoth.khara@gmail.com>

* fix(auto-reply): avoid Unicode-unsafe token spread

---------

Co-authored-by: uditDewan <udit.dewan21@gmail.com>
Co-authored-by: 陈宪彪0668000387 <chen.xianbiao@xydigit.com>
Co-authored-by: simon-w <weng.qimeng@xydigit.com>
Co-authored-by: sunlit-deng <yang.jiajun1@xydigit.com>
Co-authored-by: 杨浩宇0668001029 <yang.haoyu@xydigit.com>
Co-authored-by: hailory <hailory@xydigit.com>
Co-authored-by: connermo <conner.mo@gmail.com>
Co-authored-by: Iliya Abolghasemi <gfaerny@gmail.com>
Co-authored-by: ben.li <li.yang6@xydigit.com>
Co-authored-by: harjoth <harjoth.khara@gmail.com>
2026-07-05 05:33:11 -07:00

117 lines
4.1 KiB
TypeScript

import type { ProviderUsageSnapshot } from "openclaw/plugin-sdk/provider-usage";
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
import { normalizeClawRouterRootUrl } from "./provider-catalog.js";
const CLAWROUTER_USAGE_RESPONSE_MAX_BYTES = 1024 * 1024;
type ClawRouterBudget = {
configured?: unknown;
ledger?: unknown;
windowKey?: unknown;
limitMicros?: unknown;
spentMicros?: unknown;
remainingMicros?: unknown;
};
type ClawRouterUsagePayload = {
budget?: ClawRouterBudget;
usage?: {
summary?: {
requestCount?: unknown;
totalTokens?: unknown;
actualCostMicros?: unknown;
};
};
};
function nonNegativeNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
}
function formatUsd(micros: number): string {
const dollars = micros / 1_000_000;
return dollars < 0.01 && dollars > 0 ? `$${dollars.toFixed(4)}` : `$${dollars.toFixed(2)}`;
}
function formatCount(value: number): string {
return new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 }).format(value);
}
function resolveMonthlyResetAt(windowKey: unknown): number | undefined {
if (typeof windowKey !== "string") {
return undefined;
}
const match = windowKey.match(/\/(\d{4})-(\d{2})$/u);
if (!match) {
return undefined;
}
const year = Number(match[1]);
const month = Number(match[2]);
return Number.isSafeInteger(year) && month >= 1 && month <= 12
? Date.UTC(year, month, 1)
: undefined;
}
function buildSummary(payload: ClawRouterUsagePayload): string | undefined {
const summary = payload.usage?.summary;
const requests = nonNegativeNumber(summary?.requestCount);
const tokens = nonNegativeNumber(summary?.totalTokens);
const costMicros = nonNegativeNumber(summary?.actualCostMicros);
const parts = [
requests === undefined ? undefined : `${formatCount(requests)} requests`,
tokens === undefined ? undefined : `${formatCount(tokens)} tokens`,
costMicros === undefined ? undefined : `${formatUsd(costMicros)} used`,
].filter((part): part is string => Boolean(part));
return parts.length > 0 ? parts.join(" · ") : undefined;
}
async function readClawRouterUsagePayload(
response: Response,
timeoutMs: number,
): Promise<ClawRouterUsagePayload> {
const buffer = await readResponseWithLimit(response, CLAWROUTER_USAGE_RESPONSE_MAX_BYTES, {
chunkTimeoutMs: timeoutMs,
onOverflow: ({ maxBytes }) => new Error(`ClawRouter usage response exceeds ${maxBytes} bytes`),
onIdleTimeout: ({ chunkTimeoutMs }) =>
new Error(`ClawRouter usage response stalled: no data received for ${chunkTimeoutMs}ms`),
});
return JSON.parse(new TextDecoder().decode(buffer)) as ClawRouterUsagePayload;
}
export async function fetchClawRouterUsage(params: {
token: string;
baseUrl?: string;
timeoutMs: number;
fetchFn: typeof fetch;
}): Promise<ProviderUsageSnapshot> {
const response = await params.fetchFn(`${normalizeClawRouterRootUrl(params.baseUrl)}/v1/usage`, {
headers: {
Accept: "application/json",
Authorization: `Bearer ${params.token}`,
},
signal: AbortSignal.timeout(params.timeoutMs),
});
if (!response.ok) {
throw new Error(`ClawRouter usage request failed (HTTP ${response.status})`);
}
const payload = await readClawRouterUsagePayload(response, params.timeoutMs);
const budget = payload.budget;
const limitMicros = nonNegativeNumber(budget?.limitMicros);
const spentMicros = nonNegativeNumber(budget?.spentMicros);
const windows = [];
if (budget?.configured === true && limitMicros !== undefined && spentMicros !== undefined) {
windows.push({
label: "Monthly budget",
usedPercent: limitMicros === 0 ? 100 : Math.min(100, (spentMicros / limitMicros) * 100),
resetAt: resolveMonthlyResetAt(budget?.windowKey),
});
}
return {
provider: "clawrouter" as ProviderUsageSnapshot["provider"],
displayName: "ClawRouter",
windows,
summary: buildSummary(payload),
plan: budget?.configured === true ? "Managed monthly budget" : "Unmetered proxy key",
};
}