skeleton of the core app

This commit is contained in:
Lucas Tettamanti
2026-01-02 00:21:46 -03:00
parent a1fb46f70c
commit 947b0bd1ee
12 changed files with 735 additions and 152 deletions

228
index.js
View File

@@ -1,120 +1,35 @@
import "dotenv/config";
import express from "express";
import cors from "cors";
import crypto from "crypto";
import path from "path";
import { fileURLToPath } from "url";
import { ensureTenant, listConversations, listRuns, getRunById } from "./src/db/repo.js";
import { addSseClient, removeSseClient, sseSend } from "./src/services/sse.js";
import { processMessage } from "./src/services/pipeline.js";
const app = express();
app.use(cors());
app.use(express.json({ limit: "1mb" }));
app.use(express.static("public"));
// 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). Luego lo pasás a Postgres.
* --- Tenant ---
*/
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
const TENANT_KEY = process.env.TENANT_KEY || "piaf";
let TENANT_ID = null;
/**
* 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
* --- SSE endpoint ---
*/
app.get("/stream", (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
@@ -123,58 +38,101 @@ app.get("/stream", (req, res) => {
res.flushHeaders?.();
res.write(`event: hello\ndata: ${JSON.stringify({ ts: nowIso() })}\n\n`);
sseClients.add(res);
addSseClient(res);
req.on("close", () => {
sseClients.delete(res);
removeSseClient(res);
res.end();
});
});
/**
* Simulated WhatsApp send
* --- 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({ error: "chat_id, from_phone, text are required" });
return res.status(400).json({ ok: false, error: "chat_id, from_phone, text are required" });
}
try {
const provider = "sim";
const message_id = crypto.randomUUID(); // idempotencia por mensaje sim
const result = await processMessage({
tenantId: TENANT_ID,
chat_id,
from: from_phone,
text,
provider,
message_id,
});
res.json({ ok: true, run_id: result.run_id, reply: result.reply });
} catch (err) {
console.error(err);
res.status(500).json({ ok: false, error: "internal_error", detail: String(err?.message || err) });
}
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
* --- UI data endpoints ---
*/
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 });
app.get("/conversations", async (req, res) => {
const { q = "", status = "", state = "", limit = "50" } = req.query;
try {
const items = await listConversations({
tenant_id: TENANT_ID,
q: String(q || ""),
status: String(status || ""),
state: String(state || ""),
limit: parseInt(limit, 10) || 50,
});
res.json({ items });
} catch (err) {
console.error(err);
res.status(500).json({ ok: false, error: "internal_error" });
}
});
app.get("/runs", async (req, res) => {
const { chat_id = null, limit = "50" } = req.query;
try {
const items = await listRuns({
tenant_id: TENANT_ID,
wa_chat_id: chat_id ? String(chat_id) : null,
limit: parseInt(limit, 10) || 50,
});
res.json({ items });
} catch (err) {
console.error(err);
res.status(500).json({ ok: false, error: "internal_error" });
}
});
app.get("/runs/:run_id", async (req, res) => {
try {
const run = await getRunById({ tenant_id: TENANT_ID, run_id: req.params.run_id });
if (!run) return res.status(404).json({ ok: false, error: "not_found" });
res.json(run);
} catch (err) {
console.error(err);
res.status(500).json({ ok: false, error: "internal_error" });
}
});
app.get("/", (req, res) => {
res.sendFile(path.join(publicDir, "index.html"));
});
/**
* Runs by chat
* --- Boot ---
*/
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}`));
(async function boot() {
TENANT_ID = await ensureTenant({ key: TENANT_KEY, name: TENANT_KEY.toUpperCase() });
app.listen(port, () => console.log(`UI: http://localhost:${port} (tenant=${TENANT_KEY})`));
})().catch((err) => {
console.error("Boot failed:", err);
process.exit(1);
});