224 lines
5.6 KiB
JavaScript
224 lines
5.6 KiB
JavaScript
// main.js
|
|
// Express server for: Ops UI (static) + SSE stream + Local WhatsApp Simulator + simple in-memory stores
|
|
// Run: npm i express cors && node main.js
|
|
// Open: http://localhost:3000
|
|
|
|
import express from "express";
|
|
import cors from "cors";
|
|
import crypto from "crypto";
|
|
import path from "path";
|
|
import { fileURLToPath } from "url";
|
|
|
|
const app = express();
|
|
app.use(cors());
|
|
app.use(express.json({ limit: "1mb" }));
|
|
|
|
// Serve /public as static (UI + webcomponents)
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = path.dirname(__filename);
|
|
const publicDir = path.join(__dirname, "public");
|
|
app.use(express.static(publicDir));
|
|
|
|
/**
|
|
* In-memory store (MVP). Replace with Postgres later.
|
|
*/
|
|
const conversations = new Map(); // chat_id -> conversation snapshot
|
|
const runs = new Map(); // run_id -> run object
|
|
|
|
/**
|
|
* SSE clients (Server-Sent Events)
|
|
*/
|
|
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);
|
|
}
|
|
|
|
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: Replace this with your real pipeline later:
|
|
* - loadState from Postgres
|
|
* - call LLM (structured output)
|
|
* - product search (LIMITED) + resolve ids
|
|
* - create/update Woo order
|
|
* - save state
|
|
*/
|
|
async function processMessage({ chat_id, from, text }) {
|
|
const prevConv = conversations.get(chat_id) || null;
|
|
|
|
const run_id = newId("run");
|
|
const started_at = Date.now();
|
|
|
|
// Minimal simulated LLM output (replace later)
|
|
const plan = {
|
|
reply: `Recibido: "${text}". ¿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 },
|
|
{ name: "no_order_action_without_items", ok: true },
|
|
],
|
|
};
|
|
|
|
const run = {
|
|
run_id,
|
|
ts: nowIso(),
|
|
chat_id,
|
|
from,
|
|
status: "ok", // ok|warn|error
|
|
prev_state: prevConv?.state || "IDLE",
|
|
input: { text },
|
|
llm_output: plan,
|
|
tools: [], // later: [{name, ok, ms, input_summary, output_summary}]
|
|
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 events to UI
|
|
sseSend("conversation.upsert", conv);
|
|
sseSend("run.created", run);
|
|
|
|
return run;
|
|
}
|
|
|
|
/**
|
|
* SSE endpoint (UI connects here)
|
|
*/
|
|
app.get("/stream", (req, res) => {
|
|
res.setHeader("Content-Type", "text/event-stream");
|
|
res.setHeader("Cache-Control", "no-cache");
|
|
res.setHeader("Connection", "keep-alive");
|
|
|
|
// If compression middleware ever added, you'd need res.flushHeaders()
|
|
res.flushHeaders?.();
|
|
|
|
// hello event
|
|
res.write(`event: hello\ndata: ${JSON.stringify({ ts: nowIso() })}\n\n`);
|
|
|
|
sseClients.add(res);
|
|
|
|
req.on("close", () => {
|
|
sseClients.delete(res);
|
|
res.end();
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Local WhatsApp Simulator:
|
|
* POST /sim/send { chat_id, from_phone, text }
|
|
*/
|
|
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({ ok: false, error: "chat_id, from_phone, text are required" });
|
|
}
|
|
try {
|
|
const run = await processMessage({ chat_id, from: from_phone, text });
|
|
res.json({ ok: true, run_id: run.run_id, reply: run.final_reply });
|
|
} catch (err) {
|
|
res.status(500).json({ ok: false, error: "internal_error", detail: String(err?.message || err) });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* List conversations
|
|
* GET /conversations?q=&status=&state=
|
|
*/
|
|
app.get("/conversations", (req, res) => {
|
|
const { q = "", status = "", state = "" } = req.query;
|
|
|
|
const items = [...conversations.values()]
|
|
.filter(c => (q ? (String(c.chat_id).includes(q) || String(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 });
|
|
});
|
|
|
|
/**
|
|
* List runs (optionally by chat_id)
|
|
* GET /runs?chat_id=&limit=50
|
|
*/
|
|
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
|
|
* GET /runs/:run_id
|
|
*/
|
|
app.get("/runs/:run_id", (req, res) => {
|
|
const run = runs.get(req.params.run_id);
|
|
if (!run) return res.status(404).json({ ok: false, error: "not_found" });
|
|
res.json(run);
|
|
});
|
|
|
|
/**
|
|
* Root: serve UI
|
|
*/
|
|
app.get("/", (req, res) => {
|
|
res.sendFile(path.join(publicDir, "index.html"));
|
|
});
|
|
|
|
const port = process.env.PORT || 3000;
|
|
app.listen(port, () => {
|
|
console.log(`UI: http://localhost:${port}`);
|
|
});
|