Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion services/ai-gateway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ one that serves the whole pool.
| **Compatible token fields** | Keeps cc-gateway's `id`, `label`, `account_email`, `status`, `access_token`, `expires_at` and `scopes`, adding metadata for selection — `refresh_at` and `hold` among it — without changing those names |
| **Two providers, one shape** | Anthropic and OpenAI differ in their OAuth callback, their identity claims and their usage payload; the panel and the endpoint do not |
| **Connects on its own** | A ChatGPT account connects through OpenAI's device sign-in, and a Claude account — when the panel is opened on localhost — through a redirect straight back to the gateway; there is no code to carry back |
| **Token refresh** | Each account's token is refreshed on a schedule of its own, spread across the pool and spaced out per vendor, with a shared-expiry exception; while another account can take new work, one whose planned refresh (`refresh_at`) is closer than the hand-out floor waits for it; transient failures pause retries, and refused refresh grants require a new sign-in |
| **Token refresh** | Each account's token is refreshed on a schedule of its own, spread across the pool and spaced out per vendor, with a shared-expiry exception; while another account can take new work, one whose planned refresh (`refresh_at`) is closer than the hand-out floor waits for it; transient failures pause retries, an authenticated usage rejection refreshes that exact token generation through the same single-flight path, and refused refresh grants require a new sign-in |
| **Usage in view** | Each account's session and weekly windows — plus any per-model cap the vendor reports — as live bars coloured by how much is spent (green, yellow from half, orange from three quarters, red at the ceiling), beside a short grey one counting the window down to its rollover, which turns green when that is within the hour. An account whose session or weekly window is spent greys out like a disabled row until that window rolls over — only the look: its row menu keeps working |
| **The plan, named** | Each account's plan as its vendor sells it — Max 20x, Pro, Plus, Pro Lite — read from Anthropic's profile and from ChatGPT's own usage answer |
| **Encrypted at rest** | AES-256-GCM under `AI_GATEWAY_ENCRYPTION_KEY`; a tampered store fails loudly rather than decrypting to something plausible |
Expand Down
78 changes: 75 additions & 3 deletions services/ai-gateway/backend/accounts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,11 @@ function gate(): { wait: Promise<void>; open: () => void } {
function fakeProvider(id: 'anthropic' | 'openai'): Provider & {
usage: UsageWindow[];
usagePlan: Subscription | null;
refusals: { refresh?: RefreshRefusal; usage?: boolean; exchange?: boolean };
refusals: {
refresh?: RefreshRefusal;
usage?: boolean | 'rejected';
exchange?: boolean;
};
gates: { refresh?: Promise<void>; usage?: Promise<void> };
refreshCount: number;
refreshedExpiresAt: string;
Expand All @@ -69,7 +73,7 @@ function fakeProvider(id: 'anthropic' | 'openai'): Provider & {
usagePlan: null as Subscription | null,
refusals: {} as {
refresh?: RefreshRefusal;
usage?: boolean;
usage?: boolean | 'rejected';
exchange?: boolean;
},
gates: {} as { refresh?: Promise<void>; usage?: Promise<void> },
Expand Down Expand Up @@ -172,7 +176,13 @@ function fakeProvider(id: 'anthropic' | 'openai'): Provider & {
state.usageCount += 1;
await state.gates.usage;
if (state.refusals.usage) {
throw new ProviderError(id, 'usage_failed', 'refused');
throw new ProviderError(
id,
state.refusals.usage === 'rejected'
? 'access_token_rejected'
: 'usage_failed',
'refused',
);
}
return { windows: state.usage, subscription: state.usagePlan };
},
Expand Down Expand Up @@ -738,6 +748,26 @@ describe('createAccountService', () => {
expect(cipher.open(stored?.accessToken ?? '')).toBe('access-2');
});

it('does not reject a replacement generation when an older usage read answers 401', async () => {
const account = await connect();
const held = gate();
anthropic.gates.usage = held.wait;
anthropic.refusals.usage = 'rejected';
now = new Date('2026-09-21T10:10:00.000Z');
const reading = service.list();
await vi.waitFor(() => expect(anthropic.usageCount).toBe(2));

now = new Date('2026-09-21T10:56:00.000Z');
const handouts = service.handOutTokens();
await vi.waitFor(() => expect(anthropic.refreshCount).toBe(1));
held.open();
await Promise.all([reading, handouts]);

const stored = await store.getAccount(account.id);
expect(cipher.open(stored?.accessToken ?? '')).toBe('access-2');
expect(stored?.status).toBe('active');
});

it('keeps the last reading, and when it was read, through a failed read', async () => {
await connect();
anthropic.refusals.usage = true;
Expand All @@ -757,6 +787,48 @@ describe('createAccountService', () => {
expect(anthropic.usageCount).toBe(3);
});

it('recovers one exact access-token generation after an authenticated usage rejection', async () => {
const account = await connect();
anthropic.refusals.usage = 'rejected';
now = new Date('2026-09-21T10:10:00.000Z');

const [row] = await service.list();

expect(row?.status).toBe('active');
expect(anthropic.refreshCount).toBe(1);
expect(
cipher.open((await store.getAccount(account.id))?.accessToken ?? ''),
).toBe('access-2');
});

it('keeps a rejected generation unavailable when its recovery is rate limited', async () => {
const account = await connect();
anthropic.refusals.usage = 'rejected';
anthropic.refusals.refresh = 'failed';
now = new Date('2026-09-21T10:10:00.000Z');

const [row] = await service.list();
expect(row?.status).toBe('error');
expect(anthropic.refreshCount).toBe(1);

now = new Date('2026-09-21T10:30:00.000Z');
await service.list();
expect(anthropic.usageCount).toBe(1 + 1);
expect((await store.getAccount(account.id))?.status).toBe('error');
});

it('does not export a known unavailable account through its CLI command', async () => {
const account = await connect();
anthropic.refusals.refresh = 'failed';
await store.updateAccount(account.id, (row) => {
row.status = 'error';
});

await expect(service.cliCommand(account.id)).rejects.toMatchObject({
code: 'unavailable',
});
});

it('does not bring back an account removed while it was being read', async () => {
const account = await connect();
now = new Date('2026-09-21T10:10:00.000Z');
Expand Down
45 changes: 43 additions & 2 deletions services/ai-gateway/backend/accounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,11 @@ export function createAccountService(
return false;
}
const refreshAt = plannedRefreshMs(account);
return refreshAt === null || refreshAt <= now().getTime();
return (
account.status === 'error' ||
refreshAt === null ||
refreshAt <= now().getTime()
);
}

/**
Expand Down Expand Up @@ -691,14 +695,40 @@ export function createAccountService(
return run;
}

function usageAttemptIsNewerThanReading(account: StoredAccount): boolean {
if (!account.usage) return false;
const attempted = account.usageAttemptedAt
? Date.parse(account.usageAttemptedAt)
: Number.NaN;
const checked = Date.parse(account.usage.checkedAt);
return (
Number.isFinite(attempted) &&
Number.isFinite(checked) &&
attempted > checked
);
}

async function refreshStoredUsage(
account: StoredAccount,
force: boolean,
): Promise<StoredAccount> {
const stored = await store.getAccount(account.id);
if (!stored) return account;
const current = await ensureFresh(stored);
if (current.status === 'expired') return current;
// A persisted error has already failed a refresh. Keep it out of usage
// polling until a later refresh succeeds; an error produced by this
// call's initial refresh still gets one final usage read, preserving the
// existing transient-refresh behaviour.
if (
current.status === 'expired' ||
(current.status === 'error' &&
stored.status === 'error' &&
stored.usageAttemptedAt !== null &&
(account.status === 'error' ||
!stored.usage ||
usageAttemptIsNewerThanReading(stored)))
)
return current;
if (
current.status === 'error' &&
current.expiresAt &&
Expand Down Expand Up @@ -756,11 +786,16 @@ export function createAccountService(
`[ai-gateway] usage read failed for ${current.provider} account ${current.id}:`,
error instanceof Error ? error.message : error,
);
const rejected =
error instanceof ProviderError &&
error.code === 'access_token_rejected';
const updated = await store.updateAccount(current.id, (row) => {
if (row.accessToken !== current.accessToken) return;
row.usageAttemptedAt = now().toISOString();
if (error instanceof CipherError) row.status = 'expired';
else if (rejected) row.status = 'error';
});
if (rejected && updated?.status === 'error') return ensureFresh(updated);
return updated ?? current;
}
}
Expand Down Expand Up @@ -1170,6 +1205,12 @@ export function createAccountService(
const account = await store.getAccount(id);
if (!account) return null;
const fresh = await ensureFresh(account);
if (fresh.status !== 'active') {
throw new AccountError(
'unavailable',
'This account is not currently available.',
);
}
try {
return providerFor(fresh).cliCommand(
cipher.open(fresh.accessToken),
Expand Down
13 changes: 13 additions & 0 deletions services/ai-gateway/backend/providers/openai.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,19 @@ describe('fetchUsage', () => {
expect(calls[0]?.headers.has('chatgpt-account-id')).toBe(false);
});

it('types an authenticated usage rejection without reading its response body', async () => {
const { fetchImpl } = stubFetch(() => json({ secret: 'never-read' }, 401));
await expect(
createOpenAiProvider({ fetchImpl }).fetchUsage({
accessToken: 'access-1',
accountId: null,
}),
).rejects.toMatchObject({
code: 'access_token_rejected',
message: 'The OpenAI usage endpoint answered 401.',
});
});

it.each([
{},
{ error: { code: 'rate_limit_error' } },
Expand Down
2 changes: 1 addition & 1 deletion services/ai-gateway/backend/providers/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ export function createOpenAiProvider(
if (!response.ok) {
throw new ProviderError(
'openai',
'usage_failed',
response.status === 401 ? 'access_token_rejected' : 'usage_failed',
`The OpenAI usage endpoint answered ${response.status}.`,
);
}
Expand Down
4 changes: 3 additions & 1 deletion services/ai-gateway/backend/providers/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,9 @@ export class ProviderError extends Error {
| 'refresh_failed'
| 'refresh_rejected'
| 'identity_failed'
| 'usage_failed',
| 'usage_failed'
/** The provider rejected this exact access-token generation. */
| 'access_token_rejected',
message: string,
options?: { cause?: unknown },
) {
Expand Down