Billing and consumption
The machine API calls auth-service as your application, with a client_credentials token minted from the application's own secret. It never acts as a user, and it can only read and write the data of your application. Concepts and endpoints are documented in auth-service: Consumption tracking and Stripe integration.
Prerequisites
- A confidential application:
createMachineApithrowsCFG_001withoutclientSecret. - The machine scopes
billing:read,consumption:readandconsumption:write. New confidential applications receive them by default; an application created before that needs a superadmin to set them. A missing scope makes the call throwTOK_004with the scope indetails.scope.
import { createAuthClient } from "@circle-rd/auth-ai";
import { createMachineApi } from "@circle-rd/auth-ai/server";
const auth = createAuthClient({
issuer: "https://auth.example.com",
clientId: "my-app",
clientSecret: "<client-secret>",
redirectUri: "https://app.example.com/auth/callback",
});
const machine = createMachineApi(auth);
Tokens are cached per scope until shortly before they expire, and simultaneous callers share one request to the token endpoint.
Read a user's billing
const subscription = await machine.billing.getSubscription("user-sub");
if (subscription?.isActive) {
console.log(subscription.plan.name, subscription.currentPeriodEnd);
}
const usage = await machine.billing.getUsage("user-sub");
for (const feature of usage.features) {
// usageLimit -1 is unlimited; remaining is null when unlimited
console.log(feature.featureKey, feature.used, feature.remaining);
}
getSubscription returns null when the user holds no subscription. The userId is the user's sub.
Invoices are keyset-paginated, newest first (limit is 1 to 100):
import type { InvoiceView } from "@circle-rd/auth-ai/server";
async function allInvoices(userId: string): Promise<InvoiceView[]> {
const invoices: InvoiceView[] = [];
let cursor: string | undefined;
do {
const page = await machine.billing.listInvoices(userId, {
limit: 50,
...(cursor === undefined ? {} : { cursor }),
});
invoices.push(...page.items);
cursor = page.nextCursor ?? undefined;
} while (cursor !== undefined);
return invoices;
}
Report consumption
const result = await machine.consumption.report({
userId: "user-sub",
key: "exports",
value: 1,
idempotencyKey: "export-job-8c1f",
});
console.log(result.aggregate.total, result.metered);
keyis 1 to 64 characters froma-zA-Z0-9.;valueis a finite number (negative credits back). The SDK validates both before sending and throwsCFG_001otherwise.aggregate.totalis a decimal string: a running total is not bounded by a double.- Set
idempotencyKeyto a stable identifier of the business event (a job id, an order line). The same key reported twice counts once, which makes retries safe; without one, every call counts.
Counters and metered features
| Plain counter | Metered feature | |
|---|---|---|
| When | The key is any other key. | The key is the featureKey of a metered price on the plan of the user's active subscription. |
metered in the result | false | true |
| Rules | Any finite value. | value must be greater than zero; a report that would pass the plan's cap is refused. |
| Read back with | machine.consumption.list(userId) or .get(userId, key) | machine.billing.getUsage(userId) |
When the plan's cap is exceeded, auth-service answers with its own error, which the SDK raises as API_001: look at details.apiCode (BIL_003 for the cap, BIL_002 for a non-positive value) and details.status.
import { AuthAiError } from "@circle-rd/auth-ai";
async function recordExport(userId: string, jobId: string): Promise<"ok" | "quota"> {
try {
await machine.consumption.report({
userId,
key: "exports",
value: 1,
idempotencyKey: `export-${jobId}`,
});
return "ok";
} catch (err) {
if (err instanceof AuthAiError && err.details?.["apiCode"] === "BIL_003") return "quota";
throw err;
}
}
Reading a key that was never reported rejects: consumption.get throws API_001 with details.apiCode CONS_003.
Where to call it
Always from your backend: it needs the application secret. A typical flow is a signed-in request handler that knows request.authSession.userId, performs the work, then reports consumption. Keep the pre-check (getUsage, remaining) as a courtesy to the user and rely on the report's refusal as the authoritative cap.
Call the LiteLLM gateway
Call LLMs and MCP tools through the gateway with the user's own token, handle empty wallets and rate limits, and attribute spend to a session.
Production checklist
What to change before the first real user signs in: stores, locks, secrets, URLs, logout, logging and dependencies.