// relay/lib/cortex.js import fetch from "node-fetch"; const REFLECT_URL = process.env.CORTEX_URL || "http://localhost:7081/reflect"; const INGEST_URL = process.env.CORTEX_URL_INGEST || "http://localhost:7081/ingest"; export async function reflectWithCortex(userInput, memories = []) { const body = { prompt: userInput, memories }; try { const res = await fetch(REFLECT_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), timeout: 120000, }); const rawText = await res.text(); console.log("πŸ”Ž [Cortex-Debug] rawText from /reflect β†’", rawText.slice(0, 300)); if (!res.ok) { throw new Error(`HTTP ${res.status} β€” ${rawText.slice(0, 200)}`); } let data; try { data = JSON.parse(rawText); } catch (err) { // Fallback β‘  try to grab a JSON-looking block const match = rawText.match(/\{[\s\S]*\}/); if (match) { try { data = JSON.parse(match[0]); } catch { data = { reflection_raw: rawText.trim(), notes: "partial parse" }; } } else { // Fallback β‘‘ if it’s already an object (stringified Python dict) try { const normalized = rawText .replace(/'/g, '"') // convert single quotes .replace(/None/g, 'null'); // convert Python None data = JSON.parse(normalized); } catch { data = { reflection_raw: rawText.trim(), notes: "no JSON found" }; } } } if (typeof data !== "object") { data = { reflection_raw: rawText.trim(), notes: "non-object response" }; } console.log("🧠 Cortex reflection normalized:", data); return data; } catch (e) { console.warn("⚠️ Cortex reflect failed:", e.message); return { error: e.message, reflection_raw: "" }; } } export async function ingestToCortex(user, assistant, reflection = {}, sessionId = "default") { const body = { turn: { user, assistant }, reflection, session_id: sessionId }; try { const res = await fetch(INGEST_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), timeout: 120000, }); console.log(`πŸ“€ Sent exchange to Cortex ingest (${res.status})`); } catch (e) { console.warn("⚠️ Cortex ingest failed:", e.message); } }