Repository navigation
Expand file tree
/
Copy path_post.ts
More file actions
1107 lines (1041 loc) · 35.7 KB
/
Copy path_post.ts
File metadata and controls
1107 lines (1041 loc) · 35.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events'
import { BYOK_OPENROUTER_HEADER } from '@codebuff/common/constants/byok'
import {
type FreebuffAccessTier,
FREEBUFF_GEMINI_PRO_MODEL_ID,
isFreebuffModelAllowedForAccessTier,
isSupportedFreebuffModelId,
} from '@codebuff/common/constants/freebuff-models'
import {
isFreebuffGeminiThinkerAgent,
isFreebuffRootAgent,
isFreeMode,
isFreeModeAllowedAgentModel,
} from '@codebuff/common/constants/free-agents'
import { getErrorObject } from '@codebuff/common/util/error'
import { formatFreebuffHardBlockedMessage } from '@codebuff/common/util/freebuff-privacy'
import { pluralize } from '@codebuff/common/util/string'
import { env } from '@codebuff/internal/env'
import { NextResponse } from 'next/server'
import type { TrackEventFn } from '@codebuff/common/types/contracts/analytics'
import type {
InsertChatCompletionTraceBigqueryFn,
InsertMessageBigqueryFn,
} from '@codebuff/common/types/contracts/bigquery'
import type { GetUserUsageDataFn } from '@codebuff/common/types/contracts/billing'
import type {
GetAgentRunFromIdFn,
GetUserInfoFromApiKeyFn,
} from '@codebuff/common/types/contracts/database'
import type {
Logger,
LoggerWithContextFn,
} from '@codebuff/common/types/contracts/logger'
import type { BlockGrantResult } from '@codebuff/billing/subscription'
import {
isWeeklyLimitError,
isBlockExhaustedError,
} from '@codebuff/billing/subscription'
export type GetUserPreferencesFn = (params: {
userId: string
logger: Logger
}) => Promise<{ fallbackToALaCarte: boolean }>
import type { NextRequest } from 'next/server'
import type { ChatCompletionRequestBody } from '@/llm-api/types'
import { recordChatCompletionTrace } from '@/llm-api/chat-completion-trace'
import { createRequestAuditRecord } from '@/llm-api/helpers'
import {
CanopyWaveError,
handleCanopyWaveNonStream,
handleCanopyWaveStream,
isCanopyWaveModel,
} from '@/llm-api/canopywave'
import {
FireworksError,
handleFireworksNonStream,
handleFireworksStream,
isFireworksModel,
} from '@/llm-api/fireworks'
import {
DeepSeekError,
handleDeepSeekNonStream,
handleDeepSeekStream,
isDeepSeekModel,
} from '@/llm-api/deepseek'
import {
handleMoonshotNonStream,
handleMoonshotStream,
isMoonshotModel,
MoonshotError,
} from '@/llm-api/moonshot'
import {
OpenCodeZenError,
handleOpenCodeZenNonStream,
handleOpenCodeZenStream,
isOpenCodeZenModel,
} from '@/llm-api/opencode-zen'
import {
SiliconFlowError,
handleSiliconFlowNonStream,
handleSiliconFlowStream,
isSiliconFlowModel,
} from '@/llm-api/siliconflow'
import {
handleOpenAINonStream,
handleOpenAIStream,
isOpenAIDirectModel,
OpenAIError,
} from '@/llm-api/openai'
import {
handleOpenRouterNonStream,
handleOpenRouterStream,
OpenRouterError,
} from '@/llm-api/openrouter'
import {
checkSessionAdmissible,
endUserSession,
} from '@/server/free-session/public-api'
import { getCachedFreeModeCountryAccess } from '@/server/free-mode-country-access-cache'
import {
getFreeModeAccessTier,
getFreeModePrivacyDecision,
getFreeModePrivacyProviderDecision,
shouldHardBlockFreeModeAccess,
} from '@/server/free-mode-country'
import type { SessionGateResult } from '@/server/free-session/public-api'
import type {
FreeModeCountryAccess,
FreeModeCountryAccessOptions,
} from '@/server/free-mode-country'
import { extractApiKeyFromHeader } from '@/util/auth'
import { withDefaultProperties } from '@codebuff/common/analytics'
import { checkFreeModeRateLimit as defaultCheckFreeModeRateLimit } from './free-mode-rate-limiter'
import { beginChatCompletionRequestMetrics } from './request-metrics'
export const formatQuotaResetCountdown = (
nextQuotaReset: string | null | undefined,
): string => {
if (!nextQuotaReset) {
return 'soon'
}
const resetDate = new Date(nextQuotaReset)
if (Number.isNaN(resetDate.getTime())) {
return 'soon'
}
const now = Date.now()
const diffMs = resetDate.getTime() - now
if (diffMs <= 0) {
return 'soon'
}
const minuteMs = 60 * 1000
const hourMs = 60 * minuteMs
const dayMs = 24 * hourMs
const days = Math.floor(diffMs / dayMs)
if (days > 0) {
return `in ${pluralize(days, 'day')}`
}
const hours = Math.floor(diffMs / hourMs)
if (hours > 0) {
return `in ${pluralize(hours, 'hour')}`
}
const minutes = Math.max(1, Math.floor(diffMs / minuteMs))
return `in ${pluralize(minutes, 'minute')}`
}
export type CheckSessionAdmissibleFn = typeof checkSessionAdmissible
export type EndUserSessionFn = typeof endUserSession
export type CheckFreeModeRateLimitFn = typeof defaultCheckFreeModeRateLimit
export type ResolveFreeModeCountryAccessFn = (
userId: string,
req: NextRequest,
options: FreeModeCountryAccessOptions,
) => Promise<FreeModeCountryAccess>
const FREEBUFF_SUCCESS_SAMPLE_RATE = 0.01
function sampleSuccessLogger(logger: Logger, sampled: boolean): Logger {
if (sampled) return logger
return {
...logger,
info: (() => {}) as Logger['info'],
debug: (() => {}) as Logger['debug'],
}
}
type GateRejectCode = Extract<SessionGateResult, { ok: false }>['code']
const STATUS_BY_GATE_CODE = {
waiting_room_required: 428,
waiting_room_queued: 429,
session_superseded: 409,
session_expired: 410,
session_model_mismatch: 409,
freebuff_update_required: 426,
} satisfies Record<GateRejectCode, number>
function getHardBlockedFreeModeMessage(
countryAccess: Pick<FreeModeCountryAccess, 'ipPrivacy'>,
): string {
return formatFreebuffHardBlockedMessage(countryAccess.ipPrivacy?.signals)
}
export async function postChatCompletions(params: {
req: NextRequest
getUserInfoFromApiKey: GetUserInfoFromApiKeyFn
logger: Logger
loggerWithContext: LoggerWithContextFn
trackEvent: TrackEventFn
getUserUsageData: GetUserUsageDataFn
getAgentRunFromId: GetAgentRunFromIdFn
fetch: typeof globalThis.fetch
insertMessageBigquery: InsertMessageBigqueryFn
insertChatCompletionTraceBigquery?: InsertChatCompletionTraceBigqueryFn
ensureSubscriberBlockGrant?: (params: {
userId: string
logger: Logger
}) => Promise<BlockGrantResult | null>
getUserPreferences?: GetUserPreferencesFn
/** Optional override for the freebuff waiting-room gate. Defaults to the
* real check backed by Postgres; tests inject a no-op. */
checkSessionAdmissible?: CheckSessionAdmissibleFn
/** Optional override for the free-mode rate limiter. Tests inject this to
* avoid coupling to process-global limiter state. */
checkFreeModeRateLimit?: CheckFreeModeRateLimitFn
/** Optional override for country/cache checks. Tests inject this to avoid
* coupling to Postgres-backed cache state. */
resolveFreeModeCountryAccess?: ResolveFreeModeCountryAccessFn
/** Optional override for releasing stale waiting-room rows on hard blocks. */
endFreebuffSession?: EndUserSessionFn
}) {
const {
req,
getUserInfoFromApiKey,
loggerWithContext,
getUserUsageData,
getAgentRunFromId,
fetch,
insertMessageBigquery,
insertChatCompletionTraceBigquery,
ensureSubscriberBlockGrant,
getUserPreferences,
checkSessionAdmissible: checkSession = checkSessionAdmissible,
checkFreeModeRateLimit = defaultCheckFreeModeRateLimit,
resolveFreeModeCountryAccess,
endFreebuffSession = endUserSession,
} = params
let { logger } = params
let { trackEvent } = params
const resolveCountryAccess: ResolveFreeModeCountryAccessFn =
resolveFreeModeCountryAccess ??
((userId, req, options) =>
getCachedFreeModeCountryAccess({ userId, req, options, logger }))
try {
// Parse request body
let body: Record<string, unknown>
try {
body = await req.json()
} catch (error) {
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_VALIDATION_ERROR,
userId: 'unknown',
properties: {
error: 'Invalid JSON in request body',
},
logger,
})
return NextResponse.json(
{ message: 'Invalid JSON in request body' },
{ status: 400 },
)
}
const typedBody = body as unknown as ChatCompletionRequestBody
const bodyStream = typedBody.stream ?? false
const runId = typedBody.codebuff_metadata?.run_id
// Check if the request is in FREE mode (costs 0 credits for allowed agent+model combos)
const costMode = typedBody.codebuff_metadata?.cost_mode
const isFreeModeRequest = isFreeMode(costMode)
const sampleFreebuffSuccess =
!isFreeModeRequest || Math.random() < FREEBUFF_SUCCESS_SAMPLE_RATE
const trackSuccessEvent: TrackEventFn = (eventParams) => {
if (sampleFreebuffSuccess) {
trackEvent(eventParams)
}
}
trackEvent = withDefaultProperties(trackEvent, {
freebuff: isFreeModeRequest,
})
// Extract and validate API key
const apiKey = extractApiKeyFromHeader(req)
if (!apiKey) {
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_AUTH_ERROR,
userId: 'unknown',
properties: {
reason: 'Missing API key',
},
logger,
})
return NextResponse.json({ message: 'Unauthorized' }, { status: 401 })
}
// Get user info
const userInfo = await getUserInfoFromApiKey({
apiKey,
fields: ['id', 'email', 'discord_id', 'stripe_customer_id', 'banned'],
logger,
})
if (!userInfo) {
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_AUTH_ERROR,
userId: 'unknown',
properties: {
reason: 'Invalid API key',
},
logger,
})
return NextResponse.json(
{ message: 'Invalid Codebuff API key' },
{ status: 401 },
)
}
logger = loggerWithContext({ userInfo })
const userId = userInfo.id
const stripeCustomerId = userInfo.stripe_customer_id ?? null
let freebuffAccessTier: FreebuffAccessTier = 'full'
// Check if user is banned.
// We use a clear, helpful message rather than a cryptic error because:
// 1. Legitimate users banned by mistake deserve to know what's happening
// 2. Bad actors will figure out they're banned regardless of the message
// 3. Clear messaging encourages resolution (matches our dispute notification email)
// 4. 403 Forbidden is the correct HTTP status for "you're not allowed"
if (userInfo.banned) {
return NextResponse.json(
{
error: 'account_suspended',
message: `Your account has been suspended. Please contact ${env.NEXT_PUBLIC_SUPPORT_EMAIL} if you did not expect this.`,
},
{ status: 403 },
)
}
// For free mode requests, classify the request into full or limited
// access. Most non-allowlist/privacy cases, including VPN/proxy traffic,
// are limited to the cheap DeepSeek Flash path; Cloudflare Tor remains a
// hard block.
if (isFreeModeRequest) {
const countryAccess = await resolveCountryAccess(userId, req, {
fetch,
ipinfoToken: env.IPINFO_TOKEN,
spurToken: env.SPUR_TOKEN,
ipHashSecret: env.NEXTAUTH_SECRET,
allowLocalhost: env.NEXT_PUBLIC_CB_ENVIRONMENT === 'dev',
forceLimited:
env.NEXT_PUBLIC_CB_ENVIRONMENT === 'dev' &&
env.FREEBUFF_DEV_FORCE_LIMITED,
})
freebuffAccessTier = getFreeModeAccessTier(countryAccess)
const hardBlocked = shouldHardBlockFreeModeAccess(countryAccess)
const privacyDecision = getFreeModePrivacyDecision(countryAccess)
const privacyProviderDecision =
getFreeModePrivacyProviderDecision(countryAccess)
if (!countryAccess.allowed || sampleFreebuffSuccess) {
logger.info(
{
cfHeader: countryAccess.cfCountry,
geoipResult: countryAccess.geoipCountry,
resolvedCountry: countryAccess.countryCode,
countryBlockReason: countryAccess.blockReason,
ipPrivacySignals: countryAccess.ipPrivacy?.signals,
spurIpPrivacySignals: countryAccess.spurIpPrivacy?.signals,
spurStatus: countryAccess.spurStatus,
privacyDecision,
privacyProviderDecision,
privacyHardBlocked: hardBlocked,
clientIp: countryAccess.hasClientIp ? '[redacted]' : undefined,
},
'Free mode country detection',
)
}
if (hardBlocked) {
const error = 'free_mode_unavailable'
const message = getHardBlockedFreeModeMessage(countryAccess)
await endFreebuffSession({
userId,
userEmail: userInfo.email ?? null,
})
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_VALIDATION_ERROR,
userId,
properties: {
error,
countryCode: countryAccess.countryCode,
countryBlockReason: countryAccess.blockReason,
ipPrivacySignals: countryAccess.ipPrivacy?.signals,
spurIpPrivacySignals: countryAccess.spurIpPrivacy?.signals,
spurStatus: countryAccess.spurStatus,
privacyDecision,
privacyProviderDecision,
privacyHardBlocked: hardBlocked,
clientIp: countryAccess.hasClientIp ? '[redacted]' : undefined,
accessStatus: 'blocked',
},
logger,
})
return NextResponse.json(
{
error,
message,
countryCode: countryAccess.countryCode ?? 'UNKNOWN',
countryBlockReason: countryAccess.blockReason ?? undefined,
ipPrivacySignals: countryAccess.ipPrivacy?.signals ?? undefined,
},
{ status: 403 },
)
}
trackEvent = withDefaultProperties(trackEvent, {
accessTier: freebuffAccessTier,
accessStatus: freebuffAccessTier,
privacyDecision,
privacyProviderDecision,
privacyHardBlocked: hardBlocked,
spurStatus: countryAccess.spurStatus,
})
if (!countryAccess.allowed) {
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_VALIDATION_ERROR,
userId,
properties: {
error: 'free_mode_not_available_in_country',
countryCode: countryAccess.countryCode,
countryBlockReason: countryAccess.blockReason,
ipPrivacySignals: countryAccess.ipPrivacy?.signals,
spurIpPrivacySignals: countryAccess.spurIpPrivacy?.signals,
spurStatus: countryAccess.spurStatus,
privacyDecision,
privacyProviderDecision,
privacyHardBlocked: hardBlocked,
clientIp: countryAccess.hasClientIp ? '[redacted]' : undefined,
},
logger,
})
}
}
// Track API request. Freebuff success-path analytics are sampled to keep
// high-volume free traffic from dominating PostHog and log forwarding.
trackSuccessEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_REQUEST,
userId,
properties: {
hasStream: !!bodyStream,
hasRunId: !!runId,
userInfo,
},
logger,
})
// Extract and validate agent run ID
const runIdFromBody = typedBody.codebuff_metadata?.run_id
if (!runIdFromBody || typeof runIdFromBody !== 'string') {
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_VALIDATION_ERROR,
userId,
properties: {
error: 'Missing or invalid run_id',
},
logger,
})
return NextResponse.json(
{ message: 'No runId found in request body' },
{ status: 400 },
)
}
// Get and validate agent run
const agentRun = await getAgentRunFromId({
runId: runIdFromBody,
userId,
fields: ['agent_id', 'ancestor_run_ids', 'status'],
})
if (!agentRun) {
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_VALIDATION_ERROR,
userId,
properties: {
error: 'Agent run not found',
runId: runIdFromBody,
},
logger,
})
return NextResponse.json(
{ message: `runId Not Found: ${runIdFromBody}` },
{ status: 400 },
)
}
const {
agent_id: agentId,
ancestor_run_ids: ancestorRunIds,
status: agentRunStatus,
} = agentRun
if (agentRunStatus !== 'running') {
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_VALIDATION_ERROR,
userId,
properties: {
error: 'Agent run not running',
runId: runIdFromBody,
status: agentRunStatus,
},
logger,
})
return NextResponse.json(
{ message: `runId Not Running: ${runIdFromBody}` },
{ status: 400 },
)
}
// Free-mode requests must use an allowlisted agent+model combination.
// Without this gate, an attacker on a brand-new unpaid account can set
// cost_mode='free' to bypass both the paid-account check and the balance
// check, then request an expensive model (Opus, etc). Our OpenRouter key
// pays for the call; the downstream credit-consumption step records an
// audit row but can't actually deduct from a user who has no grants —
// net result is free Opus for the attacker, real dollars for us. Check
// must happen here, before any call to OpenRouter.
if (
isFreeModeRequest &&
!isFreeModeAllowedAgentModel(agentId, typedBody.model)
) {
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_VALIDATION_ERROR,
userId,
properties: {
error: 'free_mode_invalid_agent_model',
agentId,
model: typedBody.model,
},
logger,
})
return NextResponse.json(
{
error: 'free_mode_invalid_agent_model',
message:
'Free mode is only available for specific agent and model combinations.',
},
{ status: 403 },
)
}
if (isFreeModeRequest && !isFreebuffRootAgent(agentId)) {
const rootRunId = ancestorRunIds[0]
const rootRun = rootRunId
? await getAgentRunFromId({
runId: rootRunId,
userId,
fields: ['agent_id', 'status'],
})
: null
if (
!rootRun ||
rootRun.status !== 'running' ||
!isFreebuffRootAgent(rootRun.agent_id)
) {
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_VALIDATION_ERROR,
userId,
properties: {
error: 'free_mode_invalid_agent_hierarchy',
agentId,
runId: runIdFromBody,
rootRunId,
},
logger,
})
return NextResponse.json(
{
error: 'free_mode_invalid_agent_hierarchy',
message:
'Free mode subagents must run under an active freebuff session root.',
},
{ status: 403 },
)
}
}
if (
isFreeModeRequest &&
freebuffAccessTier === 'limited' &&
(isSupportedFreebuffModelId(typedBody.model) ||
typedBody.model === FREEBUFF_GEMINI_PRO_MODEL_ID) &&
!isFreebuffModelAllowedForAccessTier(typedBody.model, freebuffAccessTier)
) {
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_VALIDATION_ERROR,
userId,
properties: {
error: 'session_model_mismatch',
model: typedBody.model,
accessTier: freebuffAccessTier,
},
logger,
})
return NextResponse.json(
{
error: 'session_model_mismatch',
message:
'Limited free access is only available with DeepSeek V4 Flash.',
},
{ status: STATUS_BY_GATE_CODE.session_model_mismatch },
)
}
let freeModeSessionGate: SessionGateResult | null = null
// Freebuff waiting-room gate. Usually enforced only when
// FREEBUFF_WAITING_ROOM_ENABLED=true. Runs before the rate limiter so
// rejected requests don't burn a queued user's free-mode counters.
if (isFreeModeRequest) {
const claimedInstanceId =
typedBody.codebuff_metadata?.freebuff_instance_id
freeModeSessionGate = await checkSession({
userId,
accessTier: freebuffAccessTier,
userEmail: userInfo.email,
claimedInstanceId,
requestedModel: typedBody.model,
requireActiveSession: isFreebuffGeminiThinkerAgent(agentId),
})
if (!freeModeSessionGate.ok) {
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_VALIDATION_ERROR,
userId,
properties: { error: freeModeSessionGate.code },
logger,
})
return NextResponse.json(
{
error: freeModeSessionGate.code,
message: freeModeSessionGate.message,
},
{ status: STATUS_BY_GATE_CODE[freeModeSessionGate.code] },
)
}
}
// Rate limit free mode requests (after validation so invalid requests don't consume quota)
if (isFreeModeRequest) {
const rateLimitResult = checkFreeModeRateLimit(userId)
if (rateLimitResult.limited) {
const retryAfterSeconds = Math.ceil(rateLimitResult.retryAfterMs / 1000)
const resetTime = new Date(
Date.now() + rateLimitResult.retryAfterMs,
).toISOString()
const resetCountdown = formatQuotaResetCountdown(resetTime)
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_VALIDATION_ERROR,
userId,
properties: {
error: 'free_mode_rate_limited',
windowName: rateLimitResult.windowName,
retryAfterSeconds,
},
logger,
})
return NextResponse.json(
{
error: 'free_mode_rate_limited',
message: `Free mode rate limit exceeded (${rateLimitResult.windowName} limit). Try again ${resetCountdown}.`,
},
{
status: 429,
headers: { 'Retry-After': String(retryAfterSeconds) },
},
)
}
}
// For subscribers, ensure a block grant exists before processing the request.
// This is done AFTER validation so malformed requests don't start a new 5-hour block.
// When the function is provided, always include subscription credits in the balance:
// error/null results mean subscription grants have 0 balance, so including them is harmless.
const includeSubscriptionCredits =
!isFreeModeRequest && !!ensureSubscriberBlockGrant
if (!isFreeModeRequest && ensureSubscriberBlockGrant) {
try {
const blockGrantResult = await ensureSubscriberBlockGrant({
userId,
logger,
})
// Check if user hit subscription limit and should be rate-limited
if (
blockGrantResult &&
(isWeeklyLimitError(blockGrantResult) ||
isBlockExhaustedError(blockGrantResult))
) {
// Fetch user's preference for falling back to a-la-carte credits
const preferences = getUserPreferences
? await getUserPreferences({ userId, logger })
: { fallbackToALaCarte: true } // Default to allowing a-la-carte if no preference function
if (!preferences.fallbackToALaCarte) {
const resetTime = blockGrantResult.resetsAt
const resetCountdown = formatQuotaResetCountdown(
resetTime.toISOString(),
)
const limitType = isWeeklyLimitError(blockGrantResult)
? 'weekly'
: '5-hour session'
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_INSUFFICIENT_CREDITS,
userId,
properties: {
reason: 'subscription_limit_no_fallback',
limitType,
fallbackToALaCarte: false,
},
logger,
})
return NextResponse.json(
{
error: 'rate_limit_exceeded',
message: `Subscription ${limitType} limit reached. Your limit resets ${resetCountdown}. Enable "Continue with credits" in the CLI to use a-la-carte credits.`,
},
{ status: 429 },
)
}
// If fallbackToALaCarte is true, continue to use a-la-carte credits
logger.info(
{
userId,
limitType: isWeeklyLimitError(blockGrantResult)
? 'weekly'
: 'session',
},
'Subscriber hit limit, falling back to a-la-carte credits',
)
}
} catch (error) {
logger.error(
{ error: getErrorObject(error), userId },
'Error ensuring subscription block grant',
)
// Fail open: proceed with subscription credits included in balance check
}
}
// Free-mode requests have already passed their model/session/rate gates
// and should not touch paid billing/usage paths.
if (!isFreeModeRequest) {
// Fetch user credit data (includes subscription credits when block grant was ensured)
const {
balance: { totalRemaining },
nextQuotaReset,
} = await getUserUsageData({ userId, logger, includeSubscriptionCredits })
// Credit check
if (totalRemaining <= 0) {
trackEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_INSUFFICIENT_CREDITS,
userId,
properties: {
totalRemaining,
nextQuotaReset,
},
logger,
})
return NextResponse.json(
{
message: `Out of credits. Please add credits at ${env.NEXT_PUBLIC_CODEBUFF_APP_URL}/usage.`,
},
{ status: 402 },
)
}
}
const openrouterApiKey = req.headers.get(BYOK_OPENROUTER_HEADER)
const providerLogger = sampleSuccessLogger(logger, sampleFreebuffSuccess)
recordChatCompletionTrace({
body: typedBody,
userId,
agentId,
ancestorRunIds,
logger: providerLogger,
insertChatCompletionTraceBigquery,
})
const requestMetrics = beginChatCompletionRequestMetrics({
logger,
userId,
agentId,
runId: runIdFromBody,
model: typedBody.model,
streaming: bodyStream,
costMode,
})
// Handle streaming vs non-streaming
try {
if (bodyStream) {
// Streaming request — route supported models to direct providers.
const useSiliconFlow = false // isSiliconFlowModel(typedBody.model)
const useOpenCodeZen = isOpenCodeZenModel(typedBody.model)
const useMoonshot = !useOpenCodeZen && isMoonshotModel(typedBody.model)
const useCanopyWave =
!useMoonshot && !useOpenCodeZen && isCanopyWaveModel(typedBody.model)
const useDeepSeek =
!useMoonshot &&
!useOpenCodeZen &&
!useCanopyWave &&
isDeepSeekModel(typedBody.model)
const useFireworks =
!useMoonshot &&
!useOpenCodeZen &&
!useCanopyWave &&
!useDeepSeek &&
isFireworksModel(typedBody.model)
const useOpenAIDirect =
!useMoonshot &&
!useOpenCodeZen &&
!useCanopyWave &&
!useDeepSeek &&
!useFireworks &&
isOpenAIDirectModel(typedBody.model)
const baseArgs = {
body: typedBody,
userId,
stripeCustomerId,
agentId,
fetch,
logger: providerLogger,
insertMessageBigquery,
}
const stream = useSiliconFlow
? await handleSiliconFlowStream(baseArgs)
: useMoonshot
? await handleMoonshotStream(baseArgs)
: useOpenCodeZen
? await handleOpenCodeZenStream(baseArgs)
: useCanopyWave
? await handleCanopyWaveStream(baseArgs)
: useDeepSeek
? await handleDeepSeekStream(baseArgs)
: useFireworks
? await handleFireworksStream(baseArgs)
: useOpenAIDirect
? await handleOpenAIStream(baseArgs)
: await handleOpenRouterStream({
...baseArgs,
openrouterApiKey,
})
trackSuccessEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_STREAM_STARTED,
userId,
properties: {
agentId,
runId: runIdFromBody,
},
logger,
})
return new NextResponse(requestMetrics.wrapStream(stream), {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
'Access-Control-Allow-Origin': '*',
},
})
} else {
// Non-streaming request — route to direct providers for supported models
const model = typedBody.model
const useSiliconFlow = false // isSiliconFlowModel(model)
const useOpenCodeZen = isOpenCodeZenModel(model)
const useMoonshot = !useOpenCodeZen && isMoonshotModel(model)
const useCanopyWave =
!useMoonshot && !useOpenCodeZen && isCanopyWaveModel(model)
const useDeepSeek =
!useMoonshot &&
!useOpenCodeZen &&
!useCanopyWave &&
isDeepSeekModel(model)
const useFireworks =
!useMoonshot &&
!useOpenCodeZen &&
!useCanopyWave &&
!useDeepSeek &&
isFireworksModel(model)
const shouldUseOpenAIEndpoint =
!useMoonshot &&
!useOpenCodeZen &&
!useCanopyWave &&
!useDeepSeek &&
!useFireworks &&
isOpenAIDirectModel(model)
const baseArgs = {
body: typedBody,
userId,
stripeCustomerId,
agentId,
fetch,
logger: providerLogger,
insertMessageBigquery,
}
const nonStreamRequest = useSiliconFlow
? handleSiliconFlowNonStream(baseArgs)
: useMoonshot
? handleMoonshotNonStream(baseArgs)
: useOpenCodeZen
? handleOpenCodeZenNonStream(baseArgs)
: useCanopyWave
? handleCanopyWaveNonStream(baseArgs)
: useDeepSeek
? handleDeepSeekNonStream(baseArgs)
: useFireworks
? handleFireworksNonStream(baseArgs)
: shouldUseOpenAIEndpoint
? handleOpenAINonStream(baseArgs)
: handleOpenRouterNonStream({
...baseArgs,
openrouterApiKey,
})
const result = await nonStreamRequest
trackSuccessEvent({
event: AnalyticsEvent.CHAT_COMPLETIONS_GENERATION_STARTED,
userId,
properties: {
agentId,
runId: runIdFromBody,
streaming: false,
},
logger,
})
requestMetrics.end('completed')
return NextResponse.json(result)
}
} catch (error) {
requestMetrics.end('error', { error: getErrorObject(error) })
let openrouterError: OpenRouterError | undefined
if (error instanceof OpenRouterError) {
openrouterError = error
}
let fireworksError: FireworksError | undefined
if (error instanceof FireworksError) {
fireworksError = error
}
let canopywaveError: CanopyWaveError | undefined
if (error instanceof CanopyWaveError) {
canopywaveError = error
}
let deepseekError: DeepSeekError | undefined
if (error instanceof DeepSeekError) {
deepseekError = error
}
let moonshotError: MoonshotError | undefined
if (error instanceof MoonshotError) {
moonshotError = error
}
let siliconflowError: SiliconFlowError | undefined
if (error instanceof SiliconFlowError) {
siliconflowError = error
}
let openaiError: OpenAIError | undefined
if (error instanceof OpenAIError) {
openaiError = error
}
let opencodeZenError: OpenCodeZenError | undefined
if (error instanceof OpenCodeZenError) {
opencodeZenError = error
}
// Log detailed error information for debugging
const errorDetails = openrouterError?.toJSON()
const telemetryBody = createRequestAuditRecord(body)
const providerLabel = siliconflowError
? 'SiliconFlow'
: opencodeZenError
? 'OpenCode Zen'
: moonshotError
? 'Moonshot'
: canopywaveError
? 'CanopyWave'
: deepseekError
? 'DeepSeek'
: fireworksError
? 'Fireworks'