diff --git a/apps/server/src/provider/codexUsageLimits.test.ts b/apps/server/src/provider/codexUsageLimits.test.ts index 9c863f54c0867..b372e3d7b5978 100644 --- a/apps/server/src/provider/codexUsageLimits.test.ts +++ b/apps/server/src/provider/codexUsageLimits.test.ts @@ -1,4 +1,8 @@ +import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts"; +import { applyUsageLimitsUpdate } from "@t3tools/provider-core/server/usageLimits"; +import { exhaustedUsageWindow } from "@t3tools/shared/usageLimits"; import * as CodexErrors from "effect-codex-app-server/errors"; +import type { V2GetAccountRateLimitsResponse__RateLimitSnapshot } from "effect-codex-app-server/schema"; import { describe, expect, it } from "vite-plus/test"; import { @@ -127,6 +131,98 @@ describe("codexRateLimitsToLimits", () => { ); }); +describe("Codex fallback routing", () => { + it("keeps an account with spendable credits after its weekly allowance runs out", () => { + const now = Date.parse(checkedAt); + const exhaustedWeek = { + limitId: "codex", + planType: "plus", + primary: { usedPercent: 12, resetsAt: 1_784_000_000, windowDurationMins: 300 }, + secondary: { usedPercent: 100, resetsAt: 1_784_500_000, windowDurationMins: 10080 }, + } satisfies V2GetAccountRateLimitsResponse__RateLimitSnapshot; + const exhaustedWindow = ( + snapshot: V2GetAccountRateLimitsResponse__RateLimitSnapshot, + topLevel: V2GetAccountRateLimitsResponse__RateLimitSnapshot = snapshot, + ) => + exhaustedUsageWindow( + { + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt, + models: [], + slashCommands: [], + skills: [], + usageLimits: codexRateLimitsToLimits({ + checkedAt, + snapshot: topLevel, + rateLimitsByLimitId: { codex: snapshot }, + }), + } satisfies ServerProvider, + now, + "gpt-6-luna", + ); + const credits = { hasCredits: true, unlimited: false, balance: "42.50" }; + + expect(exhaustedWindow({ ...exhaustedWeek, credits: null })?.id).toBe("secondary"); + expect( + exhaustedWindow({ + ...exhaustedWeek, + credits: { hasCredits: false, unlimited: false, balance: "0" }, + })?.id, + ).toBe("secondary"); + expect(exhaustedWindow({ ...exhaustedWeek, credits, spendControlReached: true })?.id).toBe( + "secondary", + ); + expect( + exhaustedWindow({ ...exhaustedWeek, credits, spendControlReached: false }), + "weekly allowance used up but credits remain spendable", + ).toBeUndefined(); + expect( + exhaustedWindow({ + ...exhaustedWeek, + credits: { hasCredits: false, unlimited: true }, + spendControlReached: false, + }), + "weekly allowance used up but credits are unlimited", + ).toBeUndefined(); + for (const rateLimitReachedType of [ + "workspace_owner_credits_depleted", + "workspace_member_credits_depleted", + "workspace_owner_usage_limit_reached", + "workspace_member_usage_limit_reached", + ] as const) { + expect( + exhaustedWindow({ + ...exhaustedWeek, + credits, + spendControlReached: null, + rateLimitReachedType, + })?.id, + rateLimitReachedType, + ).toBe("secondary"); + } + expect( + exhaustedWindow({ + ...exhaustedWeek, + secondary: { ...exhaustedWeek.secondary, usedPercent: 40 }, + individualLimit: { limit: "50", used: "50", remainingPercent: 0, resetsAt: 1_784_500_000 }, + credits, + spendControlReached: null, + })?.id, + "monthly credit limit used up", + ).toBe("individual"); + expect( + exhaustedWindow(exhaustedWeek, { ...exhaustedWeek, credits, spendControlReached: null }), + "credits reported only on the top-level snapshot", + ).toBeUndefined(); + }); +}); + describe("codexRateLimitsToUpdate", () => { it("does not republish cached windows over a newer account probe", () => { const cached = { @@ -170,6 +266,60 @@ describe("codexRateLimitsToUpdate", () => { expect(codexRateLimitsToUpdate({ planType: "plus" })).toBeUndefined(); }); + it("only revokes the probe's credit grant, and only on an explicit block signal", () => { + const credits = { hasCredits: true, unlimited: false, balance: "42.50" }; + const probe = { + limitId: "codex", + planType: "plus", + secondary: { usedPercent: 100, resetsAt: 1_784_500_000, windowDurationMins: 10080 }, + credits, + spendControlReached: false, + } satisfies V2GetAccountRateLimitsResponse__RateLimitSnapshot; + // Codex sends null for policy fields it could not read on every ordinary notification. + const wire = { + limitId: "codex", + planType: "plus", + secondary: { usedPercent: 85, resetsAt: 1_784_500_000, windowDurationMins: 10080 }, + credits, + spendControlReached: null, + individualLimit: null, + rateLimitReachedType: null, + } satisfies V2GetAccountRateLimitsResponse__RateLimitSnapshot; + const afterNotification = ( + probed: V2GetAccountRateLimitsResponse__RateLimitSnapshot, + notification: V2GetAccountRateLimitsResponse__RateLimitSnapshot, + ) => + applyUsageLimitsUpdate({ + previous: codexRateLimitsToLimits({ checkedAt, snapshot: probed }), + update: codexRateLimitsToUpdate(notification) ?? { windows: [] }, + checkedAt: "2026-07-18T10:00:05.000Z", + })?.continuesOnCredits; + + for (const blocked of [ + { ...probe, spendControlReached: true }, + { ...probe, rateLimitReachedType: "workspace_member_usage_limit_reached" as const }, + { + ...probe, + individualLimit: { limit: "50", used: "50", remainingPercent: 0, resetsAt: 1_784_500_000 }, + }, + ]) { + expect(afterNotification(blocked, wire)).toBeUndefined(); + } + expect(afterNotification(probe, { ...wire, credits: null })).toBe(true); + expect(afterNotification(probe, { ...wire, spendControlReached: true })).toBe(false); + expect( + afterNotification(probe, { + ...wire, + credits: { hasCredits: false, unlimited: false, balance: "0" }, + }), + ).toBe(false); + expect(codexRateLimitsToUpdate({ spendControlReached: true })).toEqual({ + windows: [], + continuesOnCredits: false, + }); + expect(codexRateLimitsToUpdate({ ...wire, secondary: null })).toBeUndefined(); + }); + it("ignores Spark notifications so they cannot overwrite the main allowance", () => { expect( codexRateLimitsToUpdate({ diff --git a/apps/server/src/provider/codexUsageLimits.ts b/apps/server/src/provider/codexUsageLimits.ts index d4f9c621119df..7ddbec0eda0fc 100644 --- a/apps/server/src/provider/codexUsageLimits.ts +++ b/apps/server/src/provider/codexUsageLimits.ts @@ -19,13 +19,24 @@ interface CodexRateLimitWindow { export interface CodexRateLimitSnapshot { readonly limitId?: string | null; readonly planType?: string | null; - readonly rateLimitReachedType?: string | null; + readonly rateLimitReachedType?: string | null | undefined; readonly primary?: CodexRateLimitWindow | null; readonly secondary?: CodexRateLimitWindow | null; - readonly individualLimit?: { - readonly remainingPercent: number; - readonly resetsAt: number; - } | null; + readonly individualLimit?: + | { + readonly remainingPercent: number; + readonly resetsAt: number; + } + | null + | undefined; + readonly credits?: + | { + readonly hasCredits: boolean; + readonly unlimited: boolean; + } + | null + | undefined; + readonly spendControlReached?: boolean | null | undefined; } export interface CodexResetCreditsSummary { @@ -113,6 +124,16 @@ function codexResetCreditsToContract( }; } +/** Explicit block signals only: Codex sends null for fields it could not read, which says nothing. */ +function codexCreditsBlocked(snapshot: CodexRateLimitSnapshot): boolean { + return ( + snapshot.spendControlReached === true || + snapshot.rateLimitReachedType?.startsWith("workspace_") === true || + (snapshot.individualLimit != null && snapshot.individualLimit.remainingPercent <= 0) || + (snapshot.credits != null && !snapshot.credits.hasCredits && !snapshot.credits.unlimited) + ); +} + export function codexRateLimitsToLimits(input: { readonly snapshot: CodexRateLimitSnapshot; readonly rateLimitsByLimitId?: @@ -123,13 +144,24 @@ export function codexRateLimitsToLimits(input: { readonly checkedAt: string; }): ServerProviderUsageLimits { const resetCredits = codexResetCreditsToContract(input.resetCredits); - const windows = codexRateLimitsToWindows(input.rateLimitsByLimitId?.codex ?? input.snapshot); + const snapshot = input.rateLimitsByLimitId?.codex ?? input.snapshot; + // No fixture shows whether Codex reports credits on the bucket or the top-level snapshot. + const credits = snapshot.credits ?? input.snapshot.credits; + const continuesOnCredits = + (credits?.hasCredits === true || credits?.unlimited === true) && + !codexCreditsBlocked({ + ...snapshot, + spendControlReached: snapshot.spendControlReached ?? input.snapshot.spendControlReached, + rateLimitReachedType: snapshot.rateLimitReachedType ?? input.snapshot.rateLimitReachedType, + individualLimit: snapshot.individualLimit ?? input.snapshot.individualLimit, + }); return { ...makeUsageLimits({ checkedAt: input.checkedAt, - windows, + windows: codexRateLimitsToWindows(snapshot), }), ...(resetCredits ? { resetCredits } : {}), + ...(continuesOnCredits ? { continuesOnCredits } : {}), }; } @@ -149,6 +181,10 @@ export function codexRateLimitsToUpdate( existing.windowDurationMins !== window.windowDurationMins ); }); + // Only the account probe grants credit spending; a notification can only revoke it. + const revokesCredits = + (!snapshot.limitId || snapshot.limitId === "codex") && codexCreditsBlocked(snapshot); + if (revokesCredits) return { windows, continuesOnCredits: false }; return windows.length > 0 ? { windows } : undefined; } diff --git a/packages/contracts/src/providerUsageLimits.ts b/packages/contracts/src/providerUsageLimits.ts index 67acbe0d35b05..69ccd56577147 100644 --- a/packages/contracts/src/providerUsageLimits.ts +++ b/packages/contracts/src/providerUsageLimits.ts @@ -46,6 +46,8 @@ export const ServerProviderUsageLimits = Schema.Struct({ windows: ForwardCompatibleArray(ServerProviderUsageWindow), credentialFingerprint: Schema.optional(TrimmedNonEmptyString), resetCredits: Schema.optional(ServerProviderResetCredits), + /** True: the account keeps working on credits after its windows run out. False: revoked since the last probe. */ + continuesOnCredits: Schema.optional(Schema.Boolean), externalUsage: Schema.optional( Schema.Struct({ label: TrimmedNonEmptyString, @@ -64,6 +66,8 @@ export type ServerProviderUsageLimits = typeof ServerProviderUsageLimits.Type; /** Partial updates merge windows by id; omitted windows remain unchanged. */ export const ProviderUsageLimitsUpdate = Schema.Struct({ windows: Schema.Array(ServerProviderUsageWindow), + /** False revokes the probe's credit grant; only a probe can grant it. */ + continuesOnCredits: Schema.optional(Schema.Literal(false)), }); export type ProviderUsageLimitsUpdate = typeof ProviderUsageLimitsUpdate.Type; diff --git a/packages/provider-core/src/server/snapshot.ts b/packages/provider-core/src/server/snapshot.ts index 6cb7ea15c5b10..d130e31442525 100644 --- a/packages/provider-core/src/server/snapshot.ts +++ b/packages/provider-core/src/server/snapshot.ts @@ -24,6 +24,6 @@ export interface ManagedServerProvider { readonly refresh: Effect.Effect; readonly refreshUsage?: Effect.Effect; readonly streamChanges: Stream.Stream; - /** Merge windows by ID and set any authLabel; an update with no window leaves the snapshot untouched. */ + /** Merge windows by ID and set any authLabel; an update that changes nothing and revokes no credit grant leaves the snapshot untouched. */ readonly applyUsageLimits: (update: ProviderUsageLimitsReport) => Effect.Effect; } diff --git a/packages/provider-core/src/server/usageLimits.test.ts b/packages/provider-core/src/server/usageLimits.test.ts index 4b9c1b39c862b..bcc2c727132b5 100644 --- a/packages/provider-core/src/server/usageLimits.test.ts +++ b/packages/provider-core/src/server/usageLimits.test.ts @@ -66,20 +66,69 @@ describe("applyUsageLimitsUpdate", () => { ).toEqual({ checkedAt, windows: [weekly], unavailable: { reason: "probeFailed" } }); }); - it("preserves reset credits when a streamed window update changes usage", () => { + it("preserves reset credits and credit spending when a streamed window update changes usage", () => { const resetCredits = { availableCount: 2, nextExpiresAt: "2026-10-01T00:00:00.000Z" }; const next = applyUsageLimitsUpdate({ - previous: { ...published, resetCredits }, + previous: { ...published, resetCredits, continuesOnCredits: true }, checkedAt: "2026-09-03T12:00:05.000Z", - update: { windows: [{ ...session, usedPercent: 55 }] }, + update: { windows: [{ ...weekly, usedPercent: 100 }] }, }); expect(next).toEqual({ checkedAt: "2026-09-03T12:00:05.000Z", - windows: [{ ...session, usedPercent: 55 }, weekly], + windows: [session, { ...weekly, usedPercent: 100 }], resetCredits, + continuesOnCredits: true, }); }); + + it("records a credit block, even without a window change or a grant to revoke", () => { + const previous = { ...published, continuesOnCredits: true }; + const checkedAtNext = "2026-09-03T12:00:05.000Z"; + const revoke = ( + limits: (typeof published & { readonly continuesOnCredits?: boolean }) | undefined, + windows = [] as ReadonlyArray, + ) => + applyUsageLimitsUpdate({ + previous: limits, + checkedAt: checkedAtNext, + update: { windows, continuesOnCredits: false }, + }); + const revoked = { + checkedAt: checkedAtNext, + windows: [session, weekly], + continuesOnCredits: false, + }; + expect(revoke(previous)).toEqual(revoked); + expect(revoke(previous, [weekly])).toEqual(revoked); + // A probe in flight when the block lands must not grant over it. + const blocked = revoke(published); + expect(blocked).toEqual(revoked); + expect( + resolveUsageLimitsAfterProbe({ + published: blocked, + probed: { ...published, continuesOnCredits: true }, + })?.continuesOnCredits, + ).toBe(false); + // A repeated block moves the revocation's time past a probe that started in between. + const repeated = revoke({ ...published, continuesOnCredits: false }); + expect(repeated).toEqual(revoked); + expect( + resolveUsageLimitsAfterProbe({ + published: repeated, + probed: { ...published, checkedAt: "2026-09-03T12:00:01.000Z", continuesOnCredits: true }, + })?.continuesOnCredits, + ).toBe(false); + // The first streamed update can land before the initial probe commits. + const firstUpdate = revoke(undefined, [weekly]); + expect(firstUpdate?.continuesOnCredits).toBe(false); + expect( + resolveUsageLimitsAfterProbe({ + published: firstUpdate, + probed: { ...published, continuesOnCredits: true }, + })?.continuesOnCredits, + ).toBe(false); + }); }); describe("resolveUsageLimitsAfterProbe", () => { @@ -112,6 +161,24 @@ describe("resolveUsageLimitsAfterProbe", () => { expect(resolveUsageLimitsAfterProbe({ published: live, probed: newer })).toEqual(newer); }); + it("keeps a revocation published after the probe started, and lets a newer probe reset it", () => { + const revoked = { + ...published, + checkedAt: "2026-09-03T12:00:05.000Z", + continuesOnCredits: false, + }; + const granted = { ...published, continuesOnCredits: true }; + expect( + resolveUsageLimitsAfterProbe({ published: revoked, probed: granted })?.continuesOnCredits, + ).toBe(false); + const revokedDuringRecovery = { ...revoked, unavailable: { reason: "probeFailed" as const } }; + expect( + resolveUsageLimitsAfterProbe({ published: revokedDuringRecovery, probed: granted }), + ).toEqual({ ...granted, continuesOnCredits: false }); + const newer = { ...granted, checkedAt: "2026-09-03T12:00:06.000Z" }; + expect(resolveUsageLimitsAfterProbe({ published: revoked, probed: newer })).toBe(newer); + }); + it("keeps the last good windows through a failed probe but not an unsupported one", () => { const failed = { checkedAt, windows: [], unavailable: { reason: "probeFailed" as const } }; const unsupported = { checkedAt, windows: [], unavailable: { reason: "unsupported" as const } }; diff --git a/packages/provider-core/src/server/usageLimits.ts b/packages/provider-core/src/server/usageLimits.ts index 1e4bcd0090854..6f70b49f9c71f 100644 --- a/packages/provider-core/src/server/usageLimits.ts +++ b/packages/provider-core/src/server/usageLimits.ts @@ -53,12 +53,19 @@ export function applyUsageLimitsUpdate(input: { readonly checkedAt: string; }): ServerProviderUsageLimits | undefined { const { previous, update } = input; - if (update.windows.length === 0 || previous?.unavailable?.reason === "unsupported") { + // Every block is recorded with its own time, even without a grant to revoke, so a probe that + // started before it cannot grant over it. + const revokesCredits = update.continuesOnCredits === false; + if ( + (update.windows.length === 0 && !revokesCredits) || + previous?.unavailable?.reason === "unsupported" + ) { return previous; } + const continuesOnCredits = revokesCredits ? false : previous?.continuesOnCredits; const merged = new Map(previous?.windows.map((window) => [window.id, window] as const)); // Codex repeats unchanged limits on token ticks; avoid allocating snapshots for no-ops. - let changed = false; + let changed = revokesCredits; for (const window of update.windows) { const existing = merged.get(window.id); const next: ServerProviderUsageWindow = { @@ -84,6 +91,7 @@ export function applyUsageLimitsUpdate(input: { return { ...makeUsageLimits({ checkedAt: input.checkedAt, windows: merged.values() }), ...(previous?.resetCredits !== undefined ? { resetCredits: previous.resetCredits } : {}), + ...(continuesOnCredits !== undefined ? { continuesOnCredits } : {}), ...(unavailable !== undefined ? { unavailable } : {}), }; } @@ -108,13 +116,18 @@ export function resolveUsageLimitsAfterProbe(input: { return published; } if ( - published && - probed && - !published.unavailable && - !probed.unavailable && - Date.parse(published.checkedAt) > Date.parse(probed.checkedAt) + !published || + !probed || + probed.unavailable || + Date.parse(published.checkedAt) <= Date.parse(probed.checkedAt) ) { - return { ...probed, checkedAt: published.checkedAt, windows: published.windows }; + return probed; + } + // A revocation published after the probe started outranks that probe's grant, even while + // the published snapshot still carries an earlier probe failure. + const revoked = published.continuesOnCredits === false ? { continuesOnCredits: false } : {}; + if (published.unavailable) { + return { ...probed, ...revoked }; } - return probed; + return { ...probed, checkedAt: published.checkedAt, windows: published.windows, ...revoked }; } diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 24403fe8a6c5b..26e36ddaa0fdc 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -28,6 +28,7 @@ export function exhaustedUsageWindow( now: number, model?: string, ) { + if (provider?.usageLimits?.continuesOnCredits === true) return undefined; const exhausted = (provider?.usageLimits?.windows ?? []).filter( (window) => (window.usedPercent ?? 0) >= 100 &&