import express from "express"; import dotenv from "dotenv"; import cors from "cors"; dotenv.config(); const app = express(); app.use(cors()); app.use(express.json()); const PORT = Number(process.env.PORT || 7078); // core endpoints const CORTEX_REASON = process.env.CORTEX_REASON_URL || "http://cortex:7081/reason"; const CORTEX_INGEST = process.env.CORTEX_INGEST_URL || "http://cortex:7081/ingest"; const INTAKE_URL = process.env.INTAKE_URL || "http://intake:7082/summary"; // ----------------------------------------------------- // Helper request wrapper // ----------------------------------------------------- async function postJSON(url, data) { const resp = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), }); const raw = await resp.text(); let json; try { json = raw ? JSON.parse(raw) : null; } catch (e) { throw new Error(`Non-JSON from ${url}: ${raw}`); } if (!resp.ok) { throw new Error(json?.detail || json?.error || raw); } return json; } // ----------------------------------------------------- // HEALTHCHECK // ----------------------------------------------------- app.get("/_health", (_, res) => { res.json({ ok: true }); }); // ----------------------------------------------------- // MAIN ENDPOINT (new canonical) // ----------------------------------------------------- app.post("/chat", async (req, res) => { try { const session_id = req.body.session_id || "default"; const user_msg = req.body.message || ""; console.log(`Relay → received: "${user_msg}"`); // 1. → Cortex.reason let reason; try { reason = await postJSON(CORTEX_REASON, { session_id, user_prompt: user_msg }); } catch (e) { console.error("Relay → Cortex.reason error:", e.message); return res.status(500).json({ error: "cortex_reason_failed", detail: e.message }); } const persona = reason.final_output || reason.persona || "(no persona text)"; // 2. → Cortex.ingest postJSON(CORTEX_INGEST, { session_id, user_msg, assistant_msg: persona }).catch(e => console.warn("Relay → Cortex.ingest failed:", e.message)); // 3. → Intake summary postJSON(INTAKE_URL, { session_id, user_msg, assistant_msg: persona }).catch(e => console.warn("Relay → Intake failed:", e.message)); // 4. → Return to UI return res.json({ session_id, reply: persona }); } catch (err) { console.error("Relay fatal:", err); res.status(500).json({ error: "relay_failed", detail: err.message || String(err) }); } }); // ----------------------------------------------------- app.listen(PORT, () => { console.log(`Relay is online on port ${PORT}`); });