181 lines
4.6 KiB
JavaScript
181 lines
4.6 KiB
JavaScript
import express from "express";
|
|
import cors from "cors";
|
|
import crypto from "crypto";
|
|
|
|
const app = express();
|
|
app.use(cors());
|
|
app.use(express.json({ limit: "1mb" }));
|
|
app.use(express.static("public"));
|
|
|
|
/**
|
|
* In-memory store (MVP). Luego lo pasás a Postgres.
|
|
*/
|
|
const conversations = new Map(); // chat_id -> { chat_id, from, state, intent, last_activity, status, last_run_id }
|
|
const runs = new Map(); // run_id -> run payload
|
|
|
|
/**
|
|
* SSE clients
|
|
*/
|
|
const sseClients = new Set();
|
|
function sseSend(event, data) {
|
|
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
for (const res of sseClients) res.write(payload);
|
|
}
|
|
|
|
/**
|
|
* Helpers
|
|
*/
|
|
function nowIso() {
|
|
return new Date().toISOString();
|
|
}
|
|
function newId(prefix = "run") {
|
|
return `${prefix}_${crypto.randomUUID()}`;
|
|
}
|
|
function upsertConversation(chat_id, patch) {
|
|
const prev = conversations.get(chat_id) || {
|
|
chat_id,
|
|
from: patch.from || chat_id,
|
|
state: "IDLE",
|
|
intent: "other",
|
|
last_activity: nowIso(),
|
|
status: "ok",
|
|
last_run_id: null,
|
|
};
|
|
const next = { ...prev, ...patch, last_activity: nowIso() };
|
|
conversations.set(chat_id, next);
|
|
return next;
|
|
}
|
|
|
|
/**
|
|
* TODO: Reemplazar esto por tu pipeline real:
|
|
* - loadState (Postgres)
|
|
* - llm.plan (Structured Output)
|
|
* - tools: searchProducts (limitado), createOrder, createPaymentLink
|
|
* - invariants
|
|
* - saveState
|
|
*/
|
|
async function processMessage({ chat_id, from, text }) {
|
|
// Simulación mínima: reemplazá por tu lógica real
|
|
const prevConv = conversations.get(chat_id) || null;
|
|
|
|
const run_id = newId("run");
|
|
const started_at = Date.now();
|
|
|
|
// Ejemplo de “plan” simulado
|
|
const plan = {
|
|
reply: `Recibido: "${text}". (Sim) ¿Querés retiro o envío?`,
|
|
next_state: "BUILDING_ORDER",
|
|
intent: "create_order",
|
|
missing_fields: ["delivery_or_pickup"],
|
|
order_action: "none",
|
|
basket_resolved: { items: [] },
|
|
};
|
|
|
|
const invariants = {
|
|
ok: true,
|
|
checks: [
|
|
{ name: "required_keys_present", ok: true },
|
|
{ name: "no_checkout_without_payment_link", ok: true },
|
|
],
|
|
};
|
|
|
|
const run = {
|
|
run_id,
|
|
ts: nowIso(),
|
|
chat_id,
|
|
from,
|
|
status: "ok",
|
|
prev_state: prevConv?.state || "IDLE",
|
|
input: { text },
|
|
llm_output: plan,
|
|
tools: [], // acá metés searchProducts/createOrder/createPaymentLink (con inputs/outputs recortados)
|
|
invariants,
|
|
final_reply: plan.reply,
|
|
order_id: null,
|
|
payment_link: null,
|
|
latency_ms: Date.now() - started_at,
|
|
};
|
|
|
|
runs.set(run_id, run);
|
|
|
|
const conv = upsertConversation(chat_id, {
|
|
from,
|
|
state: plan.next_state,
|
|
intent: plan.intent,
|
|
status: run.status,
|
|
last_run_id: run_id,
|
|
});
|
|
|
|
// Push realtime
|
|
sseSend("conversation.upsert", conv);
|
|
sseSend("run.created", run);
|
|
|
|
return run;
|
|
}
|
|
|
|
/**
|
|
* SSE stream
|
|
*/
|
|
app.get("/stream", (req, res) => {
|
|
res.setHeader("Content-Type", "text/event-stream");
|
|
res.setHeader("Cache-Control", "no-cache");
|
|
res.setHeader("Connection", "keep-alive");
|
|
res.flushHeaders?.();
|
|
|
|
res.write(`event: hello\ndata: ${JSON.stringify({ ts: nowIso() })}\n\n`);
|
|
sseClients.add(res);
|
|
|
|
req.on("close", () => {
|
|
sseClients.delete(res);
|
|
res.end();
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Simulated WhatsApp send
|
|
*/
|
|
app.post("/sim/send", async (req, res) => {
|
|
const { chat_id, from_phone, text } = req.body || {};
|
|
if (!chat_id || !from_phone || !text) {
|
|
return res.status(400).json({ error: "chat_id, from_phone, text are required" });
|
|
}
|
|
const run = await processMessage({ chat_id, from: from_phone, text });
|
|
res.json({ ok: true, run_id: run.run_id, reply: run.final_reply });
|
|
});
|
|
|
|
/**
|
|
* List conversations
|
|
*/
|
|
app.get("/conversations", (req, res) => {
|
|
const { q = "", status = "", state = "" } = req.query;
|
|
const items = [...conversations.values()]
|
|
.filter(c => (q ? (c.chat_id.includes(q) || c.from.includes(q)) : true))
|
|
.filter(c => (status ? c.status === status : true))
|
|
.filter(c => (state ? c.state === state : true))
|
|
.sort((a, b) => (a.last_activity < b.last_activity ? 1 : -1));
|
|
res.json({ items });
|
|
});
|
|
|
|
/**
|
|
* Runs by chat
|
|
*/
|
|
app.get("/runs", (req, res) => {
|
|
const { chat_id, limit = "50" } = req.query;
|
|
const lim = Math.max(1, Math.min(200, parseInt(limit, 10) || 50));
|
|
let items = [...runs.values()].sort((a, b) => (a.ts < b.ts ? 1 : -1));
|
|
if (chat_id) items = items.filter(r => r.chat_id === chat_id);
|
|
res.json({ items: items.slice(0, lim) });
|
|
});
|
|
|
|
/**
|
|
* Run detail
|
|
*/
|
|
app.get("/runs/:run_id", (req, res) => {
|
|
const run = runs.get(req.params.run_id);
|
|
if (!run) return res.status(404).json({ error: "not_found" });
|
|
res.json(run);
|
|
});
|
|
|
|
const port = process.env.PORT || 3000;
|
|
app.listen(port, () => console.log(`UI: http://localhost:${port}`));
|