@@ -381,6 +381,7 @@ export async function consumeCreditsAndAddAgentStep(params: {
381381
382382 cost : number
383383 credits : number
384+ byok : boolean
384385
385386 inputTokens : number
386387 cacheCreationInputTokens : number | null
@@ -405,6 +406,7 @@ export async function consumeCreditsAndAddAgentStep(params: {
405406
406407 cost,
407408 credits,
409+ byok,
408410
409411 inputTokens,
410412 cacheCreationInputTokens,
@@ -423,31 +425,37 @@ export async function consumeCreditsAndAddAgentStep(params: {
423425 await withSerializableTransaction ( {
424426 callback : async ( tx ) => {
425427 const now = new Date ( )
426- const activeGrants = await getOrderedActiveGrants ( {
427- ...params ,
428- now,
429- conn : tx ,
430- } )
431-
432- if ( activeGrants . length === 0 ) {
433- logger . error (
434- { userId, credits } ,
435- 'No active grants found to consume credits from' ,
436- )
437- throw new Error ( 'No active grants found' )
438- }
439428
440- const result = await consumeFromOrderedGrants ( {
441- ...params ,
442- creditsToConsume : credits ,
443- grants : activeGrants ,
444- tx,
445- } )
429+ let result : CreditConsumptionResult | null = null
430+ consumeCredits: {
431+ if ( byok ) {
432+ break consumeCredits
433+ }
434+ const activeGrants = await getOrderedActiveGrants ( {
435+ ...params ,
436+ now,
437+ conn : tx ,
438+ } )
446439
447- if ( userId === TEST_USER_ID ) {
448- return { ...result , agentStepId : 'test-step-id' }
440+ if ( activeGrants . length === 0 ) {
441+ logger . error (
442+ { userId, credits } ,
443+ 'No active grants found to consume credits from' ,
444+ )
445+ throw new Error ( 'No active grants found' )
446+ }
447+
448+ result = await consumeFromOrderedGrants ( {
449+ ...params ,
450+ creditsToConsume : credits ,
451+ grants : activeGrants ,
452+ tx,
453+ } )
454+
455+ if ( userId === TEST_USER_ID ) {
456+ return { ...result , agentStepId : 'test-step-id' }
457+ }
449458 }
450- const stepId = crypto . randomUUID ( )
451459
452460 try {
453461 await tx . insert ( schema . message ) . values ( {
@@ -466,6 +474,7 @@ export async function consumeCreditsAndAddAgentStep(params: {
466474 output_tokens : outputTokens ,
467475 cost : cost . toString ( ) ,
468476 credits,
477+ byok,
469478 latency_ms : latencyMs ,
470479 user_id : userId ,
471480 } )
@@ -474,7 +483,13 @@ export async function consumeCreditsAndAddAgentStep(params: {
474483 throw error
475484 }
476485
477- return { ...result , agentStepId : stepId }
486+ if ( ! result ) {
487+ result = {
488+ consumed : 0 ,
489+ fromPurchased : 0 ,
490+ }
491+ }
492+ return { ...result , agentStepId : crypto . randomUUID ( ) }
478493 } ,
479494 context : { userId, credits } ,
480495 logger,
0 commit comments