|
| 1 | +import { type NextRequest, NextResponse } from 'next/server' |
| 2 | +import { z } from 'zod' |
| 3 | +import { |
| 4 | + authenticateCopilotRequestSessionOnly, |
| 5 | + createBadRequestResponse, |
| 6 | + createInternalServerErrorResponse, |
| 7 | + createRequestTracker, |
| 8 | + createUnauthorizedResponse, |
| 9 | +} from '@/lib/copilot/auth' |
| 10 | +import { env } from '@/lib/env' |
| 11 | +import { SIM_AGENT_API_URL_DEFAULT } from '@/lib/sim-agent' |
| 12 | + |
| 13 | +const SIM_AGENT_API_URL = env.SIM_AGENT_API_URL || SIM_AGENT_API_URL_DEFAULT |
| 14 | + |
| 15 | +const BodySchema = z |
| 16 | + .object({ |
| 17 | + // Do NOT send id; messageId is the unique correlator |
| 18 | + userId: z.string().optional(), |
| 19 | + chatId: z.string().uuid().optional(), |
| 20 | + messageId: z.string().optional(), |
| 21 | + depth: z.number().int().nullable().optional(), |
| 22 | + maxEnabled: z.boolean().nullable().optional(), |
| 23 | + createdAt: z.union([z.string().datetime(), z.date()]).optional(), |
| 24 | + diffCreated: z.boolean().nullable().optional(), |
| 25 | + diffAccepted: z.boolean().nullable().optional(), |
| 26 | + duration: z.number().int().nullable().optional(), |
| 27 | + inputTokens: z.number().int().nullable().optional(), |
| 28 | + outputTokens: z.number().int().nullable().optional(), |
| 29 | + aborted: z.boolean().nullable().optional(), |
| 30 | + }) |
| 31 | + .passthrough() |
| 32 | + |
| 33 | +export async function POST(req: NextRequest) { |
| 34 | + const tracker = createRequestTracker() |
| 35 | + try { |
| 36 | + const { userId, isAuthenticated } = await authenticateCopilotRequestSessionOnly() |
| 37 | + if (!isAuthenticated || !userId) { |
| 38 | + return createUnauthorizedResponse() |
| 39 | + } |
| 40 | + |
| 41 | + const json = await req.json().catch(() => ({})) |
| 42 | + const parsed = BodySchema.safeParse(json) |
| 43 | + if (!parsed.success) { |
| 44 | + return createBadRequestResponse('Invalid request body for copilot stats') |
| 45 | + } |
| 46 | + const body = parsed.data as any |
| 47 | + |
| 48 | + // Build outgoing payload for Sim Agent; do not include id |
| 49 | + const payload: Record<string, any> = { |
| 50 | + ...body, |
| 51 | + userId: body.userId || userId, |
| 52 | + createdAt: body.createdAt || new Date().toISOString(), |
| 53 | + } |
| 54 | + payload.id = undefined |
| 55 | + |
| 56 | + const agentRes = await fetch(`${SIM_AGENT_API_URL}/api/stats`, { |
| 57 | + method: 'POST', |
| 58 | + headers: { |
| 59 | + 'Content-Type': 'application/json', |
| 60 | + ...(env.COPILOT_API_KEY ? { 'x-api-key': env.COPILOT_API_KEY } : {}), |
| 61 | + }, |
| 62 | + body: JSON.stringify(payload), |
| 63 | + }) |
| 64 | + |
| 65 | + // Prefer not to block clients; still relay status |
| 66 | + let agentJson: any = null |
| 67 | + try { |
| 68 | + agentJson = await agentRes.json() |
| 69 | + } catch {} |
| 70 | + |
| 71 | + if (!agentRes.ok) { |
| 72 | + const message = (agentJson && (agentJson.error || agentJson.message)) || 'Upstream error' |
| 73 | + return NextResponse.json({ success: false, error: message }, { status: 400 }) |
| 74 | + } |
| 75 | + |
| 76 | + return NextResponse.json({ success: true }) |
| 77 | + } catch (error) { |
| 78 | + return createInternalServerErrorResponse('Failed to forward copilot stats') |
| 79 | + } |
| 80 | +} |
0 commit comments