Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(ai-gateway): credits extend daily cost cap 1:1

Louis Beaumontada3eb5e951b
diff --git a/packages/ai-gateway/src/index.ts b/packages/ai-gateway/src/index.ts
index f5dc2a4b2..ef1790945 100644
--- a/packages/ai-gateway/src/index.ts
+++ b/packages/ai-gateway/src/index.ts
@@ -3,7 +3,7 @@ import { Env, RequestBody, AuthResult } from './types';
import { handleOptions, createSuccessResponse, createErrorResponse, addCorsHeaders } from './utils/cors';
import { validateAuth } from './utils/auth';
import { RateLimiter, checkRateLimit } from './utils/rate-limiter';
-import { trackUsage, getUsageStatus, isModelAllowed, getTierConfig } from './services/usage-tracker';
+import { trackUsage, getUsageStatus, isModelAllowed, getTierConfig, getCreditBalance } from './services/usage-tracker';
import { handleChatCompletions } from './handlers/chat';
import { handleModelListing } from './handlers/models';
import { handleFileTranscription, handleABTestAdmin } from './handlers/transcription';
@@ -51,11 +51,14 @@ async function handleRequest(request: Request, env: Env, ctx: ExecutionContext):
const status = await getUsageStatus(env, authResult.deviceId, authResult.tier, authResult.userId);
// Enrich with cost-based limit flag (NOT the raw $ numbers — those
// are our internal margin and shouldn't leak to any client/user).
+ // Credits extend the cap 1:1 (1 credit = $1 of headroom) so that the
+ // /billing top-up button actually lifts the limit it advertises.
const dailyCost = await getDailyUserCost(env, authResult.deviceId);
const maxCost = getTierDailyCostCap(authResult.tier, env);
+ const credits = authResult.userId ? await getCreditBalance(env, authResult.userId) : 0;
const enriched = {
...status,
- cost_limit_reached: dailyCost >= maxCost,
+ cost_limit_reached: dailyCost >= maxCost + credits,
};
return addCorsHeaders(createSuccessResponse(enriched));
}
@@ -101,11 +104,18 @@ async function handleRequest(request: Request, env: Env, ctx: ExecutionContext):
// Cheap models (weight 0-1) like qwen3.5-flash, haiku, deepseek-chat
// should not trigger cost caps — they're affordable and pipes need them.
// Subscribed users get 5x higher cap.
+ //
+ // Credits extend the cap 1:1: a user with a $50 credit balance gets
+ // $50 more headroom for today before this 429 fires. Required to make
+ // the /billing one-click top-up actually unblock the user it sold to.
+ // (The credits are separately consumed per-query in the trackUsage
+ // path below, so this is just the ceiling check.)
const modelWeight = getModelWeight(body.model);
if (!isZeroCostModel(body.model) && modelWeight >= 3) {
const dailyCost = await getDailyUserCost(env, authResult.deviceId);
const maxCost = getTierDailyCostCap(authResult.tier, env);
- if (dailyCost >= maxCost) {
+ const credits = authResult.userId ? await getCreditBalance(env, authResult.userId) : 0;
+ if (dailyCost >= maxCost + credits) {
const resetsAt = new Date();
resetsAt.setUTCHours(24, 0, 0, 0);
return addCorsHeaders(createErrorResponse(429, JSON.stringify({
diff --git a/packages/ai-gateway/src/services/usage-tracker.ts b/packages/ai-gateway/src/services/usage-tracker.ts
index 678273a5e..b7a746438 100644
--- a/packages/ai-gateway/src/services/usage-tracker.ts
+++ b/packages/ai-gateway/src/services/usage-tracker.ts
@@ -86,8 +86,12 @@ async function tryDeductCredit(env: Env, userId: string, reason: string): Promis
/**
* Get user's current credit balance without deducting.
+ *
+ * Exported because the cost-cap check in `index.ts` also needs this — credits
+ * extend the daily cost ceiling 1:1 (1 credit = $1 of headroom). Without that,
+ * users who pay $50 still 429 on Opus and file Intercom tickets.
*/
-async function getCreditBalance(env: Env, userId: string): Promise<number> {
+export async function getCreditBalance(env: Env, userId: string): Promise<number> {
const clerkId = await resolveClerkId(env, userId);
if (!clerkId) return 0;