import { z } from "zod"; import { apiError, apiJson } from "@/lib/api-handler"; import { resolveApiAuth } from "@/lib/api-auth"; import { isLlmConfigured } from "@/lib/llm"; import { runAgentChat } from "@/modules/agent/server/run"; const chatInput = z.object({ messages: z .array( z.object({ role: z.enum(["user", "assistant"]), content: z.string().trim().min(1).max(8000), }), ) .min(1) .max(40), }); export async function POST(request: Request) { const auth = await resolveApiAuth(request); if (!auth) { return apiError("Unauthorized", 401); } let body: unknown; try { body = await request.json(); } catch { return apiError("Invalid JSON body", 400); } const parsed = chatInput.safeParse(body); if (!parsed.success) { return apiError(parsed.error.issues[0]?.message ?? "Validation error", 400); } try { const result = await runAgentChat({ messages: parsed.data.messages, request, }); return apiJson({ ...result, configured: isLlmConfigured(), provider: isLlmConfigured() ? "openai" : "mock", }); } catch (err) { const message = err instanceof Error ? err.message : "Agent request failed"; return apiError(message, 502); } }