@@ -17,6 +17,11 @@ import type {
1717 Logger ,
1818 LoggerWithContextFn ,
1919} from '@codebuff/common/types/contracts/logger'
20+
21+ import type {
22+ BlockGrantResult ,
23+ SubscriptionRow ,
24+ } from '@codebuff/billing/subscription'
2025import type { NextRequest } from 'next/server'
2126
2227import type { ChatCompletionRequestBody } from '@/llm-api/types'
@@ -78,6 +83,8 @@ export async function postChatCompletions(params: {
7883 getAgentRunFromId : GetAgentRunFromIdFn
7984 fetch : typeof globalThis . fetch
8085 insertMessageBigquery : InsertMessageBigqueryFn
86+ getActiveSubscription ?: ( params : { userId : string ; logger : Logger } ) => Promise < SubscriptionRow | null >
87+ ensureActiveBlockGrant ?: ( params : { userId : string ; subscription : SubscriptionRow ; logger : Logger } ) => Promise < BlockGrantResult >
8188} ) {
8289 const {
8390 req,
@@ -88,6 +95,8 @@ export async function postChatCompletions(params: {
8895 getAgentRunFromId,
8996 fetch,
9097 insertMessageBigquery,
98+ getActiveSubscription,
99+ ensureActiveBlockGrant,
91100 } = params
92101 let { logger } = params
93102
@@ -182,6 +191,22 @@ export async function postChatCompletions(params: {
182191 logger,
183192 } )
184193
194+ // For subscribers, ensure a block grant exists before checking balance.
195+ // This is done here block grants should only start when the user begins working.
196+ if ( getActiveSubscription && ensureActiveBlockGrant ) {
197+ try {
198+ const activeSub = await getActiveSubscription ( { userId, logger } )
199+ if ( activeSub ) {
200+ await ensureActiveBlockGrant ( { userId, subscription : activeSub , logger } )
201+ }
202+ } catch ( error ) {
203+ logger . error (
204+ { error : getErrorObject ( error ) , userId } ,
205+ 'Error ensuring subscription block grant' ,
206+ )
207+ }
208+ }
209+
185210 // Check user credits
186211 const {
187212 balance : { totalRemaining } ,
0 commit comments