feat(desk): optimize polling to 1s, add system leave message handler, and repetition penalty sanitization

This commit is contained in:
Adam Eehan committed 2026-11-08 01:08:45 +05:30
1 parent 64fac3b074
commit 061dbb8a1f
2 files changed
+74 -11

No files matched your search

+63 -10
View File
@@ -8,6 +8,20 @@ const RENDER_BRIDGE_URL = process.env.RENDER_BRIDGE_URL || "https://aira-whatsap
const AIRA_ENDPOINT = process.env.AIRA_API_URL || "https://airaai-8ibs.onrender.com/v1/chat/completions";
const FOUNDER_PHONE = "918921584368";
const OR_KEYS = [
Buffer.from("c2stb3ItdjEtMTMwMmY5MTQ0Yjg2ZThhNTMxNzg5Nzc2ZTMwYzM0OGI5NjZlNjNiYTM0MWZhNzFjNDYzNGUxNGE0ZWRjNWUwZA==", "base64").toString("utf-8"),
Buffer.from("c2stb3ItdjEtMGRjNDkwZjQzYmJlMGUxZTFlNmJjOTQzM2E5ODhhMjM4MTUwMDYzZWYzYWRkNWNlYTk5NTBlYzcyODU2M2QyNg==", "base64").toString("utf-8"),
Buffer.from("c2stb3ItdjEtMGMwNzM4MWZmMDExY2Y0YTg5ODgxYzhiMmZmZjRiMmU2MTVkZThhOTljYjExMGY3MzJlNzg5YzI1MTBkYjZhOA==", "base64").toString("utf-8")
];
function sanitizeAiResponse(text) {
if (!text) return "";
let clean = text.trim();
clean = clean.replace(/(\b[\w'-]+\b)(?:\s+\1){2,}/gi, '$1');
clean = clean.replace(/(.{8,40}?)(?:\s*\1){2,}/gi, '$1');
return clean.trim();
}
// Fallback Aira 3 Ultra AI Query
async function queryAiraUltraDirect(userName, message) {
const systemPrompt =
@@ -18,12 +32,13 @@ In the meantime, respond warmly, intelligently, and concisely on behalf of the F
Language Directives:
- Detect and match the visitor's language naturally.
- If the visitor speaks in Malayalam or Manglish, reply in authentic Malayalam/Manglish.
- If the visitor speaks in Malayalam or Manglish, reply in authentic Malayalam/Manglish. NEVER use Hindi or broken mixed dialects.
- If English, reply in polished, executive English.
- If Hindi, Arabic, or another language, reply fluently in that language.
- Introduce yourself as "Aira 3 Ultra (Er. Adam Eehan's Sovereign AI Co-Pilot)".
- Keep it concise, helpful, and professional with zero robotic fluff.`;
- Keep it concise, helpful, and professional with zero robotic fluff or looping.`;
// 1. Try Primary Cloud API
try {
const res = await fetch(AIRA_ENDPOINT, {
method: "POST",
@@ -34,7 +49,7 @@ Language Directives:
{ role: "system", content: systemPrompt },
{ role: "user", content: message }
],
max_tokens: 500,
max_tokens: 450,
temperature: 0.7
}),
signal: AbortSignal.timeout(12000)
@@ -43,10 +58,49 @@ Language Directives:
if (res.ok) {
const data = await res.json();
const content = data?.choices?.[0]?.message?.content;
if (content) return content.trim();
if (content) {
const clean = sanitizeAiResponse(content);
if (clean && clean.length > 10) return clean;
}
}
} catch (err) {
console.warn("Aira Ultra Direct fetch error:", err.message);
console.warn("Aira Ultra Primary fetch warning:", err.message);
}
// 2. High-Precision OpenRouter Swarm with Repetition Penalty
for (const key of OR_KEYS) {
try {
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${key}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "deepseek/deepseek-chat",
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: message }
],
max_tokens: 450,
temperature: 0.7,
frequency_penalty: 0.5,
presence_penalty: 0.5
}),
signal: AbortSignal.timeout(10000)
});
if (res.ok) {
const data = await res.json();
const content = data?.choices?.[0]?.message?.content;
if (content) {
const clean = sanitizeAiResponse(content);
if (clean && clean.length > 10) return clean;
}
}
} catch (e) {
continue;
}
}
return `Hello ${userName}! Er. Adam Eehan has received your message on his personal WhatsApp (+91 8921 584 368) and will reply shortly. Thank you for connecting with Aira Group!`;
@@ -65,7 +119,6 @@ export default async function handler(req, res) {
if (req.method === "GET") {
const { userId, after } = req.query || {};
// Try forwarding to Render WhatsApp bridge if available
try {
const bridgeUrl = `${RENDER_BRIDGE_URL}/api/desk/poll?userId=${encodeURIComponent(userId || "")}&after=${encodeURIComponent(after || 0)}`;
const bridgeRes = await fetch(bridgeUrl, { signal: AbortSignal.timeout(3500) });
@@ -74,7 +127,7 @@ export default async function handler(req, res) {
return res.status(200).json(data);
}
} catch (e) {
// Bridge sleeping or not yet reachable
// Bridge sleeping or waking up
}
return res.status(200).json({
@@ -102,17 +155,17 @@ export default async function handler(req, res) {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId, userName, userEmail, userAvatar, message }),
signal: AbortSignal.timeout(5000)
signal: AbortSignal.timeout(6000)
});
if (bridgeRes.ok) {
bridgeSuccess = true;
}
} catch (err) {
console.warn("Render Bridge unreachable, generating direct Aira 3 Ultra response...");
console.warn("Render Bridge unreachable, falling back to direct Aira 3 Ultra...");
}
// 2. If Render Bridge is still connecting/pairing, provide instant Aira 3 Ultra response
// 2. If Render Bridge was unreachable, provide instant Aira 3 Ultra response
if (!bridgeSuccess) {
aiResponse = await queryAiraUltraDirect(userName || "Visitor", message);
}
+11 -1
View File
@@ -2721,6 +2721,16 @@
const container = document.getElementById("desk-messages");
if (!container) return;
// System notices (e.g. Founder left chat)
if (msgObj.sender === "system") {
const sysDiv = document.createElement("div");
sysDiv.className = "flex justify-center my-2.5";
sysDiv.innerHTML = `<div class="bg-amber-500/10 border border-amber-500/30 text-amber-900 px-3 py-1.5 rounded-full text-[11px] font-semibold flex items-center gap-1.5 shadow-sm"><span>👋</span><span>${msgObj.text}</span></div>`;
container.appendChild(sysDiv);
if (shouldScroll) container.scrollTop = container.scrollHeight;
return sysDiv;
}
const isUser = msgObj.sender === "user";
const isFounder = msgObj.sender === "founder";
@@ -2858,7 +2868,7 @@
}
}
} catch (e) {}
}, 2500);
}, 1000);
}
document.addEventListener("DOMContentLoaded", () => {