import { ECHO_ENDPOINT, BUILD_INSTRUCTIONS, geminiFailure } from "./gemini-policy"; export async function buildSite(sessionId: string, request: string, previous?: string, userId?: string) { const key = process.env["GEMINI_API_KEY"]; if (!key) return { error: "Gemini key is missing." } as const; const text = previous ? `Current page HTML:\n${previous.slice(0, 60000)}\n\nApply this request (keep what isn't changed): ${request}` : request; const send = () => fetch(ECHO_ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json", "x-goog-api-key": key }, body: JSON.stringify({ systemInstruction: { parts: [{ text: BUILD_INSTRUCTIONS }] }, contents: [{ role: "user", parts: [{ text }] }] }), }); let res = await send(); // One retry only for Google's temporary overload errors (never for quota 429). if (res.status === 500 || res.status === 503) res = await send(); if (!res.ok) return { error: geminiFailure(res.status) } as const; const json = (await res.json()) as { candidates?: { content?: { parts?: { text?: string; thought?: boolean }[] } }[] }; let html = (json.candidates?.[0]?.content?.parts ?? []).filter((p) => !p.thought).map((p) => p.text ?? "").join("").trim(); html = html.replace(/^```(?:html)?\s*/i, "").replace(/```\s*$/, "").trim(); if (!/