const MAX_Q_CHARS = 800; function jsonResponse(body, init) { return new Response(JSON.stringify(body), { ...init, headers: { "content-type": "application/json; charset=utf-8", ...(init?.headers ?? {}), }, }); } function unauthorized() { return jsonResponse({ error: "unauthorized" }, { status: 401 }); } function badRequest(message) { return jsonResponse({ error: "bad_request", message }, { status: 400 }); } function serverError() { return jsonResponse({ error: "server_error" }, { status: 500 }); } function normalizeBearer(authHeader) { if (!authHeader) return null; const m = authHeader.match(/^Bearer\s+(.+)$/i); return m ? m[1] : null; } async function askDeepSeek(question, apiKey) { const upstream = "https://api.deepseek.com/chat/completions"; const res = await fetch(upstream, { method: "POST", headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json", }, body: JSON.stringify({ model: "deepseek-chat", messages: [ { role: "system", content: "You are Alfred, a voice assistant. Reply in English. Keep answers concise and speakable. Avoid markdown.", }, { role: "user", content: question }, ], temperature: 0.6, max_tokens: 220, }), }); if (!res.ok) { throw new Error(`Upstream error: ${res.status}`); } const data = await res.json(); const content = data?.choices?.[0]?.message?.content; return typeof content === "string" && content.trim() ? content.trim() : ""; } export default { async fetch(request, env) { try { const url = new URL(request.url); const pathname = url.pathname.endsWith("/") && url.pathname !== "/" ? url.pathname.slice(0, -1) : url.pathname; const isHealth = pathname === "/health" || pathname.endsWith("/health"); const isAsk = pathname === "/ask" || pathname.endsWith("/ask"); if (isHealth) { return jsonResponse({ ok: true }); } if (!isAsk) { return jsonResponse({ error: "not_found" }, { status: 404 }); } if (request.method !== "POST") { return jsonResponse({ error: "method_not_allowed" }, { status: 405 }); } const token = normalizeBearer(request.headers.get("authorization")); if (!token || token !== env.SHORTCUT_SECRET) { return unauthorized(); } let body; try { body = await request.json(); } catch { return badRequest("Body must be valid JSON"); } const q = typeof body?.q === "string" ? body.q.trim() : ""; if (!q) { return badRequest("Missing 'q'"); } if (q.length > MAX_Q_CHARS) { return badRequest(`'q' too long (max ${MAX_Q_CHARS} chars)`); } const answer = await askDeepSeek(q, env.DEEPSEEK_API_KEY); return jsonResponse({ answer }); } catch { return serverError(); } }, };