diff --git a/cli/src/agent/agentQuotas.test.ts b/cli/src/agent/agentQuotas.test.ts new file mode 100644 index 00000000..c512d1c1 --- /dev/null +++ b/cli/src/agent/agentQuotas.test.ts @@ -0,0 +1,802 @@ +import { spawn, spawnSync } from 'node:child_process' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import * as agentAvailability from './agentAvailability' +import { CodexAppServerClient } from '@/codex/codexAppServerClient' +import { + _resetAgentQuotasCacheForTests, + _setClaudeStatusProbeForTests, + extractCodexQuotaBuckets, + getAgentQuotasResponse, + parseAgyCreditsCommandJson, + parseAgyUsageCommandJson, + parseClaudeQuotaControlLine, + probeAgyQuota, + probeClaudeQuota, + probeCodexQuota, + recordAgyTier, + recordClaudeRateLimitEvent, + recordCodexRateLimitsUpdate +} from './agentQuotas' + +describe('agentQuotas parsers and probes', () => { + beforeEach(() => { + _resetAgentQuotasCacheForTests() + vi.restoreAllMocks() + }) + + it('extracts Codex rate limit buckets across primary, secondary, and rateLimitsByLimitId', () => { + const buckets = extractCodexQuotaBuckets({ + rateLimits: { + limitId: 'codex', + primary: { + usedPercent: 18, + windowDurationMins: 10080, + resetsAt: 1794651962 + }, + secondary: { + usedPercent: 45, + windowDurationMins: 300, + resetsAt: 1794400000 + }, + credits: { + hasCredits: true, + unlimited: false, + balance: '240' + }, + planType: 'pro' + }, + rateLimitsByLimitId: { + codex: { + limitId: 'codex', + primary: { + usedPercent: 18, + windowDurationMins: 10080, + resetsAt: 1794651962 + } + }, + codex_fast: { + limitId: 'codex_fast', + limitName: 'Fast tier', + primary: { + usedPercent: 10, + windowDurationMins: 1440, + resetsAt: 1794450000 + } + } + }, + rateLimitResetCredits: { + availableCount: 1, + nextGrantAt: 1796788800 + } + }) + + expect(buckets).toEqual([ + { + id: 'codex-primary', + label: 'Weekly (7d)', + group: null, + window: 'weekly', + usedPercent: 18, + remainingPercent: 82, + resetsAt: 1794651962 * 1000 + }, + { + id: 'codex-secondary', + label: '5h window', + group: null, + window: '5h', + usedPercent: 45, + remainingPercent: 55, + resetsAt: 1794400000 * 1000 + }, + { + id: 'codex_fast-primary', + label: 'Fast tier · Daily (24h)', + group: 'Fast tier', + window: '24h', + usedPercent: 10, + remainingPercent: 90, + resetsAt: 1794450000 * 1000 + } + ]) + }) + + it('parses Antigravity /usage and /credits JSON outputs including unauthenticated messages', () => { + const usageJson = JSON.stringify({ + session_id: 's1', + response: 'Quota remaining...', + command: { + name: 'usage', + data: { + groups: [ + { + name: 'Gemini Models', + buckets: [ + { + id: 'gemini-5h', + window: '5h', + remaining_fraction: 1, + reset_time: '2026-11-11T18:22:22Z' + }, + { + id: 'gemini-weekly', + window: 'weekly', + remaining_fraction: 0.785, + reset_time: '2026-11-15T16:45:43Z' + } + ] + }, + { + name: 'Claude and GPT models', + buckets: [ + { + id: 'claude-5h', + window: '5h', + remaining_fraction: 0.4, + reset_time: '2026-11-11T16:59:11Z' + } + ] + } + ] + } + } + }) + + const parsedUsage = parseAgyUsageCommandJson(usageJson) + expect(parsedUsage?.buckets).toHaveLength(3) + expect(parsedUsage?.buckets[0]).toEqual({ + id: 'gemini-5h', + label: 'Gemini Models · 5h', + group: 'Gemini Models', + window: '5h', + usedPercent: 0, + remainingPercent: 100, + resetsAt: Date.parse('2026-11-11T18:22:22Z') + }) + expect(parsedUsage?.buckets[1]).toEqual({ + id: 'gemini-weekly', + label: 'Gemini Models · Weekly', + group: 'Gemini Models', + window: 'weekly', + usedPercent: 21.5, + remainingPercent: 78.5, + resetsAt: Date.parse('2026-11-15T16:45:43Z') + }) + + expect(parseAgyUsageCommandJson('Error: Please sign in to continue')).toEqual({ + buckets: [], + unauthenticated: true + }) + + const creditsJson = JSON.stringify({ + command: { + name: 'credits', + data: { + remaining_credits: 1500 + } + } + }) + expect(parseAgyCreditsCommandJson(creditsJson)).toBe(1500) + }) + + it('parses Claude control_response lines for initialize and get_status', () => { + const target = { + account: null as Record | null, + statusRows: new Map() + } + + const initStep = parseClaudeQuotaControlLine(JSON.stringify({ + type: 'control_response', + response: { + subtype: 'success', + request_id: 'hapi-claude-quota-init', + response: { + account: { + email: 'dev@example.com', + subscriptionType: 'Claude Max' + } + } + } + }), target) + expect(initStep).toEqual({ initDone: true, statusDone: false }) + expect(target.account).toEqual({ + email: 'dev@example.com', + subscriptionType: 'Claude Max' + }) + + const statusStep = parseClaudeQuotaControlLine(JSON.stringify({ + type: 'control_response', + response: { + subtype: 'success', + request_id: 'hapi-claude-quota-status', + response: { + sections: [ + { + title: '', + rows: [ + { label: 'Auth token', value: 'apiKeyHelper' }, + { label: 'Anthropic base URL', value: 'https://any.s6o.org' } + ] + } + ] + } + } + }), target) + expect(statusStep).toEqual({ initDone: false, statusDone: true }) + expect(Object.fromEntries(target.statusRows.entries())).toEqual({ + 'Auth token': 'apiKeyHelper', + 'Anthropic base URL': 'https://any.s6o.org' + }) + }) + + it('probes Codex account and rate limits and formats credits and plan', async () => { + vi.spyOn(agentAvailability, 'getAgentAvailability').mockReturnValue({ + agent: 'codex', + available: true + }) + vi.spyOn(CodexAppServerClient.prototype, 'connect').mockResolvedValue(undefined) + vi.spyOn(CodexAppServerClient.prototype, 'initialize').mockResolvedValue({} as never) + vi.spyOn(CodexAppServerClient.prototype, 'disconnect').mockResolvedValue(undefined) + vi.spyOn(CodexAppServerClient.prototype, 'readAccount').mockResolvedValue({ + account: { + type: 'chatgpt', + email: 'user@example.com', + planType: 'pro' + } + }) + vi.spyOn(CodexAppServerClient.prototype, 'readRateLimits').mockResolvedValue({ + rateLimits: { + limitId: 'codex', + primary: { + usedPercent: 12, + windowDurationMins: 10080, + resetsAt: 1794900000 + }, + credits: { + hasCredits: true, + unlimited: false, + balance: 1250.5 + } + }, + rateLimitResetCredits: { + availableCount: 2 + } + }) + + const result = await probeCodexQuota({}) + expect(result.status).toBe('ok') + expect(result.accountLabel).toBe('user@example.com') + expect(result.planLabel).toBe('Pro') + expect(result.creditsLabel).toBe('1,250.5 credits · 2 free resets') + expect(result.buckets).toHaveLength(1) + expect(result.buckets[0]?.remainingPercent).toBe(88) + }) + + it('returns unavailable when CLI is not installed and caches getAgentQuotasResponse until invalidated', async () => { + const availabilitySpy = vi.spyOn(agentAvailability, 'getAgentAvailability').mockImplementation((agent) => ({ + agent, + available: false + })) + + recordAgyTier('Google AI Ultra') + recordClaudeRateLimitEvent({ + status: 'allowed', + rateLimitType: 'five_hour', + utilization: 0.35, + resetsAt: Math.floor(Date.now() / 1000) + 3600 + }) + + const first = await getAgentQuotasResponse({ env: {} }) + expect(first.accounts.map((a) => a.status)).toEqual(['unavailable', 'unavailable', 'unavailable']) + expect(availabilitySpy).toHaveBeenCalledTimes(3) + + const second = await getAgentQuotasResponse({ env: {} }) + expect(second.fetchedAt).toBe(first.fetchedAt) + expect(availabilitySpy).toHaveBeenCalledTimes(3) + + recordCodexRateLimitsUpdate({ rateLimits: {} }) + const third = await getAgentQuotasResponse({ env: {} }) + expect(availabilitySpy).toHaveBeenCalledTimes(6) + expect(third.accounts).toHaveLength(3) + }) + + it('handles unavailable status in probeAgyQuota and probeClaudeQuota directly', async () => { + vi.spyOn(agentAvailability, 'getAgentAvailability').mockImplementation((agent) => ({ + agent, + available: false + })) + + const agy = await probeAgyQuota({}) + const claude = await probeClaudeQuota({}) + expect(agy.status).toBe('unavailable') + expect(claude.status).toBe('unavailable') + }) + + it('shares live quota observations across process boundaries, isolates session credentials, and binds to the producing session account across switches', async () => { + const hapiHome = mkdtempSync(join(tmpdir(), 'hapi-live-quotas-')) + try { + const runnerEnv = { HOME: hapiHome, HAPI_HOME: hapiHome } + const resetSec = Math.floor(Date.now() / 1000) + 3600 + + // Write HOME/.claude.json for userA while HAPI_HOME is also configured + writeFileSync( + join(hapiHome, '.claude.json'), + JSON.stringify({ oauthAccount: { emailAddress: 'userA@example.com' } }), + 'utf8' + ) + + // 1. Separate OS child process (default credentials) records a five_hour observation via SDKToLogConverter + const childScript = ` + import { SDKToLogConverter } from './src/claude/utils/sdkToLogConverter.ts'; + const converter = new SDKToLogConverter({ + sessionId: 'session-a', + cwd: process.cwd() + }); + converter.convert({ + type: 'rate_limit_event', + rate_limit_info: { + status: 'allowed', + rateLimitType: 'five_hour', + utilization: 0.4, + resetsAt: ${resetSec} + } + }); + ` + const childRes = spawnSync('bun', ['-e', childScript], { + cwd: process.cwd(), + env: { + PATH: process.env.PATH, + HOME: hapiHome, + HAPI_HOME: hapiHome + }, + encoding: 'utf8' + }) + expect(childRes.status).toBe(0) + + // 2. Separate OS child process with its own CLAUDE_CODE_OAUTH_TOKEN records a conflicting observation + const tokenChildScript = ` + import { recordClaudeRateLimitEvent } from './src/agent/agentQuotas.ts'; + recordClaudeRateLimitEvent({ + status: 'allowed', + rateLimitType: 'five_hour', + utilization: 0.95, + resetsAt: ${resetSec} + }); + ` + const tokenChildRes = spawnSync('bun', ['-e', tokenChildScript], { + cwd: process.cwd(), + env: { + PATH: process.env.PATH, + HOME: hapiHome, + HAPI_HOME: hapiHome, + CLAUDE_CODE_OAUTH_TOKEN: 'session-specific-oauth-token-b' + }, + encoding: 'utf8' + }) + expect(tokenChildRes.status).toBe(0) + + // Simulate separate runner process (clear module-local memory) + _resetAgentQuotasCacheForTests() + vi.spyOn(agentAvailability, 'getAgentAvailability').mockImplementation((agent) => ({ + agent, + available: agent === 'claude' + })) + _setClaudeStatusProbeForTests(async () => ({ + account: { email: 'userA@example.com', subscriptionType: 'Claude Max' }, + statusRows: new Map([ + ['Email', 'userA@example.com'], + ['Login method', 'Claude Max Account'] + ]) + })) + + const first = await getAgentQuotasResponse({ env: runnerEnv }) + const claudeFirst = first.accounts.find((a) => a.agent === 'claude') + expect(claudeFirst?.status).toBe('ok') + expect(claudeFirst?.accountLabel).toBe('userA@example.com') + // Must return the 40% observation for userA, NOT the 95% observation from session B's token + expect(claudeFirst?.buckets).toHaveLength(1) + expect(claudeFirst?.buckets[0]?.usedPercent).toBe(40) + expect(claudeFirst?.buckets[0]?.remainingPercent).toBe(60) + + // 3. Switch machine default Claude account to userB@example.com while a userA session is still running + const lateSessionAScript = ` + import { writeFileSync } from 'node:fs'; + import { join } from 'node:path'; + import { SDKToLogConverter } from './src/claude/utils/sdkToLogConverter.ts'; + // Session A starts while HOME/.claude.json is still userA@example.com + const converterA = new SDKToLogConverter({ + sessionId: 'session-a-long-running', + cwd: process.cwd() + }); + // Host config then switches to userB@example.com + writeFileSync( + join(process.env.HOME, '.claude.json'), + JSON.stringify({ oauthAccount: { emailAddress: 'userB@example.com' } }), + 'utf8' + ); + // Session A emits a new event after the switch; it must stay bound to userA + converterA.convert({ + type: 'rate_limit_event', + rate_limit_info: { + status: 'allowed', + rateLimitType: 'five_hour', + utilization: 0.75, + resetsAt: ${resetSec} + } + }); + ` + _resetAgentQuotasCacheForTests() + vi.spyOn(agentAvailability, 'getAgentAvailability').mockImplementation((agent) => ({ + agent, + available: agent === 'claude' + })) + _setClaudeStatusProbeForTests(async () => ({ + account: { email: 'userB@example.com', subscriptionType: 'Claude Pro' }, + statusRows: new Map([ + ['Email', 'userB@example.com'], + ['Login method', 'Claude Pro Account'] + ]) + })) + + // Runner probes userB first + const beforeLateEvent = await probeClaudeQuota(runnerEnv) + expect(beforeLateEvent.accountLabel).toBe('userB@example.com') + expect(beforeLateEvent.buckets).toEqual([]) + + // Then the still-running userA session emits its late event after runner probed userB + const lateRes = spawnSync('bun', ['-e', lateSessionAScript], { + cwd: process.cwd(), + env: { + PATH: process.env.PATH, + HOME: hapiHome, + HAPI_HOME: hapiHome + }, + encoding: 'utf8' + }) + expect(lateRes.status).toBe(0) + + // Probing userB still must NOT inherit session A's late event + const afterLateEventB = await probeClaudeQuota(runnerEnv) + expect(afterLateEventB.accountLabel).toBe('userB@example.com') + expect(afterLateEventB.buckets).toEqual([]) + + // Probing userA sees the updated 75% bucket + _setClaudeStatusProbeForTests(async () => ({ + account: { email: 'userA@example.com', subscriptionType: 'Claude Max' }, + statusRows: new Map([ + ['Email', 'userA@example.com'], + ['Login method', 'Claude Max Account'] + ]) + })) + const afterLateEventA = await probeClaudeQuota(runnerEnv) + expect(afterLateEventA.accountLabel).toBe('userA@example.com') + expect(afterLateEventA.buckets).toHaveLength(1) + expect(afterLateEventA.buckets[0]?.usedPercent).toBe(75) + } finally { + rmSync(hapiHome, { recursive: true, force: true }) + } + }) + + it('preserves concurrent live quota writes across simultaneous OS processes', async () => { + const hapiHome = mkdtempSync(join(tmpdir(), 'hapi-concurrent-quotas-')) + try { + const env = { HAPI_HOME: hapiHome } + const resetSec = Math.floor(Date.now() / 1000) + 3600 + + const runChildProcess = (script: string): Promise => + new Promise((resolve, reject) => { + const child = spawn('bun', ['-e', script], { + cwd: process.cwd(), + env: { + PATH: process.env.PATH, + HOME: hapiHome, + HAPI_HOME: hapiHome + }, + stdio: 'ignore' + }) + child.on('error', reject) + child.on('close', (code) => { + if (code === 0) resolve() + else reject(new Error(`Child exited with code ${code}`)) + }) + }) + + await Promise.all([ + runChildProcess(` + import { recordCodexRateLimitsUpdate } from './src/agent/agentQuotas.ts'; + recordCodexRateLimitsUpdate({ rateLimits: {} }); + `), + runChildProcess(` + import { recordAgyTier } from './src/agent/agentQuotas.ts'; + recordAgyTier('Google AI Ultra'); + `), + runChildProcess(` + import { recordClaudeRateLimitEvent } from './src/agent/agentQuotas.ts'; + recordClaudeRateLimitEvent({ + status: 'allowed', + rateLimitType: 'five_hour', + utilization: 0.25, + resetsAt: ${resetSec} + }, process.env, 'userA@example.com'); + `), + runChildProcess(` + import { recordClaudeRateLimitEvent } from './src/agent/agentQuotas.ts'; + recordClaudeRateLimitEvent({ + status: 'allowed', + rateLimitType: 'seven_day', + utilization: 0.5, + resetsAt: ${resetSec + 86400} + }, process.env, 'userA@example.com'); + `) + ]) + + _resetAgentQuotasCacheForTests() + vi.spyOn(agentAvailability, 'getAgentAvailability').mockImplementation((agent) => ({ + agent, + available: agent === 'claude' + })) + _setClaudeStatusProbeForTests(async () => ({ + account: { email: 'userA@example.com', subscriptionType: 'Claude Max' }, + statusRows: new Map([['Email', 'userA@example.com']]) + })) + + const claude = await probeClaudeQuota(env) + expect(claude.buckets.map((b) => ({ id: b.id, usedPercent: b.usedPercent }))).toEqual([ + { id: 'claude-five_hour', usedPercent: 25 }, + { id: 'claude-seven_day', usedPercent: 50 } + ]) + } finally { + rmSync(hapiHome, { recursive: true, force: true }) + } + }) + + it('marks Claude window as exhausted when a rejected rate_limit_event omits utilization after a warning', async () => { + const hapiHome = mkdtempSync(join(tmpdir(), 'hapi-rejected-quota-')) + try { + const env = { HAPI_HOME: hapiHome } + const resetSec = Math.floor(Date.now() / 1000) + 3600 + + recordClaudeRateLimitEvent({ + status: 'allowed_warning', + rateLimitType: 'five_hour', + utilization: 0.85, + resetsAt: resetSec + }, env, 'userA@example.com') + + recordClaudeRateLimitEvent({ + status: 'rejected', + rateLimitType: 'five_hour', + resetsAt: resetSec + }, env, 'userA@example.com') + + _resetAgentQuotasCacheForTests() + vi.spyOn(agentAvailability, 'getAgentAvailability').mockImplementation((agent) => ({ + agent, + available: agent === 'claude' + })) + _setClaudeStatusProbeForTests(async () => ({ + account: { email: 'userA@example.com', subscriptionType: 'Claude Max' }, + statusRows: new Map([['Email', 'userA@example.com']]) + })) + + const claude = await probeClaudeQuota(env) + expect(claude.buckets).toEqual([ + { + id: 'claude-five_hour', + label: '5h window', + group: null, + window: '5h', + usedPercent: 100, + remainingPercent: 0, + resetsAt: resetSec * 1000 + } + ]) + } finally { + rmSync(hapiHome, { recursive: true, force: true }) + } + }) + + it('bounds a stalled Codex initialization within probeTimeoutMs while preserving other provider results', async () => { + const hapiHome = mkdtempSync(join(tmpdir(), 'hapi-stalled-codex-')) + try { + const env = { HAPI_HOME: hapiHome } + vi.spyOn(agentAvailability, 'getAgentAvailability').mockImplementation((agent) => ({ + agent, + available: agent === 'codex' || agent === 'claude' + })) + vi.spyOn(CodexAppServerClient.prototype, 'connect').mockResolvedValue(undefined) + vi.spyOn(CodexAppServerClient.prototype, 'initialize').mockImplementation( + () => new Promise(() => { /* never resolves */ }) + ) + vi.spyOn(CodexAppServerClient.prototype, 'disconnect').mockResolvedValue(undefined) + + _setClaudeStatusProbeForTests(async () => ({ + account: { email: 'userA@example.com', subscriptionType: 'Claude Max' }, + statusRows: new Map([ + ['Email', 'userA@example.com'], + ['Login method', 'Claude Max Account'] + ]) + })) + + const started = Date.now() + const response = await getAgentQuotasResponse({ + env, + refresh: true, + probeTimeoutMs: 60 + }) + const elapsed = Date.now() - started + + expect(elapsed).toBeLessThan(1500) + const codex = response.accounts.find((a) => a.agent === 'codex') + const claude = response.accounts.find((a) => a.agent === 'claude') + expect(codex?.status).toBe('error') + expect(codex?.note).toContain('timed out') + expect(claude?.status).toBe('ok') + expect(claude?.accountLabel).toBe('userA@example.com') + } finally { + rmSync(hapiHome, { recursive: true, force: true }) + } + }) + + it('preserves credential isolation across two distinct OAuth tokens when initialize returns only tokenSource through getAccountIdentity and updateAccountIdentity', async () => { + const hapiHome = mkdtempSync(join(tmpdir(), 'hapi-token-source-isolation-')) + try { + const resetSec = Math.floor(Date.now() / 1000) + 3600 + + const runTokenSession = (token: string, utilization: number) => { + const script = ` + import { Writable } from 'node:stream'; + import { Query } from './src/claude/sdk/query.ts'; + import { SDKToLogConverter } from './src/claude/utils/sdkToLogConverter.ts'; + + const converter = new SDKToLogConverter({ + sessionId: 'session-${utilization}', + cwd: process.cwd() + }); + const fakeQuery = Object.create(Query.prototype); + fakeQuery.childStdin = new Writable({ write(_chunk, _enc, cb) { cb(); } }); + fakeQuery.request = async () => ({ + response: { + account: { + tokenSource: 'CLAUDE_CODE_OAUTH_TOKEN', + apiProvider: 'firstParty' + } + } + }); + const identity = await fakeQuery.getAccountIdentity(); + converter.updateAccountIdentity(identity); + converter.convert({ + type: 'rate_limit_event', + rate_limit_info: { + status: 'allowed', + rateLimitType: 'five_hour', + utilization: ${utilization}, + resetsAt: ${resetSec} + } + }); + ` + return spawnSync('bun', ['-e', script], { + cwd: process.cwd(), + env: { + PATH: process.env.PATH, + HOME: hapiHome, + HAPI_HOME: hapiHome, + CLAUDE_CODE_OAUTH_TOKEN: token + }, + encoding: 'utf8' + }) + } + + expect(runTokenSession('oauth-token-alpha', 0.3).status).toBe(0) + expect(runTokenSession('oauth-token-beta', 0.85).status).toBe(0) + + _resetAgentQuotasCacheForTests() + vi.spyOn(agentAvailability, 'getAgentAvailability').mockImplementation((agent) => ({ + agent, + available: agent === 'claude' + })) + _setClaudeStatusProbeForTests(async () => ({ + account: { + tokenSource: 'CLAUDE_CODE_OAUTH_TOKEN', + subscriptionType: 'Claude Max' + }, + statusRows: new Map([ + ['Login method', 'Claude Max Account'], + ['Auth token', 'CLAUDE_CODE_OAUTH_TOKEN'] + ]) + })) + + const alphaQuota = await probeClaudeQuota({ + HOME: hapiHome, + HAPI_HOME: hapiHome, + CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-alpha' + }) + expect(alphaQuota.buckets).toHaveLength(1) + expect(alphaQuota.buckets[0]?.usedPercent).toBe(30) + + const betaQuota = await probeClaudeQuota({ + HOME: hapiHome, + HAPI_HOME: hapiHome, + CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-beta' + }) + expect(betaQuota.buckets).toHaveLength(1) + expect(betaQuota.buckets[0]?.usedPercent).toBe(85) + + const gammaQuota = await probeClaudeQuota({ + HOME: hapiHome, + HAPI_HOME: hapiHome, + CLAUDE_CODE_OAUTH_TOKEN: 'oauth-token-gamma' + }) + expect(gammaQuota.buckets).toEqual([]) + } finally { + rmSync(hapiHome, { recursive: true, force: true }) + } + }) + + it('reports failed Codex account and rateLimits reads with status error while preserving partial account metadata', async () => { + vi.spyOn(agentAvailability, 'getAgentAvailability').mockImplementation((agent) => ({ + agent, + available: agent === 'codex' + })) + vi.spyOn(CodexAppServerClient.prototype, 'connect').mockResolvedValue(undefined) + vi.spyOn(CodexAppServerClient.prototype, 'initialize').mockResolvedValue({}) + vi.spyOn(CodexAppServerClient.prototype, 'disconnect').mockResolvedValue(undefined) + + // 1. account/read succeeds, account/rateLimits/read rejects + vi.spyOn(CodexAppServerClient.prototype, 'readAccount').mockResolvedValueOnce({ + account: { + type: 'chatgpt', + email: 'user@example.com', + planType: 'pro' + } + }) + vi.spyOn(CodexAppServerClient.prototype, 'readRateLimits').mockRejectedValueOnce( + new Error('Rate limits endpoint unavailable') + ) + + const rateLimitFailed = await probeCodexQuota({}) + expect(rateLimitFailed.status).toBe('error') + expect(rateLimitFailed.accountLabel).toBe('user@example.com') + expect(rateLimitFailed.planLabel).toBe('Pro') + expect(rateLimitFailed.buckets).toEqual([]) + expect(rateLimitFailed.note).toBe('Rate limits endpoint unavailable') + + // 2. account/read rejects, account/rateLimits/read succeeds + vi.spyOn(CodexAppServerClient.prototype, 'readAccount').mockRejectedValueOnce( + new Error('Account endpoint unavailable') + ) + vi.spyOn(CodexAppServerClient.prototype, 'readRateLimits').mockResolvedValueOnce({ + rateLimits: { + planType: 'plus', + primary: { + usedPercent: 35, + windowDurationMins: 300, + resetsAt: 1775559600 + } + } + }) + + const accountFailed = await probeCodexQuota({}) + expect(accountFailed.status).toBe('error') + expect(accountFailed.planLabel).toBe('Plus') + expect(accountFailed.buckets).toHaveLength(1) + expect(accountFailed.buckets[0]?.usedPercent).toBe(35) + expect(accountFailed.note).toBe('Account endpoint unavailable') + + // 3. Both reads reject + vi.spyOn(CodexAppServerClient.prototype, 'readAccount').mockRejectedValueOnce( + new Error('Account RPC failed') + ) + vi.spyOn(CodexAppServerClient.prototype, 'readRateLimits').mockRejectedValueOnce( + new Error('RateLimits RPC failed') + ) + + const bothFailed = await probeCodexQuota({}) + expect(bothFailed.status).toBe('error') + expect(bothFailed.buckets).toEqual([]) + expect(bothFailed.note).toBe('RateLimits RPC failed') + }) +}) diff --git a/cli/src/agent/agentQuotas.ts b/cli/src/agent/agentQuotas.ts new file mode 100644 index 00000000..91da4e78 --- /dev/null +++ b/cli/src/agent/agentQuotas.ts @@ -0,0 +1,1211 @@ +import { spawn } from 'node:child_process' +import { createHash } from 'node:crypto' +import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' +import { homedir } from 'node:os' +import { dirname, join } from 'node:path' +import type { + AgentQuotaAccount, + AgentQuotaBucket, + AgentQuotasResponse +} from '@hapi/protocol/apiTypes' +import { buildAgyAcpEnv } from '@/agy/utils/agyAcpBackend' +import { getDefaultClaudeCodePath } from '@/claude/sdk/utils' +import { CodexAppServerClient } from '@/codex/codexAppServerClient' +import type { + AccountRateLimitsReadResponse, + AccountReadResponse, + CodexRateLimitEntry, + CodexRateLimitWindow +} from '@/codex/appServerTypes' +import { resolveHapiHomeDir } from '@/configuration' +import { withBunRuntimeEnv } from '@/utils/bunRuntime' +import { killProcessByChildProcess } from '@/utils/process' +import { getAgentAvailability } from './agentAvailability' +import { getAgentLaunchCommand } from './agentLaunchCommand' + +const CACHE_TTL_MS = 60_000 +const DEFAULT_PROVIDER_PROBE_TIMEOUT_MS = 5_000 +const AGY_PROBE_TIMEOUT_MS = DEFAULT_PROVIDER_PROBE_TIMEOUT_MS +const CLAUDE_PROBE_TIMEOUT_MS = DEFAULT_PROVIDER_PROBE_TIMEOUT_MS +const CLAUDE_INIT_REQ_ID = 'hapi-claude-quota-init' +const CLAUDE_STATUS_REQ_ID = 'hapi-claude-quota-status' + +type RecordValue = Record + +function asRecord(value: unknown): RecordValue | null { + return typeof value === 'object' && value !== null && !Array.isArray(value) + ? value as RecordValue + : null +} + +function asNonEmptyString(value: unknown): string | null { + return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null +} + +function asFiniteNumber(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) ? value : null +} + +function clampPercent(value: number): number { + return Math.max(0, Math.min(100, Math.round(value * 10) / 10)) +} + +function normalizeResetTimestampMs(value: unknown): number | null { + if (typeof value === 'number' && Number.isFinite(value) && value > 0) { + return value < 1_000_000_000_000 ? Math.round(value * 1000) : Math.round(value) + } + if (typeof value === 'string' && value.trim()) { + const parsed = Date.parse(value.trim()) + if (Number.isFinite(parsed) && parsed > 0) { + return parsed + } + } + return null +} + +function formatPlanName(raw: string | null | undefined): string | null { + if (!raw || !raw.trim()) return null + const trimmed = raw.trim() + const lower = trimmed.toLowerCase() + if (lower === 'pro') return 'Pro' + if (lower === 'plus') return 'Plus' + if (lower === 'team') return 'Team' + if (lower === 'enterprise') return 'Enterprise' + if (lower === 'free') return 'Free' + if (lower === 'max') return 'Max' + return trimmed +} + +function formatWindowMinutes(mins: number | null | undefined): { window: string | null; label: string } { + if (!mins || mins <= 0) return { window: null, label: 'Rate limit' } + if (mins === 300) return { window: '5h', label: '5h window' } + if (mins === 10080) return { window: 'weekly', label: 'Weekly (7d)' } + if (mins === 1440) return { window: '24h', label: 'Daily (24h)' } + if (mins % 1440 === 0) { + const days = mins / 1440 + return { window: `${days}d`, label: `${days}d window` } + } + if (mins % 60 === 0) { + const hours = mins / 60 + return { window: `${hours}h`, label: `${hours}h window` } + } + return { window: `${mins}m`, label: `${mins}m window` } +} + +function formatCodexCredits( + rateLimits: CodexRateLimitEntry | null | undefined, + resetCreditsCount: number | null | undefined +): string | null { + const parts: string[] = [] + const credits = rateLimits?.credits + if (credits?.unlimited === true) { + parts.push('Unlimited credits') + } else if (credits?.hasCredits && credits.balance !== null && credits.balance !== undefined) { + const num = typeof credits.balance === 'number' ? credits.balance : Number(credits.balance) + if (Number.isFinite(num)) { + parts.push(`${num.toLocaleString('en-US', { maximumFractionDigits: 2 })} credits`) + } + } + if (typeof resetCreditsCount === 'number' && Number.isFinite(resetCreditsCount) && resetCreditsCount > 0) { + parts.push(`${resetCreditsCount} free reset${resetCreditsCount === 1 ? '' : 's'}`) + } + return parts.length > 0 ? parts.join(' · ') : null +} + +function parseCodexWindowBucket( + id: string, + windowObj: CodexRateLimitWindow | null | undefined, + prefixLabel?: string | null +): AgentQuotaBucket | null { + if (!windowObj || typeof windowObj !== 'object') return null + const usedRaw = asFiniteNumber(windowObj.usedPercent ?? (windowObj as RecordValue).used_percent) + if (usedRaw === null) return null + const usedPercent = clampPercent(usedRaw) + const remainingPercent = clampPercent(100 - usedPercent) + const durationMins = asFiniteNumber(windowObj.windowDurationMins ?? (windowObj as RecordValue).window_duration_mins) + const { window, label: windowLabel } = formatWindowMinutes(durationMins) + const resetsAt = normalizeResetTimestampMs(windowObj.resetsAt ?? (windowObj as RecordValue).resets_at) + const label = prefixLabel ? `${prefixLabel} · ${windowLabel}` : windowLabel + return { + id, + label, + group: prefixLabel ?? null, + window, + usedPercent, + remainingPercent, + resetsAt + } +} + +export function extractCodexQuotaBuckets(response: AccountRateLimitsReadResponse | null | undefined): AgentQuotaBucket[] { + if (!response) return [] + const buckets: AgentQuotaBucket[] = [] + const seen = new Set() + + const addEntryBuckets = (entry: CodexRateLimitEntry | null | undefined, keyPrefix: string, groupLabel?: string | null) => { + if (!entry) return + const primary = parseCodexWindowBucket(`${keyPrefix}-primary`, entry.primary, groupLabel) + if (primary) { + const sig = `${primary.group ?? ''}|${primary.window ?? ''}|${primary.usedPercent}|${primary.resetsAt ?? ''}` + if (!seen.has(sig)) { + seen.add(sig) + buckets.push(primary) + } + } + const secondary = parseCodexWindowBucket(`${keyPrefix}-secondary`, entry.secondary, groupLabel) + if (secondary) { + const sig = `${secondary.group ?? ''}|${secondary.window ?? ''}|${secondary.usedPercent}|${secondary.resetsAt ?? ''}` + if (!seen.has(sig)) { + seen.add(sig) + buckets.push(secondary) + } + } + } + + addEntryBuckets(response.rateLimits, response.rateLimits?.limitId ?? 'codex', response.rateLimits?.limitName ?? null) + + if (response.rateLimitsByLimitId && typeof response.rateLimitsByLimitId === 'object') { + for (const [limitId, entry] of Object.entries(response.rateLimitsByLimitId)) { + const groupLabel = asNonEmptyString(entry?.limitName) ?? (limitId !== 'codex' ? limitId : null) + addEntryBuckets(entry, limitId, groupLabel) + } + } + + return buckets +} + +// Live in-memory observations + cross-process per-observation atomic files under HAPI_HOME/agent-quotas-live +type LiveClaudeBucketRecord = AgentQuotaBucket & { + updatedAt: number + accountKey: string + rateLimitType: string +} + +type PersistedLiveQuotaState = { + codexUpdatedAt?: number + claudeBuckets?: Record + agyTierLabel?: string | null + agyUpdatedAt?: number +} + +let cachedResponse: { startedAt: number; expiresAt: number; response: AgentQuotasResponse } | null = null +let inflightPromise: Promise | null = null +const liveClaudeBuckets = new Map() +let liveAgyTierLabel: string | null = null + +function shortHash(value: string): string { + return createHash('sha256').update(value).digest('hex').slice(0, 16) +} + +function sanitizeKeySegment(value: string): string { + return value.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 48) || 'default' +} + +function resolveLiveQuotaStateDir(env: NodeJS.ProcessEnv = process.env): string | null { + if (env.VITEST === 'true' && !env.HAPI_HOME) { + return null + } + return join(resolveHapiHomeDir(env), 'agent-quotas-live') +} + +function writeAtomicJsonFile(filePath: string, payload: unknown): void { + try { + mkdirSync(dirname(filePath), { recursive: true }) + const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp` + writeFileSync(tmpPath, JSON.stringify(payload), 'utf8') + renameSync(tmpPath, filePath) + } catch { + // Best-effort cross-process state persistence + } +} + +export function resolveClaudeEnvCredentialKey(env: NodeJS.ProcessEnv = process.env): string | null { + const token = asNonEmptyString(env.CLAUDE_CODE_OAUTH_TOKEN) + ?? asNonEmptyString(env.ANTHROPIC_AUTH_TOKEN) + ?? asNonEmptyString(env.ANTHROPIC_API_KEY) + if (!token) return null + return `cred:${shortHash(token)}` +} + +function normalizeClaudeAccountKey(rawIdentity: string | null | undefined): string | null { + const trimmed = asNonEmptyString(rawIdentity) + if (!trimmed) return null + const lower = trimmed.toLowerCase() + if (lower.startsWith('auth:')) { + return null + } + if ( + lower.startsWith('acct:') + || lower.startsWith('cred:') + || lower.startsWith('url:') + || lower.startsWith('org:') + ) { + return lower + } + if (lower.startsWith('http://') || lower.startsWith('https://')) { + return `url:${lower}` + } + return `acct:${lower}` +} + +function readClaudeConfigAccountKey(env: NodeJS.ProcessEnv = process.env): string | null { + const configDir = asNonEmptyString(env.CLAUDE_CONFIG_DIR) + const home = asNonEmptyString(env.HOME) ?? (env.VITEST === 'true' ? null : homedir()) + const candidates: string[] = [] + if (configDir) { + candidates.push(join(configDir, '.claude.json')) + } + if (home) { + candidates.push(join(home, '.claude.json')) + } + for (const filePath of candidates) { + if (!existsSync(filePath)) continue + try { + const parsed = asRecord(JSON.parse(readFileSync(filePath, 'utf8'))) + const oauthAccount = asRecord(parsed?.oauthAccount) + const identity = asNonEmptyString(oauthAccount?.emailAddress) + ?? asNonEmptyString(oauthAccount?.accountUuid) + if (identity) { + return `acct:${identity.toLowerCase()}` + } + } catch { + // Ignore malformed config file + } + } + return null +} + +export function resolveClaudeSessionAccountKey( + env: NodeJS.ProcessEnv = process.env, + explicitIdentity?: string | null +): string | null { + const explicit = normalizeClaudeAccountKey(explicitIdentity) + if (explicit) return explicit + const envCredKey = resolveClaudeEnvCredentialKey(env) + if (envCredKey) return envCredKey + const configKey = readClaudeConfigAccountKey(env) + if (configKey) return configKey + const baseUrl = asNonEmptyString(env.ANTHROPIC_BASE_URL) + if (baseUrl) return `url:${baseUrl.toLowerCase()}` + return null +} + +function claudeBucketCompositeKey(accountKey: string, rateLimitType: string): string { + return `${accountKey}::${rateLimitType}` +} + +function claudeBucketFileName(accountKey: string, rateLimitType: string): string { + return `claude-bucket-${shortHash(accountKey)}-${sanitizeKeySegment(rateLimitType)}.json` +} + +function parsePersistedClaudeBucket(raw: unknown): LiveClaudeBucketRecord | null { + const entry = asRecord(raw) + if (!entry) return null + const id = asNonEmptyString(entry.id) + const label = asNonEmptyString(entry.label) + const usedPercent = asFiniteNumber(entry.usedPercent) + const remainingPercent = asFiniteNumber(entry.remainingPercent) + const updatedAt = asFiniteNumber(entry.updatedAt) + const accountKey = normalizeClaudeAccountKey(asNonEmptyString(entry.accountKey)) + if (!id || !label || usedPercent === null || remainingPercent === null || updatedAt === null || !accountKey) { + return null + } + const rateLimitType = asNonEmptyString(entry.rateLimitType) ?? id.replace(/^claude-/, '') + return { + id, + label, + group: asNonEmptyString(entry.group), + window: asNonEmptyString(entry.window), + usedPercent, + remainingPercent, + resetsAt: asFiniteNumber(entry.resetsAt), + updatedAt, + accountKey, + rateLimitType + } +} + +function readPersistedLiveQuotaState(env: NodeJS.ProcessEnv = process.env): PersistedLiveQuotaState { + const dirPath = resolveLiveQuotaStateDir(env) + if (!dirPath || !existsSync(dirPath)) return {} + + let codexUpdatedAt: number | undefined + let agyTierLabel: string | null = null + let agyUpdatedAt: number | undefined + const claudeBuckets: Record = {} + + try { + const files = readdirSync(dirPath) + for (const name of files) { + if (!name.endsWith('.json') || name.endsWith('.tmp')) continue + const fullPath = join(dirPath, name) + try { + const parsed = asRecord(JSON.parse(readFileSync(fullPath, 'utf8'))) + if (!parsed) continue + if (name === 'codex.json') { + const ts = asFiniteNumber(parsed.updatedAt ?? parsed.codexUpdatedAt) + if (ts !== null && (codexUpdatedAt === undefined || ts > codexUpdatedAt)) { + codexUpdatedAt = ts + } + } else if (name === 'agy.json') { + const tier = asNonEmptyString(parsed.tierLabel ?? parsed.agyTierLabel) + const ts = asFiniteNumber(parsed.updatedAt) ?? 0 + if (tier && (agyUpdatedAt === undefined || ts >= agyUpdatedAt)) { + agyTierLabel = tier + agyUpdatedAt = ts + } + } else if (name.startsWith('claude-bucket-')) { + const bucket = parsePersistedClaudeBucket(parsed) + if (bucket) { + const compKey = claudeBucketCompositeKey(bucket.accountKey, bucket.rateLimitType) + const prev = claudeBuckets[compKey] + if (!prev || bucket.updatedAt >= prev.updatedAt) { + claudeBuckets[compKey] = bucket + } + } + } + } catch { + // Ignore individual file parse errors + } + } + } catch { + // Ignore directory read errors + } + + return { codexUpdatedAt, claudeBuckets, agyTierLabel, agyUpdatedAt } +} + +function getLatestLiveQuotaUpdateAt(env: NodeJS.ProcessEnv = process.env): number { + const persisted = readPersistedLiveQuotaState(env) + let latest = Math.max(persisted.codexUpdatedAt ?? 0, persisted.agyUpdatedAt ?? 0) + if (persisted.claudeBuckets) { + for (const entry of Object.values(persisted.claudeBuckets)) { + if (entry.updatedAt > latest) { + latest = entry.updatedAt + } + } + } + for (const entry of liveClaudeBuckets.values()) { + if (entry.updatedAt > latest) { + latest = entry.updatedAt + } + } + return latest +} + +export function recordCodexRateLimitsUpdate(params: unknown, env: NodeJS.ProcessEnv = process.env): void { + const record = asRecord(params) + if (!record) return + const now = Date.now() + cachedResponse = null + const dirPath = resolveLiveQuotaStateDir(env) + if (dirPath) { + writeAtomicJsonFile(join(dirPath, 'codex.json'), { updatedAt: now }) + } +} + +export function recordClaudeRateLimitEvent( + info: unknown, + env: NodeJS.ProcessEnv = process.env, + accountIdentity?: string | null +): void { + const record = asRecord(info) + if (!record) return + const status = asNonEmptyString(record.status)?.toLowerCase() + const rawUtilization = asFiniteNumber(record.utilization) + const effectiveUtilization = status === 'rejected' + ? (rawUtilization !== null ? Math.max(1, rawUtilization) : 1) + : rawUtilization + if (effectiveUtilization === null) return + + const rateLimitType = asNonEmptyString(record.rateLimitType) ?? 'default' + const explicitAccount = accountIdentity + ?? asNonEmptyString(record.accountEmail) + ?? asNonEmptyString(record.email) + const accountKey = resolveClaudeSessionAccountKey(env, explicitAccount) + cachedResponse = null + if (!accountKey) { + return + } + const compKey = claudeBucketCompositeKey(accountKey, rateLimitType) + + const existingInMemory = liveClaudeBuckets.get(compKey) + const existingPersisted = readPersistedLiveQuotaState(env).claudeBuckets?.[compKey] + const resetsAt = normalizeResetTimestampMs(record.resetsAt) + ?? existingInMemory?.resetsAt + ?? existingPersisted?.resetsAt + ?? null + + const usedPercent = status === 'rejected' + ? 100 + : clampPercent(effectiveUtilization <= 1 ? effectiveUtilization * 100 : effectiveUtilization) + const remainingPercent = clampPercent(100 - usedPercent) + const lowerType = rateLimitType.toLowerCase() + const window = lowerType.includes('5h') || lowerType.includes('five_hour') + ? '5h' + : lowerType.includes('7d') || lowerType.includes('seven_day') || lowerType.includes('week') + ? 'weekly' + : rateLimitType + const label = window === '5h' + ? '5h window' + : window === 'weekly' + ? 'Weekly (7d)' + : `Limit (${rateLimitType})` + + const bucketRecord: LiveClaudeBucketRecord = { + id: `claude-${rateLimitType}`, + label, + group: null, + window, + usedPercent, + remainingPercent, + resetsAt, + updatedAt: Date.now(), + accountKey, + rateLimitType + } + liveClaudeBuckets.set(compKey, bucketRecord) + cachedResponse = null + const dirPath = resolveLiveQuotaStateDir(env) + if (dirPath) { + writeAtomicJsonFile(join(dirPath, claudeBucketFileName(accountKey, rateLimitType)), bucketRecord) + } +} + +export function recordAgyTier(tierName: string | null | undefined, env: NodeJS.ProcessEnv = process.env): void { + const normalized = asNonEmptyString(tierName) + if (normalized) { + liveAgyTierLabel = normalized + cachedResponse = null + const dirPath = resolveLiveQuotaStateDir(env) + if (dirPath) { + writeAtomicJsonFile(join(dirPath, 'agy.json'), { + tierLabel: normalized, + updatedAt: Date.now() + }) + } + } +} + +export async function probeCodexQuota( + env: NodeJS.ProcessEnv = process.env, + timeoutMs: number = DEFAULT_PROVIDER_PROBE_TIMEOUT_MS +): Promise { + const updatedAt = Date.now() + const availability = getAgentAvailability('codex', env) + if (!availability.available) { + return { + agent: 'codex', + available: false, + status: 'unavailable', + buckets: [], + updatedAt + } + } + + const client = new CodexAppServerClient({ cwd: homedir() }) + let timeoutHandle: ReturnType | null = null + const timeoutPromise = new Promise((_, reject) => { + timeoutHandle = setTimeout(() => { + reject(new Error('Codex quota probe timed out')) + }, timeoutMs) + }) + + try { + return await Promise.race([ + (async (): Promise => { + await client.connect() + await client.initialize({ + clientInfo: { + name: 'hapi-codex-quota', + version: '1.0.0' + }, + capabilities: { + experimentalApi: true + } + }) + + let accountReadError: unknown = null + let rateLimitsReadError: unknown = null + const [accountRes, rateLimitsRes] = await Promise.all([ + client.readAccount().catch((error): AccountReadResponse => { + accountReadError = error + return {} + }), + client.readRateLimits().catch((error): AccountRateLimitsReadResponse => { + rateLimitsReadError = error + return {} + }) + ]) + + const account = accountRes.account + if (!account && accountRes.requiresOpenaiAuth) { + return { + agent: 'codex', + available: true, + status: 'unauthenticated', + buckets: [], + note: 'Not signed in to Codex', + updatedAt + } + } + + const email = asNonEmptyString(account?.email) + const accountType = asNonEmptyString(account?.type) + const accountLabel = email ?? (accountType === 'apiKey' ? 'OpenAI API Key' : null) + const planLabel = formatPlanName( + asNonEmptyString(account?.planType) ?? asNonEmptyString(rateLimitsRes.rateLimits?.planType) + ) + const resetCount = asFiniteNumber(rateLimitsRes.rateLimitResetCredits?.availableCount) + const creditsLabel = formatCodexCredits(rateLimitsRes.rateLimits, resetCount) + const buckets = extractCodexQuotaBuckets(rateLimitsRes) + + if (accountType === 'apiKey' && buckets.length === 0 && !rateLimitsReadError) { + return { + agent: 'codex', + available: true, + status: 'custom_provider', + accountLabel, + planLabel: planLabel ?? 'API Key', + creditsLabel, + buckets: [], + note: 'Authenticated via OpenAI API key', + updatedAt + } + } + + const readError = rateLimitsReadError ?? accountReadError + if (readError !== null) { + return { + agent: 'codex', + available: true, + status: 'error', + accountLabel, + planLabel, + creditsLabel, + buckets, + note: readError instanceof Error ? readError.message : 'Failed to query Codex quota', + updatedAt + } + } + + return { + agent: 'codex', + available: true, + status: 'ok', + accountLabel, + planLabel, + creditsLabel, + buckets, + note: rateLimitsRes.rateLimits?.spendControlReached ? 'Spend control limit reached' : null, + updatedAt + } + })(), + timeoutPromise + ]) + } catch (error) { + return { + agent: 'codex', + available: true, + status: 'error', + buckets: [], + note: error instanceof Error ? error.message : 'Failed to query Codex quota', + updatedAt + } + } finally { + if (timeoutHandle) clearTimeout(timeoutHandle) + // Bound disconnect cleanup so a hung subprocess cannot stall the RPC response + await Promise.race([ + client.disconnect().catch(() => undefined), + new Promise((resolve) => setTimeout(resolve, 250)) + ]) + } +} + +export function parseAgyUsageCommandJson(stdout: string): { + buckets: AgentQuotaBucket[] + unauthenticated?: boolean +} | null { + const lower = stdout.toLowerCase() + if ( + lower.includes('authentication required') + || lower.includes('please sign in') + || lower.includes('not logged in') + ) { + return { buckets: [], unauthenticated: true } + } + + for (const line of stdout.split('\n')) { + const trimmed = line.trim() + if (!trimmed.startsWith('{')) continue + let parsed: unknown + try { + parsed = JSON.parse(trimmed) + } catch { + continue + } + const root = asRecord(parsed) + const command = asRecord(root?.command) + if (command?.name !== 'usage') continue + const data = asRecord(command.data) + const groups = Array.isArray(data?.groups) ? data.groups : [] + const buckets: AgentQuotaBucket[] = [] + + for (const rawGroup of groups) { + const group = asRecord(rawGroup) + if (!group) continue + const groupName = asNonEmptyString(group.name) ?? 'Models' + const groupBuckets = Array.isArray(group.buckets) ? group.buckets : [] + for (const rawBucket of groupBuckets) { + const bucket = asRecord(rawBucket) + if (!bucket) continue + const fraction = asFiniteNumber(bucket.remaining_fraction) + if (fraction === null) continue + const remainingPercent = clampPercent(fraction * 100) + const usedPercent = clampPercent(100 - remainingPercent) + const window = asNonEmptyString(bucket.window) + const bucketName = asNonEmptyString(bucket.name) ?? (window ?? 'Quota') + const shortWindow = window === '5h' + ? '5h' + : window === 'weekly' + ? 'Weekly' + : bucketName + const id = asNonEmptyString(bucket.id) ?? `${groupName}-${shortWindow}` + const resetsAt = normalizeResetTimestampMs(bucket.reset_time) + buckets.push({ + id, + label: `${groupName} · ${shortWindow}`, + group: groupName, + window, + usedPercent, + remainingPercent, + resetsAt + }) + } + } + return { buckets } + } + return null +} + +export function parseAgyCreditsCommandJson(stdout: string): number | null { + for (const line of stdout.split('\n')) { + const trimmed = line.trim() + if (!trimmed.startsWith('{')) continue + let parsed: unknown + try { + parsed = JSON.parse(trimmed) + } catch { + continue + } + const root = asRecord(parsed) + const command = asRecord(root?.command) + if (command?.name !== 'credits') continue + const data = asRecord(command.data) + const remaining = asFiniteNumber(data?.remaining_credits) + if (remaining !== null) return remaining + } + return null +} + +function runAgyHeadlessCommand(command: string, promptCommand: string, env: NodeJS.ProcessEnv): Promise<{ stdout: string; stderr: string }> { + return new Promise((resolve, reject) => { + const child = spawn(command, ['-p', promptCommand, '--output-format', 'json'], { + cwd: homedir(), + env: buildAgyAcpEnv(env), + stdio: ['ignore', 'pipe', 'pipe'], + shell: false, + windowsHide: process.platform === 'win32' + }) + + let stdout = '' + let stderr = '' + let settled = false + + const finish = (cb: () => void) => { + if (settled) return + settled = true + clearTimeout(timer) + cb() + } + + const timer = setTimeout(() => { + void killProcessByChildProcess(child, true).catch(() => undefined) + finish(() => reject(new Error(`Antigravity ${promptCommand} timed out`))) + }, AGY_PROBE_TIMEOUT_MS) + + child.stdout?.on('data', (chunk) => { + stdout += chunk.toString() + }) + child.stderr?.on('data', (chunk) => { + stderr += chunk.toString() + }) + child.on('error', (error) => { + finish(() => reject(error)) + }) + child.on('close', () => { + finish(() => resolve({ stdout, stderr })) + }) + }) +} + +export async function probeAgyQuota(env: NodeJS.ProcessEnv = process.env): Promise { + const updatedAt = Date.now() + const availability = getAgentAvailability('agy', env) + if (!availability.available) { + return { + agent: 'agy', + available: false, + status: 'unavailable', + buckets: [], + updatedAt + } + } + + const executable = getAgentLaunchCommand('agy', env) + try { + const [usageOut, creditsOut] = await Promise.all([ + runAgyHeadlessCommand(executable, '/usage', env), + runAgyHeadlessCommand(executable, '/credits', env).catch(() => ({ stdout: '', stderr: '' })) + ]) + + const parsedUsage = parseAgyUsageCommandJson(`${usageOut.stdout}\n${usageOut.stderr}`) + if (parsedUsage?.unauthenticated) { + return { + agent: 'agy', + available: true, + status: 'unauthenticated', + buckets: [], + note: 'Not signed in to Antigravity', + updatedAt + } + } + + if (!parsedUsage) { + return { + agent: 'agy', + available: true, + status: 'error', + buckets: [], + note: 'Unable to parse Antigravity quota output', + updatedAt + } + } + + const remainingCredits = parseAgyCreditsCommandJson(creditsOut.stdout) + const creditsLabel = remainingCredits !== null && remainingCredits > 0 + ? `${remainingCredits.toLocaleString('en-US')} G1 credits` + : null + + return { + agent: 'agy', + available: true, + status: 'ok', + accountLabel: null, + planLabel: liveAgyTierLabel ?? readPersistedLiveQuotaState(env).agyTierLabel ?? null, + creditsLabel, + buckets: parsedUsage.buckets, + updatedAt + } + } catch (error) { + return { + agent: 'agy', + available: true, + status: 'error', + buckets: [], + note: error instanceof Error ? error.message : 'Failed to query Antigravity quota', + updatedAt + } + } +} + +type ClaudeControlProbeResult = { + account: RecordValue | null + statusRows: Map +} + +export function parseClaudeQuotaControlLine( + line: string, + target: ClaudeControlProbeResult +): { initDone: boolean; statusDone: boolean } { + const trimmed = line.trim() + if (!trimmed.startsWith('{')) return { initDone: false, statusDone: false } + let parsed: unknown + try { + parsed = JSON.parse(trimmed) + } catch { + return { initDone: false, statusDone: false } + } + const message = asRecord(parsed) + if (message?.type !== 'control_response') return { initDone: false, statusDone: false } + const response = asRecord(message.response) + const reqId = asNonEmptyString(response?.request_id) + const inner = asRecord(response?.response) + + if (reqId === CLAUDE_INIT_REQ_ID) { + target.account = asRecord(inner?.account) + return { initDone: true, statusDone: false } + } + if (reqId === CLAUDE_STATUS_REQ_ID) { + const sections = Array.isArray(inner?.sections) ? inner.sections : [] + for (const rawSection of sections) { + const section = asRecord(rawSection) + const rows = Array.isArray(section?.rows) ? section.rows : [] + for (const rawRow of rows) { + const row = asRecord(rawRow) + const label = asNonEmptyString(row?.label) + const value = asNonEmptyString(row?.value) + if (label && value) { + target.statusRows.set(label, value) + } + } + } + return { initDone: false, statusDone: true } + } + return { initDone: false, statusDone: false } +} + +function runClaudeStatusProbe(executable: string, env: NodeJS.ProcessEnv): Promise { + const args = [ + '--print', + '--input-format', 'stream-json', + '--output-format', 'stream-json', + '--verbose', + '--setting-sources', 'user', + '--strict-mcp-config', + '--settings', JSON.stringify({ disableAllHooks: true }) + ] + + return new Promise((resolve, reject) => { + const child = spawn(executable, args, { + cwd: homedir(), + env: withBunRuntimeEnv(env, { allowBunBeBun: false }), + stdio: ['pipe', 'pipe', 'pipe'], + shell: false, + windowsHide: process.platform === 'win32' + }) + + const result: ClaudeControlProbeResult = { + account: null, + statusRows: new Map() + } + let initDone = false + let statusDone = false + let stdoutBuffer = '' + let stderr = '' + let settled = false + + const finish = (cb: () => void) => { + if (settled) return + settled = true + clearTimeout(timer) + if (child.pid) { + void (async () => { + await killProcessByChildProcess(child, false).catch(() => false) + await killProcessByChildProcess(child, true).catch(() => false) + })() + } + cb() + } + + const timer = setTimeout(() => { + finish(() => { + if (initDone || statusDone) { + resolve(result) + } else { + reject(new Error('Claude status probe timed out')) + } + }) + }, CLAUDE_PROBE_TIMEOUT_MS) + + child.stdout?.on('data', (chunk) => { + stdoutBuffer += chunk.toString() + let idx = stdoutBuffer.indexOf('\n') + while (idx !== -1 && !settled) { + const line = stdoutBuffer.slice(0, idx) + stdoutBuffer = stdoutBuffer.slice(idx + 1) + idx = stdoutBuffer.indexOf('\n') + const step = parseClaudeQuotaControlLine(line, result) + if (step.initDone) initDone = true + if (step.statusDone) statusDone = true + if (initDone && statusDone) { + finish(() => resolve(result)) + return + } + } + }) + child.stderr?.on('data', (chunk) => { + stderr += chunk.toString() + }) + child.on('error', (error) => { + finish(() => reject(error)) + }) + child.on('close', (code) => { + finish(() => { + if (initDone || statusDone) { + resolve(result) + } else { + reject(new Error(stderr.trim() || `Claude exited with code ${code ?? 'unknown'}`)) + } + }) + }) + child.stdin?.on('error', () => { /* handled via close */ }) + child.stdin?.write( + `${JSON.stringify({ type: 'control_request', request_id: CLAUDE_INIT_REQ_ID, request: { subtype: 'initialize' } })}\n` + + `${JSON.stringify({ type: 'control_request', request_id: CLAUDE_STATUS_REQ_ID, request: { subtype: 'get_status' } })}\n` + ) + }) +} + +function computeProbedClaudeAccountKey(params: { + email: string | null + accountUuid?: string | null + baseUrl: string | null + organization: string | null +}): string | null { + if (params.email) return `acct:${params.email.toLowerCase()}` + if (params.accountUuid) return `acct:${params.accountUuid.toLowerCase()}` + if (params.baseUrl) return `url:${params.baseUrl.toLowerCase()}` + if (params.organization) return `org:${params.organization.toLowerCase()}` + return null +} + +export function getActiveClaudeBuckets( + env: NodeJS.ProcessEnv = process.env, + allowedAccountKeys?: ReadonlySet +): AgentQuotaBucket[] { + const now = Date.now() + const defaultSessionKey = resolveClaudeSessionAccountKey(env) + const effectiveAllowed = allowedAccountKeys + ?? (defaultSessionKey ? new Set([defaultSessionKey]) : new Set()) + if (effectiveAllowed.size === 0) return [] + const byRateLimitType = new Map() + const persisted = readPersistedLiveQuotaState(env) + + const consider = (compKey: string, entry: LiveClaudeBucketRecord) => { + if (!effectiveAllowed.has(entry.accountKey)) return + if (entry.resetsAt && entry.resetsAt <= now) { + liveClaudeBuckets.delete(compKey) + return + } + const existing = byRateLimitType.get(entry.rateLimitType) + if (!existing || entry.updatedAt >= existing.updatedAt) { + byRateLimitType.set(entry.rateLimitType, entry) + } + } + + if (persisted.claudeBuckets) { + for (const [compKey, entry] of Object.entries(persisted.claudeBuckets)) { + consider(compKey, entry) + } + } + for (const [compKey, entry] of liveClaudeBuckets.entries()) { + consider(compKey, entry) + } + + const buckets: AgentQuotaBucket[] = [] + for (const entry of byRateLimitType.values()) { + const { + updatedAt: _updatedAt, + accountKey: _accountKey, + rateLimitType: _rateLimitType, + ...bucket + } = entry + buckets.push(bucket) + } + return buckets +} + +let claudeStatusProbeOverrideForTests: ((executable: string, env: NodeJS.ProcessEnv) => Promise) | null = null + +export function _setClaudeStatusProbeForTests( + fn: ((executable: string, env: NodeJS.ProcessEnv) => Promise) | null +): void { + claudeStatusProbeOverrideForTests = fn +} + +export async function probeClaudeQuota(env: NodeJS.ProcessEnv = process.env): Promise { + const updatedAt = Date.now() + const availability = getAgentAvailability('claude', env) + if (!availability.available) { + return { + agent: 'claude', + available: false, + status: 'unavailable', + buckets: [], + updatedAt + } + } + + try { + const probeRunner = claudeStatusProbeOverrideForTests ?? runClaudeStatusProbe + const executable = claudeStatusProbeOverrideForTests ? 'claude' : getDefaultClaudeCodePath(env) + const probe = await probeRunner(executable, env) + const rows = probe.statusRows + const account = probe.account + + const loginRow = rows.get('Login') + if (loginRow && loginRow.toLowerCase().startsWith('expired')) { + return { + agent: 'claude', + available: true, + status: 'unauthenticated', + accountLabel: rows.get('Email') ?? null, + buckets: [], + note: loginRow, + updatedAt + } + } + + const email = rows.get('Email') ?? asNonEmptyString(account?.email) + const baseUrl = rows.get('Anthropic base URL') + ?? rows.get('Gateway URL') + ?? rows.get('Bedrock base URL') + ?? rows.get('Vertex base URL') + ?? asNonEmptyString(env.ANTHROPIC_BASE_URL) + const loginMethod = rows.get('Login method') + ?? asNonEmptyString(account?.subscriptionType) + const authTokenSource = rows.get('Auth token') + ?? rows.get('API key') + ?? asNonEmptyString(account?.tokenSource) + const apiProvider = rows.get('API provider') + ?? asNonEmptyString(account?.apiProvider) + const organization = rows.get('Organization') + + if (!email && !authTokenSource && !loginMethod && !baseUrl) { + return { + agent: 'claude', + available: true, + status: 'unauthenticated', + buckets: [], + note: 'Not signed in to Claude Code', + updatedAt + } + } + + const probedAccountKey = computeProbedClaudeAccountKey({ + email: email ?? null, + accountUuid: asNonEmptyString(account?.accountUuid), + baseUrl: baseUrl ?? null, + organization: organization ?? null + }) + const allowedKeys = new Set() + if (probedAccountKey) { + allowedKeys.add(probedAccountKey) + } + const envCredKey = resolveClaudeEnvCredentialKey(env) + if (envCredKey) { + allowedKeys.add(envCredKey) + } + if (!probedAccountKey && !envCredKey) { + const configKey = readClaudeConfigAccountKey(env) + if (configKey) { + allowedKeys.add(configKey) + } + } + + const buckets = getActiveClaudeBuckets(env, allowedKeys) + + const isCustomProvider = Boolean(baseUrl) || (apiProvider !== null && apiProvider !== 'firstParty') || (!loginMethod && Boolean(authTokenSource)) + const accountLabel = email ?? baseUrl ?? organization ?? authTokenSource + const planLabel = loginMethod + ? loginMethod.replace(/\s+account$/i, '') + : authTokenSource ?? apiProvider ?? null + + if (isCustomProvider && buckets.length === 0) { + const noteParts: string[] = [] + if (baseUrl) noteParts.push(`Endpoint: ${baseUrl}`) + if (authTokenSource) noteParts.push(`Auth: ${authTokenSource}`) + return { + agent: 'claude', + available: true, + status: 'custom_provider', + accountLabel, + planLabel, + buckets: [], + note: noteParts.join(' · ') || 'Custom provider endpoint (no fixed subscription window)', + updatedAt + } + } + + return { + agent: 'claude', + available: true, + status: 'ok', + accountLabel, + planLabel, + buckets, + note: buckets.length === 0 ? 'Quota utilization updates on the next Claude turn' : null, + updatedAt + } + } catch (error) { + return { + agent: 'claude', + available: true, + status: 'error', + buckets: getActiveClaudeBuckets(env), + note: error instanceof Error ? error.message : 'Failed to query Claude status', + updatedAt + } + } +} + +export async function getAgentQuotasResponse(options?: { + refresh?: boolean + env?: NodeJS.ProcessEnv + probeTimeoutMs?: number +}): Promise { + const refresh = options?.refresh === true + const env = options?.env ?? process.env + const probeTimeoutMs = options?.probeTimeoutMs ?? DEFAULT_PROVIDER_PROBE_TIMEOUT_MS + const now = Date.now() + const latestLiveUpdateAt = getLatestLiveQuotaUpdateAt(env) + + if ( + !refresh + && cachedResponse + && cachedResponse.expiresAt > now + && latestLiveUpdateAt <= cachedResponse.startedAt + ) { + return cachedResponse.response + } + + if (!refresh && inflightPromise) { + return await inflightPromise + } + + const startedAt = Date.now() + const promise = (async (): Promise => { + const accounts = await Promise.all([ + probeCodexQuota(env, probeTimeoutMs), + probeAgyQuota(env), + probeClaudeQuota(env) + ]) + const fetchedAt = Date.now() + const response: AgentQuotasResponse = { + accounts, + fetchedAt + } + cachedResponse = { + startedAt, + expiresAt: fetchedAt + CACHE_TTL_MS, + response + } + return response + })().finally(() => { + if (inflightPromise === promise) { + inflightPromise = null + } + }) + + inflightPromise = promise + return await promise +} + +export function _resetAgentQuotasCacheForTests(): void { + cachedResponse = null + inflightPromise = null + liveClaudeBuckets.clear() + liveAgyTierLabel = null + claudeStatusProbeOverrideForTests = null +} diff --git a/cli/src/api/apiMachine.ts b/cli/src/api/apiMachine.ts index 73ad5f4d..c1e9aa56 100644 --- a/cli/src/api/apiMachine.ts +++ b/cli/src/api/apiMachine.ts @@ -16,6 +16,8 @@ import { ListPiSessionsRpcRequestSchema, type ArchiveCodexSessionRpcResponse, type AgentAvailabilityResponse, + type AgentQuotasRequest, + type AgentQuotasResponse, type ListCodexSessionsRpcResponse, type ListOpencodeSessionsRpcResponse, type ListPiSessionsRpcResponse, @@ -77,6 +79,7 @@ import { homedir } from 'node:os' import type { CursorChatStoreStatus } from '@hapi/protocol/apiTypes' import { MachinePathPolicy } from './machinePathPolicy' import { getAgentAvailabilityResponse } from '@/agent/agentAvailability' +import { getAgentQuotasResponse } from '@/agent/agentQuotas' export { normalizeWindowsDriveRoot } from './machinePathPolicy' @@ -203,6 +206,11 @@ export class ApiMachineClient { async () => getAgentAvailabilityResponse() ) + this.rpcHandlerManager.registerHandler( + RPC_METHODS.AgentQuotas, + async (params) => await getAgentQuotasResponse({ refresh: params?.refresh === true }) + ) + this.rpcHandlerManager.registerHandler(RPC_METHODS.PathExists, async (params) => { const rawPaths = Array.isArray(params?.paths) ? params.paths : [] const uniquePaths = Array.from(new Set(rawPaths.filter((path): path is string => typeof path === 'string'))) diff --git a/cli/src/claude/claudeRemote.ts b/cli/src/claude/claudeRemote.ts index befccace..52510a5d 100644 --- a/cli/src/claude/claudeRemote.ts +++ b/cli/src/claude/claudeRemote.ts @@ -91,6 +91,7 @@ export async function claudeRemote(opts: { onThinkingChange?: (thinking: boolean) => void, onMessage: (message: SDKMessage) => void, onContextUsage?: (usage: { model?: string, maxTokens?: number }) => void, + onAccountIdentity?: (accountIdentity: string | null) => void, onFirstResult?: (initialMessage: string) => void, /** * The delivered input finished at the SDK boundary although onReady is @@ -687,6 +688,15 @@ export async function claudeRemote(opts: { }); } + if ( + opts.onAccountIdentity + && typeof (response as { getAccountIdentity?: () => Promise }).getAccountIdentity === 'function' + ) { + response.getAccountIdentity().then(opts.onAccountIdentity, (e) => { + logger.debug('[claudeRemote] getAccountIdentity failed', e); + }); + } + // Claude silently starts in default when plan/auto is unavailable // (e.g. auto disabled by settings); surface it instead of // showing a mode that is not in effect. diff --git a/cli/src/claude/claudeRemoteLauncher.ts b/cli/src/claude/claudeRemoteLauncher.ts index 607d78e6..e0d10b77 100644 --- a/cli/src/claude/claudeRemoteLauncher.ts +++ b/cli/src/claude/claudeRemoteLauncher.ts @@ -626,6 +626,7 @@ class ClaudeRemoteLauncher extends RemoteLauncherBase { claudeArgs: session.claudeArgs, onMessage, onContextUsage: (usage) => sdkToLogConverter.applyContextUsage(usage.model, usage.maxTokens), + onAccountIdentity: (identity) => sdkToLogConverter.updateAccountIdentity?.(identity), onFirstResult: (initialMessage) => { // SDK streams omit Claude Code's native ai-title; it is only in the transcript. const sessionId = session.sessionId; diff --git a/cli/src/claude/sdk/query.ts b/cli/src/claude/sdk/query.ts index 7138b316..84894885 100644 --- a/cli/src/claude/sdk/query.ts +++ b/cli/src/claude/sdk/query.ts @@ -196,6 +196,36 @@ export class Query implements AsyncIterableIterator { return response.response ?? {} } + /** + * Query the running Claude process for its authenticated account/provider identity. + */ + async getAccountIdentity(): Promise { + if (!this.childStdin) { + throw new Error('getAccountIdentity requires --input-format stream-json') + } + + const response = await this.request({ + subtype: 'initialize' + } as unknown as ControlRequest, this.childStdin) as { + response?: { + account?: { + email?: string + accountUuid?: string + tokenSource?: string + apiProvider?: string + } + } + } + const account = response.response?.account + if (typeof account?.email === 'string' && account.email.trim()) { + return `acct:${account.email.trim().toLowerCase()}` + } + if (typeof account?.accountUuid === 'string' && account.accountUuid.trim()) { + return `acct:${account.accountUuid.trim().toLowerCase()}` + } + return null + } + /** * Change Claude's native permission mode without restarting the process */ diff --git a/cli/src/claude/utils/sdkToLogConverter.ts b/cli/src/claude/utils/sdkToLogConverter.ts index f0ff2ae1..d21384ca 100644 --- a/cli/src/claude/utils/sdkToLogConverter.ts +++ b/cli/src/claude/utils/sdkToLogConverter.ts @@ -5,6 +5,7 @@ import { randomUUID } from 'node:crypto' import { execSync } from 'node:child_process' +import { recordClaudeRateLimitEvent, resolveClaudeSessionAccountKey } from '@/agent/agentQuotas' import type { SDKMessage, SDKUserMessage, @@ -55,6 +56,7 @@ export interface ConversionContext { // the only turn-1 signal that such a session is 1M. Used only to seed the very first // contextWindow estimate before result.modelUsage confirms the real value. selectedModel?: string | null + accountIdentity?: string | null } type PermissionResponse = { @@ -108,6 +110,7 @@ export class SDKToLogConverter { // window (capped by DISABLE_1M / autoCompactWindow), so a result's raw contextWindow // must not overwrite it. private contextUsageKeys = new Set() + private accountIdentity: string | null constructor( context: Omit, @@ -120,6 +123,7 @@ export class SDKToLogConverter { parentUuid: null } this.responses = responses + this.accountIdentity = resolveClaudeSessionAccountKey(process.env, context.accountIdentity) } /** @@ -191,6 +195,20 @@ export class SDKToLogConverter { this.context.sessionId = sessionId } + /** + * Bind the session's verified Claude account/provider identity so all subsequent + * rate_limit_event observations from this session stay attributed to its account. + * Retains any credential-specific binding captured at session startup when + * initialize returns no verified account identity. + */ + updateAccountIdentity(accountIdentity: string | null | undefined): void { + if (!accountIdentity) return + const verified = resolveClaudeSessionAccountKey({}, accountIdentity) + if (verified) { + this.accountIdentity = verified + } + } + /** * Reset parent chain (useful when starting new conversation) */ @@ -208,6 +226,8 @@ export class SDKToLogConverter { const info = (sdkMessage as any).rate_limit_info if (typeof info !== 'object' || info === null) return null + recordClaudeRateLimitEvent(info, process.env, this.accountIdentity) + const { status, resetsAt, utilization, rateLimitType } = info if (status === 'allowed') return null @@ -384,6 +404,18 @@ export class SDKToLogConverter { this.updateSessionId(systemMsg.session_id) } + if (systemMsg.subtype === 'init') { + const initAccount = (systemMsg as unknown as { account?: { email?: unknown }; email?: unknown }).account + const initEmail = typeof initAccount?.email === 'string' + ? initAccount.email + : typeof (systemMsg as unknown as { email?: unknown }).email === 'string' + ? (systemMsg as unknown as { email: string }).email + : null + if (initEmail) { + this.updateAccountIdentity(initEmail) + } + } + // Capture the resolved model name on init. The remote launcher re-emits // system/init on every turn for the lifetime of this converter, so if we // already learned this model's real contextWindow from a previous result diff --git a/cli/src/codex/appServerTypes.ts b/cli/src/codex/appServerTypes.ts index 8d6dc4dc..f70fce25 100644 --- a/cli/src/codex/appServerTypes.ts +++ b/cli/src/codex/appServerTypes.ts @@ -387,3 +387,54 @@ export interface ExperimentalFeatureEnablementSetResponse { enablement: Record; [key: string]: unknown; } + +export interface CodexAccountInfo { + type?: string | null; + email?: string | null; + planType?: string | null; + [key: string]: unknown; +} + +export interface AccountReadResponse { + account?: CodexAccountInfo | null; + requiresOpenaiAuth?: boolean; + [key: string]: unknown; +} + +export interface CodexRateLimitWindow { + usedPercent?: number | null; + windowDurationMins?: number | null; + resetsAt?: number | null; + [key: string]: unknown; +} + +export interface CodexRateLimitCredits { + hasCredits?: boolean | null; + unlimited?: boolean | null; + balance?: string | number | null; + [key: string]: unknown; +} + +export interface CodexRateLimitEntry { + limitId?: string | null; + limitName?: string | null; + normalModelSlug?: string | null; + primary?: CodexRateLimitWindow | null; + secondary?: CodexRateLimitWindow | null; + credits?: CodexRateLimitCredits | null; + planType?: string | null; + spendControlReached?: boolean | null; + rateLimitReachedType?: string | null; + [key: string]: unknown; +} + +export interface AccountRateLimitsReadResponse { + ordinaryUsageAllowed?: boolean; + rateLimits?: CodexRateLimitEntry | null; + rateLimitsByLimitId?: Record | null; + rateLimitResetCredits?: { + availableCount?: number | null; + [key: string]: unknown; + } | null; + [key: string]: unknown; +} diff --git a/cli/src/codex/codexAppServerClient.ts b/cli/src/codex/codexAppServerClient.ts index 06a75415..a23860dd 100644 --- a/cli/src/codex/codexAppServerClient.ts +++ b/cli/src/codex/codexAppServerClient.ts @@ -8,6 +8,8 @@ import { CODEX_WEBSOCKET_MAX_PAYLOAD } from './websocketLimits'; import { resolveModelCatalogArgs } from './utils/modelCatalog'; import { resolveSelectedCodexCommand } from './utils/codexExecutable'; import type { + AccountRateLimitsReadResponse, + AccountReadResponse, CollaborationModeListResponse, InitializeParams, InitializeResponse, @@ -366,6 +368,20 @@ export class CodexAppServerClient extends JsonLineParser { return response as ModelListResponse; } + async readAccount(): Promise { + const response = await this.sendRequest('account/read', {}, { + timeoutMs: 15_000 + }); + return response as AccountReadResponse; + } + + async readRateLimits(): Promise { + const response = await this.sendRequest('account/rateLimits/read', {}, { + timeoutMs: 15_000 + }); + return response as AccountRateLimitsReadResponse; + } + async listSkills(params: SkillsListParams): Promise { const response = await this.sendRequest('skills/list', params, { timeoutMs: 30_000 diff --git a/cli/src/codex/utils/appServerEventConverter.ts b/cli/src/codex/utils/appServerEventConverter.ts index a64f450a..78b113f4 100644 --- a/cli/src/codex/utils/appServerEventConverter.ts +++ b/cli/src/codex/utils/appServerEventConverter.ts @@ -1,5 +1,6 @@ import { INCLUSIVE_INPUT_TOKEN_USAGE_MARKER } from '@hapi/protocol/usage'; import { fileURLToPath } from 'node:url'; +import { recordCodexRateLimitsUpdate } from '@/agent/agentQuotas'; import { logger } from '@/ui/logger'; import { codexAssistantText } from './assistantText'; @@ -679,6 +680,7 @@ export class AppServerEventConverter { } if (method === 'account/rateLimits/updated') { + recordCodexRateLimitsUpdate(paramsRecord); return events; } diff --git a/hub/src/store/index.ts b/hub/src/store/index.ts index d0261c0e..b0323660 100644 --- a/hub/src/store/index.ts +++ b/hub/src/store/index.ts @@ -420,11 +420,13 @@ export class Store { // Backfill any *missing* tables (sessions, machines, ...) that // a partially-built legacy DB may not have yet. this.createSchema() + this.ensureUsageScanParserVersion() this.setUserVersion(SCHEMA_VERSION) return } this.createSchema() + this.ensureUsageScanParserVersion() this.setUserVersion(SCHEMA_VERSION) return } @@ -441,7 +443,9 @@ export class Store { this.migrateFromV30ToV31() this.migrateFromV31ToV32() this.migrateFromV32ToV33() + this.migrateFromV33ToV34() this.migrateFromV34ToV35() + this.ensureUsageScanParserVersion() this.setUserVersion(SCHEMA_VERSION) return } @@ -451,6 +455,7 @@ export class Store { if (!step) throw this.buildSchemaMismatchError(currentVersion) step() } + this.ensureUsageScanParserVersion() this.setUserVersion(SCHEMA_VERSION) return } @@ -460,6 +465,7 @@ export class Store { } this.assertRequiredTablesPresent() + this.ensureUsageScanParserVersion() } private createSchema(): void { @@ -660,6 +666,7 @@ export class Store { session_id TEXT PRIMARY KEY, message_epoch INTEGER NOT NULL DEFAULT 0, last_seq INTEGER NOT NULL DEFAULT 0, + parser_version INTEGER NOT NULL DEFAULT 2, FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE ); @@ -1055,6 +1062,7 @@ export class Store { session_id TEXT PRIMARY KEY, message_epoch INTEGER NOT NULL DEFAULT 0, last_seq INTEGER NOT NULL DEFAULT 0, + parser_version INTEGER NOT NULL DEFAULT 2, FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE ); DELETE FROM usage_events; @@ -1074,6 +1082,7 @@ export class Store { session_id TEXT PRIMARY KEY, message_epoch INTEGER NOT NULL DEFAULT 0, last_seq INTEGER NOT NULL DEFAULT 0, + parser_version INTEGER NOT NULL DEFAULT 2, FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE ); DELETE FROM usage_scan_state; @@ -1372,6 +1381,15 @@ export class Store { `) } + private ensureUsageScanParserVersion(): void { + const columns = this.db.prepare('PRAGMA table_info(usage_scan_state)').all() as Array<{ name: string }> + if (columns.length === 0) return + if (!columns.some((col) => col.name === 'parser_version')) { + this.db.exec('ALTER TABLE usage_scan_state ADD COLUMN parser_version INTEGER NOT NULL DEFAULT 2') + this.db.exec('DELETE FROM usage_scan_state') + } + } + private getUserVersion(): number { const row = this.db.prepare('PRAGMA user_version').get() as { user_version: number } | undefined return row?.user_version ?? 0 diff --git a/hub/src/store/usage.ts b/hub/src/store/usage.ts index 3c3644fe..7afba156 100644 --- a/hub/src/store/usage.ts +++ b/hub/src/store/usage.ts @@ -25,6 +25,8 @@ export type UsageScanState = { lastSeq: number } +export const USAGE_SCAN_PARSER_VERSION = 2 + type UsageEventRow = { session_id: string source_key: string @@ -161,17 +163,20 @@ export function recordUsageScan( } db.prepare(` - INSERT INTO usage_scan_state (session_id, message_epoch, last_seq) - VALUES (?, ?, ?) + INSERT INTO usage_scan_state (session_id, message_epoch, last_seq, parser_version) + VALUES (?, ?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET message_epoch = excluded.message_epoch, last_seq = CASE WHEN usage_scan_state.message_epoch = excluded.message_epoch + AND usage_scan_state.parser_version = excluded.parser_version THEN MAX(usage_scan_state.last_seq, excluded.last_seq) ELSE excluded.last_seq - END + END, + parser_version = excluded.parser_version WHERE excluded.message_epoch >= usage_scan_state.message_epoch - `).run(sessionId, messageEpoch, lastSeq) + OR usage_scan_state.parser_version < excluded.parser_version + `).run(sessionId, messageEpoch, lastSeq, USAGE_SCAN_PARSER_VERSION) })() } @@ -212,7 +217,8 @@ export function getUsageScanStates(db: Database, sessionIds: string[]): Map + AND parser_version = ? + `).all(...sessionIds, USAGE_SCAN_PARSER_VERSION) as Array<{ session_id: string; message_epoch: number; last_seq: number }> return new Map(rows.map((row) => [row.session_id, { messageEpoch: row.message_epoch, diff --git a/hub/src/sync/rpcGateway.ts b/hub/src/sync/rpcGateway.ts index 5d1fd9d4..05c02b34 100644 --- a/hub/src/sync/rpcGateway.ts +++ b/hub/src/sync/rpcGateway.ts @@ -3,6 +3,7 @@ import { PERMISSION_REQUEST_NOT_FOUND_MESSAGE, RPC_METHODS } from '@hapi/protoco import { ArchiveCodexSessionRpcResponseSchema, AgentAvailabilityResponseSchema, + AgentQuotasResponseSchema, CursorChatStoreStatusSchema, ListCodexSessionsRpcResponseSchema, ListOpencodeSessionsRpcResponseSchema, @@ -12,6 +13,7 @@ import type { AgyModelsResponse, ClaudeModelsResponse, AgentAvailabilityResponse, + AgentQuotasResponse, CodexModelSummary, CodexModelsResponse, CommandResponse, @@ -375,6 +377,12 @@ export class RpcGateway { return AgentAvailabilityResponseSchema.parse(result) } + async getAgentQuotas(machineId: string, options?: { refresh?: boolean }): Promise { + const params = options?.refresh ? { refresh: true } : {} + const result = await this.machineRpc(machineId, RPC_METHODS.AgentQuotas, params, 20_000) + return AgentQuotasResponseSchema.parse(result) + } + async checkPathsExist(machineId: string, paths: string[]): Promise { const result = await this.machineRpc(machineId, RPC_METHODS.PathExists, { paths }) as RpcPathExistsResponse | unknown if (!result || typeof result !== 'object') { diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index d5dfddb0..289e6d9e 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -5385,6 +5385,10 @@ export class SyncEngine { return await this.rpcGateway.getAgentAvailability(machineId) } + async getAgentQuotas(machineId: string, options?: { refresh?: boolean }): ReturnType { + return await this.rpcGateway.getAgentQuotas(machineId, options) + } + async listMachineDirectory(machineId: string, path: string, includeHidden?: boolean): Promise { return await this.rpcGateway.listMachineDirectory(machineId, path, includeHidden) } diff --git a/hub/src/sync/usageService.test.ts b/hub/src/sync/usageService.test.ts index 70efa476..48a096b6 100644 --- a/hub/src/sync/usageService.test.ts +++ b/hub/src/sync/usageService.test.ts @@ -1,3 +1,7 @@ +import { Database } from 'bun:sqlite' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { describe, expect, it } from 'bun:test' import { Store } from '../store' import { getUsageSummary } from './usageService' @@ -866,4 +870,101 @@ describe('usage service', () => { expect(store.usage.getEvents([target.id])).toHaveLength(1) store.close() }) + + it('extracts Antigravity (agy) round-summary token usage with inclusive input tokens', () => { + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession( + 'agy-usage-test', + { path: '/tmp', host: 'test', flavor: 'agy' }, + null, + 'default', + 'gemini-3.1-pro-high' + ) + + addAgentMessage(store, session.id, { + type: 'codex', + data: { + type: 'round-summary', + summary: { + provider: 'agy', + model: 'gemini-3.1-pro-high', + agy_usage: { + input_tokens: 1000, + output_tokens: 200, + cache_read_tokens: 800 + } + } + } + }) + + const result = getUsageSummary(store, 'default', 'all') + expect(result.totals.requests).toBe(1) + expect(result.totals.inputTokens).toBe(1800) + expect(result.totals.outputTokens).toBe(200) + expect(result.totals.cacheReadTokens).toBe(800) + expect(result.totals.totalTokens).toBe(2000) + expect(result.totals.uncachedTokens).toBe(1200) + expect(result.byAgent.find((row) => row.key === 'agy')?.totalTokens).toBe(2000) + expect(result.byModel.find((row) => row.key === 'gemini-3.1-pro-high')?.totalTokens).toBe(2000) + store.close() + }) + + it('reindexes historical Antigravity messages when upgrading a pre-parser_version usage_scan_state', () => { + const dir = mkdtempSync(join(tmpdir(), 'hapi-agy-upgrade-')) + const dbPath = join(dir, 'hapi.db') + try { + const initialStore = new Store(dbPath) + const session = initialStore.sessions.getOrCreateSession( + 'agy-upgrade-test', + { path: '/tmp', host: 'test', flavor: 'agy' }, + null, + 'default', + 'gemini-3.1-pro-high' + ) + addAgentMessage(initialStore, session.id, { + type: 'codex', + data: { + type: 'round-summary', + summary: { + provider: 'agy', + model: 'gemini-3.1-pro-high', + agy_usage: { + input_tokens: 500, + output_tokens: 100, + cache_read_tokens: 300 + } + } + } + }) + initialStore.close() + + // Simulate a database whose usage_scan_state was created before parser_version existed + // and already scanned past seq 1 without indexing the Antigravity round-summary message. + const rawDb = new Database(dbPath, { readwrite: true }) + rawDb.exec(` + DROP TABLE usage_scan_state; + CREATE TABLE usage_scan_state ( + session_id TEXT PRIMARY KEY, + message_epoch INTEGER NOT NULL DEFAULT 0, + last_seq INTEGER NOT NULL DEFAULT 0 + ); + DELETE FROM usage_events; + `) + rawDb.prepare('INSERT INTO usage_scan_state (session_id, message_epoch, last_seq) VALUES (?, 0, 1)') + .run(session.id) + rawDb.close() + + const upgradedStore = new Store(dbPath) + const summary = getUsageSummary(upgradedStore, 'default', 'all') + expect(summary.totals.requests).toBe(1) + expect(summary.totals.inputTokens).toBe(800) + expect(summary.totals.outputTokens).toBe(100) + expect(summary.totals.cacheReadTokens).toBe(300) + expect(summary.totals.totalTokens).toBe(900) + expect(summary.totals.uncachedTokens).toBe(600) + upgradedStore.close() + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) }) diff --git a/hub/src/sync/usageService.ts b/hub/src/sync/usageService.ts index 1dac14b4..8b3b0c4a 100644 --- a/hub/src/sync/usageService.ts +++ b/hub/src/sync/usageService.ts @@ -211,6 +211,39 @@ function parseUsageEvent(session: StoredSession, message: StoredMessage): UsageE } } + // Antigravity (agy) emits per-turn round-summary payloads rather than token_count. + if (data.type === 'round-summary') { + const summary = asRecord(data.summary) + if (summary?.provider === 'agy') { + const agyUsage = asRecord(summary.agy_usage) + if (!agyUsage) return null + const inputTokens = firstCount(agyUsage, 'input_tokens', 'inputTokens') + const outputTokens = firstCount(agyUsage, 'output_tokens', 'outputTokens') + const cacheReadTokens = firstCount(agyUsage, 'cache_read_tokens', 'cacheReadTokens') + if (inputTokens + outputTokens + cacheReadTokens <= 0) return null + const model = typeof summary.model === 'string' && summary.model.trim() + ? summary.model.trim() + : null + return { + sessionId: session.id, + sourceKey: `delta|${message.id}`, + sourceSeq: message.seq, + createdAt: message.createdAt, + agent: 'agy', + model, + kind: 'delta', + inputTokens: inputTokens + cacheReadTokens, + outputTokens, + cacheReadTokens, + cacheCreationTokens: 0, + lastInputTokens: null, + lastOutputTokens: null, + lastCacheReadTokens: null, + lastCacheCreationTokens: null + } + } + } + return null } diff --git a/hub/src/web/routes/machines.test.ts b/hub/src/web/routes/machines.test.ts index 55308ecc..1010496d 100644 --- a/hub/src/web/routes/machines.test.ts +++ b/hub/src/web/routes/machines.test.ts @@ -1227,4 +1227,37 @@ describe('machines routes', () => { expect(response.status).toBe(503) expect(await response.json()).toMatchObject({ success: false, code: RPC_TARGET_MISSING_ERROR_CODE }) }) + + it('forwards agent-quotas requests and refresh flag to SyncEngine.getAgentQuotas and rejects older runners with 409', async () => { + const legacyMachine = createMachine() + const capableMachine = createMachine({ + id: 'machine-2', + metadata: { + host: 'localhost', + platform: 'darwin', + happyCliVersion: '1.0.0', + capabilities: [MACHINE_CAPABILITIES.AgentAvailability, MACHINE_CAPABILITIES.AgentQuotas] + } + }) + const calls: Array<{ refresh?: boolean } | undefined> = [] + const engine = { + getMachine: (id: string) => id === 'machine-2' ? capableMachine : legacyMachine, + getMachineByNamespace: (id: string) => id === 'machine-2' ? capableMachine : legacyMachine, + getAgentQuotas: async (_machineId: string, options?: { refresh?: boolean }) => { + calls.push(options) + return { + accounts: [], + fetchedAt: 1700000000000 + } + } + } as unknown as Partial + const app = new Hono() + app.use('*', async (c, next) => { c.set('namespace', 'default'); await next() }) + app.route('/api', createMachinesRoutes(() => engine as SyncEngine)) + + expect((await app.request('/api/machines/machine-1/agent-quotas')).status).toBe(409) + expect((await app.request('/api/machines/machine-2/agent-quotas')).status).toBe(200) + expect((await app.request('/api/machines/machine-2/agent-quotas?refresh=1')).status).toBe(200) + expect(calls).toEqual([{ refresh: false }, { refresh: true }]) + }) }) diff --git a/hub/src/web/routes/machines.ts b/hub/src/web/routes/machines.ts index a5b7aa53..24e7c661 100644 --- a/hub/src/web/routes/machines.ts +++ b/hub/src/web/routes/machines.ts @@ -252,6 +252,32 @@ export function createMachinesRoutes( } }) + app.get('/machines/:id/agent-quotas', async (c) => { + const engine = getSyncEngine() + if (!engine) return c.json({ error: 'Not connected' }, 503) + + const machineId = c.req.param('id') + const machine = requireMachine(c, engine, machineId) + if (machine instanceof Response) return machine + if (!machine.metadata?.capabilities?.includes(MACHINE_CAPABILITIES.AgentQuotas)) { + return c.json({ + error: 'This runner does not support agent quota inspection yet', + code: 'runner_upgrade_required', + }, 409) + } + + const refreshQuery = c.req.query('refresh') + const refresh = refreshQuery === '1' || refreshQuery === 'true' + + try { + return c.json(await engine.getAgentQuotas(machineId, { refresh })) + } catch (error) { + return c.json({ + error: error instanceof Error ? error.message : 'Failed to inspect Agent quotas', + }, 500) + } + }) + app.post('/machines/:id/list-directory', async (c) => { const engine = getSyncEngine() if (!engine) { diff --git a/hub/src/web/routes/usage.test.ts b/hub/src/web/routes/usage.test.ts index 907bbcca..3e108008 100644 --- a/hub/src/web/routes/usage.test.ts +++ b/hub/src/web/routes/usage.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'bun:test' import { Hono } from 'hono' +import { MACHINE_CAPABILITIES } from '@hapi/protocol' import { Store } from '../../store' import type { WebAppEnv } from '../middleware/auth' import { createUsageRoutes } from './usage' @@ -58,4 +59,64 @@ describe('GET /api/usage/summary', () => { store.close() } }) + + it('returns CLI account quotas across online machines on GET /api/usage/quotas', async () => { + const store = new Store(':memory:') + try { + const fakeSyncEngine = { + getOnlineMachinesByNamespace: () => [ + { + id: 'machine-1', + active: true, + metadata: { + displayName: 'Dev Box', + host: 'dev-host', + capabilities: [MACHINE_CAPABILITIES.AgentQuotas] + } + } + ], + getAgentQuotas: async (_machineId: string, opts?: { refresh?: boolean }) => ({ + fetchedAt: 1700000000000, + accounts: [ + { + agent: 'codex' as const, + available: true, + status: 'ok' as const, + accountLabel: 'user@example.com', + planLabel: opts?.refresh ? 'Pro (Refreshed)' : 'Pro', + buckets: [ + { + id: 'codex-primary', + label: 'Weekly (7d)', + group: null, + window: 'weekly', + usedPercent: 18, + remainingPercent: 82, + resetsAt: 1700600000000 + } + ], + updatedAt: 1700000000000 + } + ] + }) + } + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createUsageRoutes(store, () => fakeSyncEngine as never)) + + const response = await app.request('/api/usage/quotas?refresh=1') + expect(response.status).toBe(200) + const body = await response.json() as { machines: Array<{ machineId: string; machineName: string | null; accounts: Array<{ planLabel?: string }> }> } + expect(body.machines).toHaveLength(1) + expect(body.machines[0]?.machineId).toBe('machine-1') + expect(body.machines[0]?.machineName).toBe('Dev Box') + expect(body.machines[0]?.accounts[0]?.planLabel).toBe('Pro (Refreshed)') + } finally { + store.close() + } + }) }) diff --git a/hub/src/web/routes/usage.ts b/hub/src/web/routes/usage.ts index 5be1d4a8..21418114 100644 --- a/hub/src/web/routes/usage.ts +++ b/hub/src/web/routes/usage.ts @@ -1,10 +1,19 @@ import { Hono } from 'hono' -import type { UsageSummaryResponse } from '@hapi/protocol/apiTypes' +import { MACHINE_CAPABILITIES } from '@hapi/protocol' +import type { + UsageMachineQuotasEntry, + UsageQuotasResponse, + UsageSummaryResponse +} from '@hapi/protocol/apiTypes' import type { WebAppEnv } from '../middleware/auth' import type { Store } from '../../store' +import type { SyncEngine } from '../../sync/syncEngine' import { getUsageSummary } from '../../sync/usageService' -export function createUsageRoutes(store: Store): Hono { +export function createUsageRoutes( + store: Store, + getSyncEngine?: () => SyncEngine | null +): Hono { const app = new Hono() app.get('/usage/summary', (c) => { @@ -26,5 +35,66 @@ export function createUsageRoutes(store: Store): Hono { return c.json(response) }) + app.get('/usage/quotas', async (c) => { + if (c.get('namespace') !== 'default') { + return c.json({ error: 'Usage quotas are only available to the hub owner' }, 403) + } + const engine = getSyncEngine?.() ?? null + const updatedAt = Date.now() + if (!engine) { + const emptyResponse: UsageQuotasResponse = { machines: [], updatedAt } + c.header('Cache-Control', 'no-store') + return c.json(emptyResponse) + } + + const refreshQuery = c.req.query('refresh') + const refresh = refreshQuery === '1' || refreshQuery === 'true' + const onlineMachines = engine.getOnlineMachinesByNamespace('default') + + const machines: UsageMachineQuotasEntry[] = await Promise.all( + onlineMachines.map(async (machine): Promise => { + const machineName = machine.metadata?.displayName?.trim() + || machine.metadata?.host?.trim() + || machine.id + const supported = Boolean(machine.metadata?.capabilities?.includes(MACHINE_CAPABILITIES.AgentQuotas)) + if (!supported) { + return { + machineId: machine.id, + machineName, + supported: false, + accounts: [], + fetchedAt: null + } + } + try { + const result = await engine.getAgentQuotas(machine.id, { refresh }) + return { + machineId: machine.id, + machineName, + supported: true, + accounts: result.accounts, + fetchedAt: result.fetchedAt + } + } catch (error) { + return { + machineId: machine.id, + machineName, + supported: true, + accounts: [], + fetchedAt: null, + error: error instanceof Error ? error.message : 'Failed to fetch quotas' + } + } + }) + ) + + const response: UsageQuotasResponse = { + machines, + updatedAt: Date.now() + } + c.header('Cache-Control', 'no-store') + return c.json(response) + }) + return app } diff --git a/hub/src/web/server.ts b/hub/src/web/server.ts index c8f022a6..ec960964 100644 --- a/hub/src/web/server.ts +++ b/hub/src/web/server.ts @@ -294,7 +294,7 @@ function createWebApp(options: { app.route('/api', createMachinesRoutes(options.getSyncEngine, { dataDir: configuration.dataDir })) app.route('/api', createStorageRoutes(configuration.dbPath)) app.route('/api', createHubSettingsRoutes(configuration.dataDir)) - app.route('/api', createUsageRoutes(options.store)) + app.route('/api', createUsageRoutes(options.store, options.getSyncEngine)) app.route('/api', createActivityRoutes(options.store)) app.route('/api', createGitRoutes(options.getSyncEngine)) // 中文注释:这里提供两类 Codex 辅助能力:扫描本地 transcript 以导入到 Hapi,以及按需重启 Codex Desktop 客户端。 diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index b82c12cd..6ce1ac7d 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -803,6 +803,66 @@ export const AgentAvailabilityResponseSchema = z.object({ }) export type AgentAvailabilityResponse = z.infer +export const AgentQuotaStatusSchema = z.enum([ + 'ok', + 'custom_provider', + 'unauthenticated', + 'unavailable', + 'error' +]) +export type AgentQuotaStatus = z.infer + +export const AgentQuotaBucketSchema = z.object({ + id: z.string(), + label: z.string(), + group: z.string().nullable().optional(), + window: z.string().nullable().optional(), + usedPercent: z.number().min(0).max(100), + remainingPercent: z.number().min(0).max(100), + resetsAt: z.number().nullable().optional() +}) +export type AgentQuotaBucket = z.infer + +export const AgentQuotaAccountSchema = z.object({ + agent: AgentFlavorSchema, + available: z.boolean(), + status: AgentQuotaStatusSchema, + accountLabel: z.string().nullable().optional(), + planLabel: z.string().nullable().optional(), + creditsLabel: z.string().nullable().optional(), + buckets: z.array(AgentQuotaBucketSchema), + note: z.string().nullable().optional(), + updatedAt: z.number() +}) +export type AgentQuotaAccount = z.infer + +export const AgentQuotasRequestSchema = z.object({ + refresh: z.boolean().optional() +}) +export type AgentQuotasRequest = z.infer + +export const AgentQuotasResponseSchema = z.object({ + accounts: z.array(AgentQuotaAccountSchema), + fetchedAt: z.number() +}) +export type AgentQuotasResponse = z.infer + +export const UsageMachineQuotasEntrySchema = z.object({ + machineId: z.string(), + machineName: z.string(), + supported: z.boolean(), + accounts: z.array(AgentQuotaAccountSchema), + fetchedAt: z.number().nullable(), + error: z.string().optional() +}) +export type UsageMachineQuotasEntry = z.infer + +export const UsageQuotasResponseSchema = z.object({ + machines: z.array(UsageMachineQuotasEntrySchema), + updatedAt: z.number() +}) +export type UsageQuotasResponse = z.infer + export const AuthRequestSchema = z.union([ z.object({ initData: z.string() }), z.object({ accessToken: z.string() }) diff --git a/shared/src/rpcMethods.ts b/shared/src/rpcMethods.ts index 8c0e4fab..e311983a 100644 --- a/shared/src/rpcMethods.ts +++ b/shared/src/rpcMethods.ts @@ -11,6 +11,7 @@ export const RPC_METHODS = { ListMachineDirectory: 'list-directory', PathExists: 'path-exists', AgentAvailability: 'agent-availability', + AgentQuotas: 'agent-quotas', CursorChatStoreStatus: 'cursor-chat-store-status', GitStatus: 'git-status', GitDiffNumstat: 'git-diff-numstat', diff --git a/shared/src/runnerCapabilities.ts b/shared/src/runnerCapabilities.ts index 7ae20368..824a01d4 100644 --- a/shared/src/runnerCapabilities.ts +++ b/shared/src/runnerCapabilities.ts @@ -31,6 +31,7 @@ export type RunnerCapabilities = typeof RUNNER_CAPABILITIES export const MACHINE_CAPABILITIES = { ForkArchivedCodex: 'fork-archived-codex', AgentAvailability: RPC_METHODS.AgentAvailability, + AgentQuotas: RPC_METHODS.AgentQuotas, CursorChatStoreStatus: RPC_METHODS.CursorChatStoreStatus, StopRunner: RPC_METHODS.StopRunner, /** Read-only file/Git/search RPCs available on the long-lived runner. */ @@ -44,6 +45,7 @@ export type MachineCapability = export const CURRENT_MACHINE_CAPABILITIES: readonly MachineCapability[] = [ MACHINE_CAPABILITIES.ForkArchivedCodex, MACHINE_CAPABILITIES.AgentAvailability, + MACHINE_CAPABILITIES.AgentQuotas, MACHINE_CAPABILITIES.CursorChatStoreStatus, MACHINE_CAPABILITIES.StopRunner, MACHINE_CAPABILITIES.WorkspaceFileAccess, diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 7e6e9031..b6411bde 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -38,6 +38,7 @@ import type { import type { AgyModelsResponse, AgentAvailabilityResponse, + AgentQuotasResponse, CodexModelsResponse, CursorMigrateOutcome, CursorMigrateToAcpRequest, @@ -66,6 +67,7 @@ import type { SqliteStorageUsageResponse, HubSettingsResponse, UpdateHubSettingsRequest, + UsageQuotasResponse, UsageSummaryResponse, UploadFileResponse } from '@hapi/protocol/apiTypes' @@ -966,6 +968,16 @@ export class ApiClient { return await this.request(`/api/usage/summary?${params.toString()}`) } + async getUsageQuotas(refresh?: boolean): Promise { + return await this.request(`/api/usage/quotas${refresh ? '?refresh=1' : ''}`) + } + + async getMachineAgentQuotas(machineId: string, refresh?: boolean): Promise { + return await this.request( + `/api/machines/${encodeURIComponent(machineId)}/agent-quotas${refresh ? '?refresh=1' : ''}` + ) + } + async restartMachineRunner(machineId: string): Promise<{ message: string }> { return await this.request<{ message: string }>( `/api/machines/${encodeURIComponent(machineId)}/restart-runner`, diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index 4e257ca6..7db48457 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -926,6 +926,17 @@ export default { 'settings.usage.model.title': 'By model', 'settings.usage.bucketDetails': '{requests} requests · {input} in · {output} out', 'settings.usage.sessions': '{count} sessions with usage', + 'settings.usage.quotas.title': 'CLI account quotas', + 'settings.usage.quotas.refresh': 'Refresh quotas', + 'settings.usage.quotas.refreshing': 'Refreshing…', + 'settings.usage.quotas.loading': 'Loading CLI account quotas…', + 'settings.usage.quotas.empty': 'No online machines with installed CLI accounts.', + 'settings.usage.quotas.unsupportedRunner': 'Update the runner on this machine to view CLI account quotas.', + 'settings.usage.quotas.remaining': '{remaining}% remaining ({used}% used)', + 'settings.usage.quotas.resetsAt': 'Resets {time}', + 'settings.usage.quotas.status.unauthenticated': 'Not signed in', + 'settings.usage.quotas.status.custom_provider': 'Custom endpoint / API key', + 'settings.usage.quotas.status.error': 'Quota unavailable', 'settings.general.description': 'Language, companion pairing, and general application preferences.', 'settings.general.agents.title': 'Agents', 'settings.general.agents.description': 'Hub-wide defaults for New Session create and peer spawn (MCP spawn_peer / hapi spawn-peer).', diff --git a/web/src/lib/locales/ru.ts b/web/src/lib/locales/ru.ts index 6bd37a47..2a34a886 100644 --- a/web/src/lib/locales/ru.ts +++ b/web/src/lib/locales/ru.ts @@ -869,6 +869,17 @@ export default { 'settings.usage.model.title': 'По моделям', 'settings.usage.bucketDetails': '{requests} запросов · {input} вход · {output} выход', 'settings.usage.sessions': 'Сессий с расходом: {count}', + 'settings.usage.quotas.title': 'Квоты аккаунтов CLI', + 'settings.usage.quotas.refresh': 'Обновить квоты', + 'settings.usage.quotas.refreshing': 'Обновление…', + 'settings.usage.quotas.loading': 'Загрузка квот аккаунтов CLI…', + 'settings.usage.quotas.empty': 'Нет машин онлайн с установленными аккаунтами CLI.', + 'settings.usage.quotas.unsupportedRunner': 'Обновите раннер на этой машине, чтобы видеть квоты аккаунтов CLI.', + 'settings.usage.quotas.remaining': 'Осталось {remaining}% (использовано {used}%)', + 'settings.usage.quotas.resetsAt': 'Сброс: {time}', + 'settings.usage.quotas.status.unauthenticated': 'Не выполнен вход', + 'settings.usage.quotas.status.custom_provider': 'Свой эндпоинт / API-ключ', + 'settings.usage.quotas.status.error': 'Квота недоступна', 'settings.general.description': 'Язык, сопряжение с приложением-компаньоном и общие предпочтения приложения.', 'settings.general.sessionSummary.title': 'Сводки статуса сессий', 'settings.general.sessionSummary.description': 'Выберите, будут ли поддерживаемые агенты формировать сводки статуса и отображаться ли они в чате.', diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index fa4f114c..cdad87d1 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -924,6 +924,17 @@ export default { 'settings.usage.model.title': '按模型', 'settings.usage.bucketDetails': '{requests} 次请求 · 输入 {input} · 输出 {output}', 'settings.usage.sessions': '{count} 个会话有用量记录', + 'settings.usage.quotas.title': 'CLI 账号额度', + 'settings.usage.quotas.refresh': '刷新额度', + 'settings.usage.quotas.refreshing': '正在刷新…', + 'settings.usage.quotas.loading': '正在读取 CLI 账号额度…', + 'settings.usage.quotas.empty': '暂无在线机器或可用 CLI 账号。', + 'settings.usage.quotas.unsupportedRunner': '请更新此机器上的 runner 以查看 CLI 账号额度。', + 'settings.usage.quotas.remaining': '剩余 {remaining}%(已用 {used}%)', + 'settings.usage.quotas.resetsAt': '重置时间:{time}', + 'settings.usage.quotas.status.unauthenticated': '未登录', + 'settings.usage.quotas.status.custom_provider': '自定义接口 / API Key', + 'settings.usage.quotas.status.error': '无法获取额度', 'settings.general.description': '语言、伴侣应用配对和通用应用偏好。', 'settings.general.agents.title': '智能体', 'settings.general.agents.description': '新建会话与对等 spawn(MCP spawn_peer / hapi spawn-peer)共用的中心级默认值。', diff --git a/web/src/lib/query-keys.ts b/web/src/lib/query-keys.ts index 35ce1b9f..5b93cb1f 100644 --- a/web/src/lib/query-keys.ts +++ b/web/src/lib/query-keys.ts @@ -7,6 +7,7 @@ export const queryKeys = { sqliteStorage: ['sqlite-storage'] as const, hubSettings: ['hub-settings'] as const, usageSummary: (range: string, timeZone: string) => ['usage-summary', range, timeZone] as const, + usageQuotas: ['usage-quotas'] as const, machineCodexModels: (machineId: string) => ['machine-codex-models', machineId] as const, machineAgentAvailability: (machineId: string) => ['machine-agent-availability', machineId] as const, sessionCodexModels: (sessionId: string) => ['session-codex-models', sessionId] as const, diff --git a/web/src/routes/settings/index.test.tsx b/web/src/routes/settings/index.test.tsx index aedabb93..48272ff4 100644 --- a/web/src/routes/settings/index.test.tsx +++ b/web/src/routes/settings/index.test.tsx @@ -10,6 +10,7 @@ import SettingsAboutPage from './about' import SettingsVoicePage from './voice' import SettingsVoiceVoicesPage from './voice-voices' import SettingsVoiceAdvancedPage from './voice-advanced' +import SettingsUsagePage from './usage' const { context, navigate, setAppearance, setColorTheme, setFontScale, setTerminalFontSize, setComposerEnterBehavior, setCodexExplorationCollapsed, setVoice, setAppBadgeEnabled } = vi.hoisted(() => ({ context: { token: '' }, @@ -38,6 +39,66 @@ const updateHubSettings = vi.fn().mockResolvedValue({ ...hubSettingsFixture, sessionSummaryContract: true }) +const getUsageSummary = vi.fn().mockResolvedValue({ + range: { from: null, to: null }, + totals: { + inputTokens: 1000, + outputTokens: 200, + cacheReadTokens: 800, + cacheCreationTokens: 0, + totalTokens: 1200, + uncachedTokens: 400, + requests: 3, + sessions: 1 + }, + daily: [], + byAgent: [], + byModel: [], + updatedAt: 1700000000000 +}) +const getUsageQuotas = vi.fn().mockResolvedValue({ + machines: [ + { + machineId: 'machine-1', + machineName: 'Dev Box', + supported: true, + fetchedAt: 1700000000000, + accounts: [ + { + agent: 'codex', + available: true, + status: 'ok', + accountLabel: 'dev@example.com', + planLabel: 'Pro', + creditsLabel: '500 credits · 1 free reset', + buckets: [ + { + id: 'codex-primary', + label: 'Weekly (7d)', + group: null, + window: 'weekly', + usedPercent: 18, + remainingPercent: 82, + resetsAt: 1700600000000 + } + ], + updatedAt: 1700000000000 + }, + { + agent: 'claude', + available: true, + status: 'custom_provider', + accountLabel: 'https://any.s6o.org', + planLabel: 'apiKeyHelper', + buckets: [], + note: 'Endpoint: https://any.s6o.org · Auth: apiKeyHelper', + updatedAt: 1700000000000 + } + ] + } + ], + updatedAt: 1700000000000 +}) vi.mock('@/hooks/useColorTheme', () => ({ useColorTheme: () => ({ colorTheme: 'default', setColorTheme }), @@ -183,7 +244,7 @@ vi.mock('@/hooks/useChatSurfaceColors', () => ({ vi.mock('@/lib/app-context', () => ({ useAppContext: () => ({ - api: { getHubSettings, updateHubSettings }, + api: { getHubSettings, updateHubSettings, getUsageSummary, getUsageQuotas }, baseUrl: 'http://127.0.0.1:3006', token: context.token, }), @@ -420,4 +481,38 @@ describe('responsive settings pages', () => { expect(screen.getByText('Sound controls')).toBeInTheDocument() expect(screen.getByText('Diagnostics controls')).toBeInTheDocument() }) + + it('renders CLI account quotas and supports manual quota refresh on the usage page', async () => { + renderPage() + + expect(await screen.findByText('CLI account quotas')).toBeInTheDocument() + expect(await screen.findByText('dev@example.com')).toBeInTheDocument() + expect(screen.getByText('Pro')).toBeInTheDocument() + expect(screen.getByText('500 credits · 1 free reset')).toBeInTheDocument() + expect(screen.getByText('82% remaining (18% used)')).toBeInTheDocument() + expect(screen.getByText('Endpoint: https://any.s6o.org · Auth: apiKeyHelper')).toBeInTheDocument() + + fireEvent.click(screen.getByRole('button', { name: 'Refresh quotas' })) + await waitFor(() => { + expect(getUsageQuotas).toHaveBeenCalledWith(true) + }) + }) + + it('renders quota errors instead of the empty state and preserves existing quota cards when refresh fails', async () => { + getUsageQuotas.mockRejectedValueOnce(new Error('Quota endpoint unreachable')) + const firstRender = renderPage() + + expect(await screen.findByText('Quota endpoint unreachable')).toBeInTheDocument() + expect(screen.queryByText('No online machines with installed CLI accounts')).not.toBeInTheDocument() + firstRender.unmount() + + renderPage() + expect(await screen.findByText('dev@example.com')).toBeInTheDocument() + + getUsageQuotas.mockRejectedValueOnce(new Error('Refresh quota timeout')) + fireEvent.click(screen.getByRole('button', { name: 'Refresh quotas' })) + + expect(await screen.findByText('Refresh quota timeout')).toBeInTheDocument() + expect(screen.getByText('dev@example.com')).toBeInTheDocument() + }) }) diff --git a/web/src/routes/settings/usage.tsx b/web/src/routes/settings/usage.tsx index c865a896..c2744e47 100644 --- a/web/src/routes/settings/usage.tsx +++ b/web/src/routes/settings/usage.tsx @@ -1,6 +1,6 @@ import { useMemo, useState } from 'react' -import { useQuery } from '@tanstack/react-query' -import type { UsageSummaryBucket } from '@hapi/protocol/apiTypes' +import { useQuery, useQueryClient } from '@tanstack/react-query' +import type { AgentQuotaAccount, AgentQuotaBucket, UsageSummaryBucket } from '@hapi/protocol/apiTypes' import { SettingsPageContent, SettingsRow, SettingsSection } from '@/components/settings/SettingsPrimitives' import { useAppContext } from '@/lib/app-context' import { queryKeys } from '@/lib/query-keys' @@ -8,6 +8,12 @@ import { useTranslation } from '@/lib/use-translation' type UsageRange = '7d' | '30d' | 'all' +const AGENT_LABELS: Record = { + codex: 'Codex', + agy: 'Antigravity (agy)', + claude: 'Claude Code', +} + function formatTokens(value: number): string { if (value < 1000) return value.toLocaleString() if (value < 1_000_000) return `${(value / 1000).toFixed(value < 10_000 ? 1 : 0)}K` @@ -15,6 +21,113 @@ function formatTokens(value: number): string { return `${(value / 1_000_000_000).toFixed(1)}B` } +function formatResetTime(timestampMs: number): string { + try { + return new Intl.DateTimeFormat(undefined, { + month: 'short', + day: 'numeric', + hour: '2-digit', + minute: '2-digit' + }).format(new Date(timestampMs)) + } catch { + return new Date(timestampMs).toISOString() + } +} + +function quotaBarColorClass(remainingPercent: number): string { + if (remainingPercent <= 5) return 'bg-red-500' + if (remainingPercent <= 20) return 'bg-amber-500' + return 'bg-[var(--app-link)]' +} + +function QuotaBucketRow(props: { bucket: AgentQuotaBucket }) { + const { t } = useTranslation() + const { bucket } = props + const remaining = Math.round(bucket.remainingPercent) + const used = Math.round(bucket.usedPercent) + return ( +
+
+ {bucket.label} + + {t('settings.usage.quotas.remaining', { + remaining: String(remaining), + used: String(used) + })} + +
+
+
+
+ {bucket.resetsAt ? ( +
+ {t('settings.usage.quotas.resetsAt', { time: formatResetTime(bucket.resetsAt) })} +
+ ) : null} +
+ ) +} + +function AccountQuotaCard(props: { account: AgentQuotaAccount; machineLabel?: string | null }) { + const { t } = useTranslation() + const { account, machineLabel } = props + const agentTitle = AGENT_LABELS[account.agent] ?? account.agent + const fallbackStatusNote = account.status === 'unauthenticated' + ? t('settings.usage.quotas.status.unauthenticated') + : account.status === 'custom_provider' + ? t('settings.usage.quotas.status.custom_provider') + : account.status === 'error' + ? t('settings.usage.quotas.status.error') + : null + + return ( +
+
+
+ {agentTitle} + {machineLabel ? ( + + {machineLabel} + + ) : null} + {account.planLabel ? ( + + {account.planLabel} + + ) : null} + {account.creditsLabel ? ( + + {account.creditsLabel} + + ) : null} +
+ {account.accountLabel ? ( + + {account.accountLabel} + + ) : null} +
+ + {account.buckets.length > 0 ? ( +
+ {account.buckets.map((bucket) => ( + + ))} +
+ ) : null} + + {account.note || fallbackStatusNote ? ( +
+ {account.note ?? fallbackStatusNote} +
+ ) : null} +
+ ) +} + function UsageBarList(props: { rows: UsageSummaryBucket[]; empty: string }) { const { t } = useTranslation() const max = props.rows[0]?.totalTokens ?? 0 @@ -46,8 +159,12 @@ function UsageBarList(props: { rows: UsageSummaryBucket[]; empty: string }) { export default function SettingsUsagePage() { const { api } = useAppContext() const { t } = useTranslation() + const queryClient = useQueryClient() const [range, setRange] = useState('7d') const [timeZone] = useState(() => Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC') + const [isRefreshingQuotas, setIsRefreshingQuotas] = useState(false) + const [refreshQuotasError, setRefreshQuotasError] = useState(null) + const query = useQuery({ queryKey: queryKeys.usageSummary(range, timeZone), queryFn: async () => { @@ -59,6 +176,80 @@ export default function SettingsUsagePage() { refetchOnWindowFocus: false, retry: false }) + + const quotasQuery = useQuery({ + queryKey: queryKeys.usageQuotas, + queryFn: async () => { + if (!api) throw new Error('API unavailable') + setRefreshQuotasError(null) + return await api.getUsageQuotas(false) + }, + enabled: Boolean(api), + staleTime: 60_000, + refetchOnWindowFocus: false, + retry: false + }) + + const handleRefreshQuotas = async () => { + if (!api || isRefreshingQuotas) return + setIsRefreshingQuotas(true) + setRefreshQuotasError(null) + try { + const fresh = await api.getUsageQuotas(true) + queryClient.setQueryData(queryKeys.usageQuotas, fresh) + } catch (error) { + setRefreshQuotasError(error instanceof Error ? error.message : String(error)) + } finally { + setIsRefreshingQuotas(false) + } + } + + const quotaErrorMessage = refreshQuotasError + ?? (quotasQuery.error ? (quotasQuery.error instanceof Error ? quotasQuery.error.message : String(quotasQuery.error)) : null) + + const visibleQuotaItems = useMemo(() => { + const machines = quotasQuery.data?.machines ?? [] + const showMachineLabel = machines.length > 1 + const items: Array< + | { kind: 'account'; key: string; account: AgentQuotaAccount; machineLabel: string | null } + | { kind: 'machine-error'; key: string; machineLabel: string; error: string } + > = [] + + for (const machine of machines) { + const label = machine.machineName || machine.machineId + if (!machine.supported) { + items.push({ + kind: 'machine-error', + key: `${machine.machineId}:unsupported`, + machineLabel: label, + error: t('settings.usage.quotas.unsupportedRunner') + }) + continue + } + if (machine.error && machine.accounts.length === 0) { + items.push({ + kind: 'machine-error', + key: `${machine.machineId}:error`, + machineLabel: label, + error: machine.error.includes('RPC method not available') + ? t('settings.usage.quotas.unsupportedRunner') + : machine.error + }) + continue + } + for (const account of machine.accounts) { + if (!account.available && account.status === 'unavailable') continue + items.push({ + kind: 'account', + key: `${machine.machineId}:${account.agent}`, + account, + machineLabel: showMachineLabel ? label : null + }) + } + } + return items + }, [quotasQuery.data?.machines, t]) + const maxDaily = useMemo(() => Math.max(...(query.data?.daily.map((row) => row.totalTokens) ?? [0]), 1), [query.data?.daily]) const cacheHitRate = query.data && query.data.totals.inputTokens > 0 ? `${((query.data.totals.cacheReadTokens / query.data.totals.inputTokens) * 100).toFixed(1)}%` @@ -66,6 +257,55 @@ export default function SettingsUsagePage() { return ( +
+
+

+ {t('settings.usage.quotas.title')} +

+ +
+
+ {quotaErrorMessage ? ( + + ) : null} + {quotasQuery.isLoading ? ( + + ) : visibleQuotaItems.length === 0 ? ( + quotaErrorMessage ? null : ( +
+ {t('settings.usage.quotas.empty')} +
+ ) + ) : ( + visibleQuotaItems.map((item) => ( + item.kind === 'machine-error' ? ( + + ) : ( + + ) + )) + )} +
+
+
{(['7d', '30d', 'all'] as const).map((option) => (