π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(usage): expose the caller's credit quota via API, SDK and lh (#21933)
Rdmclin25e00dae61b38
diff --git a/.agents/skills/cli/references/search-config.md b/.agents/skills/cli/references/search-config.mdindex b5a6b07bd41..8b44e5d24ec 100644--- a/.agents/skills/cli/references/search-config.md+++ b/.agents/skills/cli/references/search-config.md@@ -68,7 +68,7 @@ lh search view <target> [-i <impls>] [--json [fields]]----## User Configuration (`lh whoami` / `lh usage`)+## User Configuration (`lh whoami` / `lh usage` / `lh usage quota`)**Source**: `apps/cli/src/commands/config.ts`@@ -98,6 +98,22 @@ lh usage [--month <YYYY-MM>] [--agent-id <id>] [--daily] [--json [fields]]**Output**: Token usage, costs, and model breakdown for the specified period.+### `lh usage quota`++Show the caller's credit allowance for the current cycle: used share, what is+left, and the next reset. Reads `GET /api/v1/usage` (its `quota` field), so it+needs a deployment with a metered budget provider; elsewhere it prints that no+allowance exists.++```bash+lh usage quota [--workspace <id|slug>] [--json [fields]]+```++`--json` prints `{ quota, scope }`. `quota.usedRatio` is `used / limit`+clamped to `0..1`, and `null` when the allowance has no cap. In a workspace,+`quota.source` is `member_budget` when the member has their own cap, otherwise+`workspace_pool`. Any member, viewers included, may read it.+---## Workspace (`lh workspace`)diff --git a/apps/cli/src/api/openapi.test.ts b/apps/cli/src/api/openapi.test.tsnew file mode 100644index 00000000000..c5e3136c9c8--- /dev/null+++ b/apps/cli/src/api/openapi.test.ts@@ -0,0 +1,87 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type * as RefreshModule from '../auth/refresh';+import { getValidToken } from '../auth/refresh';+import { getOpenApi } from './openapi';++vi.mock('../auth/refresh', async (importOriginal) => ({+ ...(await importOriginal<typeof RefreshModule>()),+ getValidToken: vi.fn(),+}));+vi.mock('../settings', () => ({+ loadActiveWorkspace: () => undefined,+ resolveServerUrl: () => 'https://app.lobehub.com',+}));+vi.mock('../utils/logger', () => ({ log: { debug: vi.fn(), error: vi.fn(), warn: vi.fn() } }));++const jwt = (payload: Record<string, unknown>) =>+ `e30.${Buffer.from(JSON.stringify(payload)).toString('base64url')}.sig`;++const storedToken = jwt({ sub: 'user-1' });++describe('getOpenApi', () => {+ const fetchMock = vi.fn();+ const originalJwt = process.env.LOBEHUB_JWT;+ const originalWorkspaceId = process.env.LOBEHUB_WORKSPACE_ID;++ const sentHeaders = () => fetchMock.mock.calls[0][1].headers as Record<string, string>;++ beforeEach(() => {+ delete process.env.LOBEHUB_JWT;+ delete process.env.LOBEHUB_WORKSPACE_ID;+ vi.stubGlobal('fetch', fetchMock);+ fetchMock.mockReset();+ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ data: { quota: null }, success: true })),+ );+ vi.mocked(getValidToken).mockResolvedValue({+ credentials: { accessToken: storedToken },+ status: 'ok',+ } as any);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ if (originalJwt === undefined) delete process.env.LOBEHUB_JWT;+ else process.env.LOBEHUB_JWT = originalJwt;+ if (originalWorkspaceId === undefined) delete process.env.LOBEHUB_WORKSPACE_ID;+ else process.env.LOBEHUB_WORKSPACE_ID = originalWorkspaceId;+ });++ it('sends the stored login as a Bearer token and unwraps data', async () => {+ await expect(getOpenApi('/usage', 'ws-1')).resolves.toEqual({ quota: null });++ expect(fetchMock.mock.calls[0][0]).toBe('https://app.lobehub.com/api/v1/usage');+ expect(sentHeaders()).toEqual({+ 'Authorization': `Bearer ${storedToken}`,+ 'X-Workspace-Id': 'ws-1',+ });+ });++ it("replaces a run's operation token with the same account's stored login", async () => {+ process.env.LOBEHUB_JWT = jwt({ purpose: 'hetero-operation', sub: 'user-1' });++ await getOpenApi('/usage');++ expect(sentHeaders().Authorization).toBe(`Bearer ${storedToken}`);+ });++ it('keeps a regular JWT from the environment', async () => {+ const envToken = jwt({ sub: 'user-2' });+ process.env.LOBEHUB_JWT = envToken;++ await getOpenApi('/usage');++ expect(sentHeaders().Authorization).toBe(`Bearer ${envToken}`);+ });++ it("throws the server's error message", async () => {+ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ error: 'Not a member of this workspace', success: false }), {+ status: 403,+ }),+ );++ await expect(getOpenApi('/usage', 'ws-1')).rejects.toThrow('Not a member of this workspace');+ });+});diff --git a/apps/cli/src/api/openapi.ts b/apps/cli/src/api/openapi.tsnew file mode 100644index 00000000000..9ff1832ffb8--- /dev/null+++ b/apps/cli/src/api/openapi.ts@@ -0,0 +1,44 @@+import { resolveServerUrl } from '../settings';+import { log } from '../utils/logger';+import { getAgentStreamAuthInfo } from './http';+import { isOperationToken, storedLoginFor } from './operationTokenFallback';+import { withWorkspaceHeader } from './workspace';++/**+ * The Bearer token for `/api/v1/*`. That API accepts OIDC JWTs and API keys+ * but refuses a run's `hetero-operation` token outright, so an operation token+ * in `LOBEHUB_JWT` is swapped for this machine's stored login of the same+ * account, the same rule `operationTokenFallbackLink` applies to tRPC.+ */+const resolveBearerToken = async (): Promise<string> => {+ const envJwt = process.env.LOBEHUB_JWT;+ if (envJwt && isOperationToken(envJwt)) {+ const lookup = await storedLoginFor(envJwt);+ if ('token' in lookup) return lookup.token;++ log.error(lookup.warning);+ process.exit(1);+ }++ return (await getAgentStreamAuthInfo()).token;+};++/**+ * GET a LobeHub REST API (`/api/v1/*`) resource and unwrap its `data`+ * envelope. The workspace scope resolves like every other command.+ */+export async function getOpenApi<T>(path: string, workspaceId?: string): Promise<T> {+ const token = await resolveBearerToken();++ const res = await fetch(`${resolveServerUrl()}/api/v1${path}`, {+ headers: withWorkspaceHeader({ Authorization: `Bearer ${token}` }, workspaceId),+ });+ const body = (await res.json().catch(() => undefined)) as+ { data?: T; error?: string; success?: boolean } | undefined;++ if (!res.ok || !body?.success) {+ throw new Error(body?.error || `GET /api/v1${path} failed with HTTP ${res.status}`);+ }++ return body.data as T;+}diff --git a/apps/cli/src/api/operationTokenFallback.ts b/apps/cli/src/api/operationTokenFallback.tsindex 75f56d341cf..a9098aeaed4 100644--- a/apps/cli/src/api/operationTokenFallback.ts+++ b/apps/cli/src/api/operationTokenFallback.ts@@ -54,7 +54,7 @@ export const isOperationTokenRefusal = (error: unknown): boolean =>* The stored login, when it is usable and belongs to the operation token's own* account.*/-const storedLoginFor = async (+export const storedLoginFor = async (operationToken: string,): Promise<{ token: string } | { warning: string }> => {const result = await getValidToken();diff --git a/apps/cli/src/commands/config.test.ts b/apps/cli/src/commands/config.test.tsindex 53062f7df82..11f26059133 100644--- a/apps/cli/src/commands/config.test.ts+++ b/apps/cli/src/commands/config.test.ts@@ -20,7 +20,14 @@ const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({getTrpcClient: vi.fn(),}));+const { mockGetOpenApi, mockResolveWorkspaceRef } = vi.hoisted(() => ({+ mockGetOpenApi: vi.fn(),+ mockResolveWorkspaceRef: vi.fn(async (ref?: string) => (ref ? `ws-${ref}` : undefined)),+}));+vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));+vi.mock('../api/openapi', () => ({ getOpenApi: mockGetOpenApi }));+vi.mock('../api/workspaceRef', () => ({ resolveWorkspaceRef: mockResolveWorkspaceRef }));// Scope resolution falls through to the persisted `workspace use` value, which// must not leak the developer's own machine state into these assertions.vi.mock('../settings', () => ({@@ -175,4 +182,69 @@ describe('config command', () => {expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(data, null, 2));});});++ describe('usage quota', () => {+ const quota = {+ limit: 10,+ remaining: 3.8,+ resetsAt: '2026-11-30T00:00:00.000Z',+ source: 'personal',+ used: 6.2,+ usedRatio: 0.62,+ };++ const output = () => consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');++ beforeEach(() => mockGetOpenApi.mockReset());++ it('shows the used share of the allowance, what is left and when it resets', async () => {+ mockGetOpenApi.mockResolvedValue({ quota, scope: 'personal' });++ await createProgram().parseAsync(['node', 'test', 'usage', 'quota']);++ expect(mockGetOpenApi).toHaveBeenCalledWith('/usage', undefined);+ expect(output()).toContain('62% ($6.20 of $10.00)');+ expect(output()).toContain('Remaining: $3.80');+ expect(output()).toContain('Resets: 2026-11-30');+ expect(mockTrpcClient.usage.findAndGroupByDay.query).not.toHaveBeenCalled();+ });++ it('reads the workspace passed with --workspace', async () => {+ mockGetOpenApi.mockResolvedValue({ quota, scope: 'workspace' });++ await createProgram().parseAsync(['node', 'test', 'usage', 'quota', '--workspace', 'acme']);++ expect(mockGetOpenApi).toHaveBeenCalledWith('/usage', 'ws-acme');+ });++ it('prints the quota and scope as JSON', async () => {+ mockGetOpenApi.mockResolvedValue({ quota, remainingBalance: 3.8, scope: 'personal' });++ await createProgram().parseAsync(['node', 'test', 'usage', 'quota', '--json']);++ expect(consoleSpy).toHaveBeenCalledWith(+ JSON.stringify({ quota, scope: 'personal' }, null, 2),+ );+ });++ it('says so when the server has no allowance', async () => {+ mockGetOpenApi.mockResolvedValue({ quota: null, scope: 'personal' });++ await createProgram().parseAsync(['node', 'test', 'usage', 'quota']);++ expect(output()).toContain('No credit allowance on this server.');+ });++ it('shows spend without a percentage when the allowance has no cap', async () => {+ mockGetOpenApi.mockResolvedValue({+ quota: { ...quota, limit: null, source: 'workspace_pool', usedRatio: null },+ scope: 'workspace',+ });++ await createProgram().parseAsync(['node', 'test', 'usage', 'quota']);++ expect(output()).toContain('$6.20 (no cap)');+ expect(output()).not.toContain('%');+ });+ });});diff --git a/apps/cli/src/commands/config.ts b/apps/cli/src/commands/config.tsindex 4eb09f84ae4..f43810d54c2 100644--- a/apps/cli/src/commands/config.ts+++ b/apps/cli/src/commands/config.ts@@ -2,7 +2,9 @@ import type { Command } from 'commander';import pc from 'picocolors';import { getTrpcClient } from '../api/client';+import { getOpenApi } from '../api/openapi';import { resolveWorkspaceScope } from '../api/workspace';+import { resolveWorkspaceRef } from '../api/workspaceRef';import { CLI_PRODUCT_NAME } from '../constants/identity';import {type BoxTableRow,@@ -58,7 +60,7 @@ export function registerConfigCommand(program: Command) {// ββ usage βββββββββββββββββββββββββββββββββββββββββββββ- program+ const usage = program.command('usage').description('View usage statistics').option('--month <YYYY-MM>', 'Month to query (default: current)')@@ -228,4 +230,70 @@ export function registerConfigCommand(program: Command) {});},);++ // ββ usage quota βββββββββββββββββββββββββββββββββββββββ++ usage+ .command('quota')+ .description("Show how much of this cycle's credit allowance is used and left")+ .option(+ '--workspace <id|slug>',+ 'Read the allowance in this workspace (defaults to the active scope)',+ )+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')+ .action(async (_options: unknown, command: Command) => {+ // `usage` declares `--json` too, and Commander hands it a `--json`+ // written after `quota`; merging the ancestors' options recovers it.+ const options = command.optsWithGlobals<{ json?: string | boolean; workspace?: string }>();+ const summary = await getOpenApi<UsageSummary>(+ '/usage',+ await resolveWorkspaceRef(options.workspace),+ );++ if (options.json !== undefined) {+ outputJson(+ { quota: summary.quota, scope: summary.scope },+ typeof options.json === 'string' ? options.json : undefined,+ );+ return;+ }++ const { quota } = summary;+ if (!quota) {+ console.log('No credit allowance on this server.');+ return;+ }++ console.log(pc.bold('Credit Allowance'));+ console.log(` Source: ${QUOTA_SOURCE_LABELS[quota.source]}`);+ if (quota.limit === null) {+ console.log(` Used: ${formatCost(quota.used)} ${pc.dim('(no cap)')}`);+ } else {+ const percent = Math.round((quota.usedRatio ?? 0) * 100);+ console.log(+ ` Used: ${percent}% (${formatCost(quota.used)} of ${formatCost(quota.limit)})`,+ );+ }+ if (quota.remaining !== null) console.log(` Remaining: ${formatCost(quota.remaining)}`);+ if (quota.resetsAt) console.log(` Resets: ${quota.resetsAt.slice(0, 10)}`);+ });}++/** The fields of `GET /api/v1/usage` that `lh usage quota` reads. */+interface UsageSummary {+ quota: {+ limit: number | null;+ remaining: number | null;+ resetsAt: string | null;+ source: 'member_budget' | 'personal' | 'workspace_pool';+ used: number;+ usedRatio: number | null;+ } | null;+ scope: 'personal' | 'workspace';+}++const QUOTA_SOURCE_LABELS: Record<NonNullable<UsageSummary['quota']>['source'], string> = {+ member_budget: 'your member limit in this workspace',+ personal: 'personal credits',+ workspace_pool: 'workspace credit pool',+};diff --git a/packages/business-server/src/openapiUsage.ts b/packages/business-server/src/openapiUsage.tsindex 46b8f681846..d0bbc9b4264 100644--- a/packages/business-server/src/openapiUsage.ts+++ b/packages/business-server/src/openapiUsage.ts@@ -1,8 +1,29 @@+/**+ * The caller's own spending allowance for the current cycle, in USD.+ *+ * `limit` is the denominator a "how much is left" indicator needs; it is+ * `null` when the allowance has no cap (or none is known), and then+ * `usedRatio` is `null` too.+ */+export interface OpenApiUsageQuota {+ limit: number | null;+ remaining: number | null;+ /** Next reset of a recurring allowance (ISO 8601), `null` when none recurs. */+ resetsAt: string | null;+ /** Where the allowance comes from: the user's own budgets, the workspace pool, or a member cap. */+ source: 'personal' | 'workspace_pool' | 'member_budget';+ used: number;+ /** `used / limit`, clamped to `0..1`. */+ usedRatio: number | null;+}+export interface OpenApiUsageSummary {available: boolean;currency: 'USD';daily: Array<{ date: string; value: number }>;period: { since: string; until: string };+ /** `null` when the deployment has no metered budget provider. */+ quota: OpenApiUsageQuota | null;remainingBalance: number | null;scope: 'personal' | 'workspace';spent: number;@@ -29,6 +50,7 @@ export const getOpenApiUsage = async (currency: 'USD',daily: [],period: { since: since.toISOString(), until: until.toISOString() },+ quota: null,remainingBalance: null,scope: params.workspaceId ? 'workspace' : 'personal',spent: 0,diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.ymlindex cee0cfab4b2..497a1b364c6 100644--- a/packages/openapi/openapi.yml+++ b/packages/openapi/openapi.yml@@ -1003,6 +1003,44 @@ components:- since- untiltype: object+ quota:+ additionalProperties: false+ properties:+ limit:+ type:+ - number+ - "null"+ remaining:+ type:+ - number+ - "null"+ resetsAt:+ format: date-time+ type:+ - string+ - "null"+ source:+ enum:+ - personal+ - workspace_pool+ - member_budget+ type: string+ used:+ type: number+ usedRatio:+ type:+ - number+ - "null"+ required:+ - limit+ - remaining+ - resetsAt+ - source+ - used+ - usedRatio+ type:+ - object+ - "null"remainingBalance:type:- number@@ -1037,6 +1075,7 @@ components:- currency- daily- period+ - quota- remainingBalance- scope- spentdiff --git a/packages/openapi/src/routes/usage.route.test.ts b/packages/openapi/src/routes/usage.route.test.tsnew file mode 100644index 00000000000..af06892b5c8--- /dev/null+++ b/packages/openapi/src/routes/usage.route.test.ts@@ -0,0 +1,67 @@+import { Hono } from 'hono';+import { describe, expect, it, vi } from 'vitest';++// The route only declares an API-key scope gate; workspace membership is+// checked upstream by `workspaceAuthMiddleware`. RBAC is stubbed to deny+// everything so a case passes only if the route no longer asks for an RBAC+// permission a workspace viewer lacks.+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/rbac', () => ({+ RbacModel: class {+ hasAnyPermission = async () => false;+ },+}));+vi.mock('../middleware/auth', () => ({+ requireAuth: async (_c: any, next: any) => next(),+}));+vi.mock('../controllers/usage.controller', () => ({+ UsageController: class {+ getUsage(c: any) {+ return c.json({ data: { quota: null }, success: true });+ }+ },+}));++const { default: UsageRoutes } = await import('./usage.route');++const requestAs = (auth: {+ apiKeyScopes?: string[];+ authType: 'apikey' | 'oidc';+ workspaceRole?: string;+}) => {+ const app = new Hono();++ app.use('*', async (c, next) => {+ c.set('userId' as never, 'user-1' as never);+ c.set('authType' as never, auth.authType as never);+ c.set('apiKeyScopes' as never, auth.apiKeyScopes as never);+ if (auth.workspaceRole) {+ c.set('workspaceId' as never, 'ws-1' as never);+ c.set('workspaceRole' as never, auth.workspaceRole as never);+ }+ await next();+ });+ app.route('/', UsageRoutes);++ return app.request('/');+};++describe('GET /usage access', () => {+ it('lets a workspace viewer read their own usage summary', async () => {+ const res = await requestAs({ authType: 'oidc', workspaceRole: 'viewer' });++ expect(res.status).toBe(200);+ });++ it('accepts a key holding usage:read', async () => {+ const res = await requestAs({ apiKeyScopes: ['usage:read'], authType: 'apikey' });++ expect(res.status).toBe(200);+ });++ it('rejects a key without usage:read', async () => {+ const res = await requestAs({ apiKeyScopes: ['file:read'], authType: 'apikey' });++ expect(res.status).toBe(403);+ });+});diff --git a/packages/openapi/src/routes/usage.route.ts b/packages/openapi/src/routes/usage.route.tsindex cca59cfa376..4dbaefbe5da 100644--- a/packages/openapi/src/routes/usage.route.ts+++ b/packages/openapi/src/routes/usage.route.ts@@ -1,11 +1,9 @@import { Hono } from 'hono';import { describeRoute } from 'hono-openapi';-import { getAllScopePermissions } from '@/utils/rbac';-import { UsageController } from '../controllers/usage.controller';import { requireAuth } from '../middleware/auth';-import { requireAnyPermissionWithApiKeyScope } from '../middleware/permission-check';+import { requireApiKeyScope } from '../middleware/permission-check';const app = new Hono();@@ -13,7 +11,10 @@ app.get('/',describeRoute({ summary: 'Get usage and quota summary', tags: ['usage'] }),requireAuth,- requireAnyPermissionWithApiKeyScope(getAllScopePermissions('API_KEY_READ'), 'usage:read'),+ // Every workspace member, viewers included, may read the pool balance and+ // their own allowance: `workspaceAuthMiddleware` has already checked the+ // membership, and the summary exposes no other member's figures.+ requireApiKeyScope('usage:read'),async (c) => new UsageController().getUsage(c),);diff --git a/packages/openapi/src/spec.ts b/packages/openapi/src/spec.tsindex b6e025b5650..b16ad15f666 100644--- a/packages/openapi/src/spec.ts+++ b/packages/openapi/src/spec.ts@@ -427,6 +427,19 @@ const resourceSchemas: Record<string, SchemaObject> = {required: ['since', 'until'],type: 'object',},+ quota: {+ additionalProperties: false,+ properties: {+ limit: nullableNumber,+ remaining: nullableNumber,+ resetsAt: { ...dateTime, type: ['string', 'null'] },+ source: { enum: ['personal', 'workspace_pool', 'member_budget'], type: 'string' },+ used: { type: 'number' },+ usedRatio: nullableNumber,+ },+ required: ['limit', 'remaining', 'resetsAt', 'source', 'used', 'usedRatio'],+ type: ['object', 'null'],+ },remainingBalance: nullableNumber,scope: { enum: ['personal', 'workspace'], type: 'string' },spent: { type: 'number' },@@ -449,6 +462,7 @@ const resourceSchemas: Record<string, SchemaObject> = {'currency','daily','period',+ 'quota','remainingBalance','scope','spent',diff --git a/packages/sdk/src/generated/types.gen.ts b/packages/sdk/src/generated/types.gen.tsindex 7fc4f19e43d..cc0accd4972 100644--- a/packages/sdk/src/generated/types.gen.ts+++ b/packages/sdk/src/generated/types.gen.ts@@ -331,6 +331,14 @@ export type Usage = {since: string;until: string;};+ quota: {+ limit: number | null;+ remaining: number | null;+ resetsAt: string | null;+ source: 'personal' | 'workspace_pool' | 'member_budget';+ used: number;+ usedRatio: number | null;+ } | null;remainingBalance: number | null;scope: 'personal' | 'workspace';spent: number;@@ -6338,12 +6346,14 @@ export type PostApiV1ImMessagesData = {agentId: string;clientMessageId?: string;content: string;+ fileIds?: Array<string>;groupId?: string;topicId?: string | null;} | {agentId?: string;clientMessageId?: string;content: string;+ fileIds?: Array<string>;groupId: string;topicId?: string | null;};@@ -6403,6 +6413,13 @@ export type PostApiV1ImMessagesResponses = {content: string;createdAt: string;error: boolean;+ files?: Array<{+ id: string;+ name: string;+ fileType: string;+ size: number;+ url: string;+ }>;id: string;role: 'assistant' | 'user';};@@ -6478,6 +6495,13 @@ export type GetApiV1ImTopicsByTopicIdSyncResponses = {content: string;createdAt: string;error: boolean;+ files?: Array<{+ id: string;+ name: string;+ fileType: string;+ size: number;+ url: string;+ }>;id: string;role: 'assistant' | 'user';}>;