import 'dotenv/config';
import Fastify from 'fastify';
import { startWhatsAppBot, sendMessage, getQRCode, getConnectionStatus } from './services/whatsapp-baileys.js';
import { handleWhatsApp } from './webhook.js';
import { getActiveSessionCount } from './services/session.js';
const fastify = Fastify({ logger: false });
const PORT = Number(process.env.PORT || 3000);
// Root route (avoid confusing 404 on localhost:3000)
fastify.get('/', async () => ({
message: 'HealthBridge server is running',
endpoints: ['/health', '/qr', '/send']
}));
// QR Code page
fastify.get('/qr', async (_request, reply) => {
const qr = getQRCode();
if (!qr) {
const status = getConnectionStatus();
if (status.status === 'connected') {
return reply.type('text/html').send(`
HealthBridge โ Connected
โ
Connected & Active
WhatsApp: ${status.user?.id || 'unknown'}
Active sessions: ${getActiveSessionCount()} | Uptime: ${Math.floor(process.uptime() / 60)}m
`);
}
return reply.type('text/html').send(`
HealthBridge โ Connecting
Connecting...
Auto-refreshes in 5s
`);
}
return reply.type('text/html').send(`
HealthBridge QR
๐ฑ Scan with WhatsApp
Settings โ Linked Devices โ Link a Device
`);
});
// Health check
fastify.get('/health', async () => ({
status: 'ok',
whatsapp: getConnectionStatus().status,
user: getConnectionStatus().user?.id || null,
sessions: getActiveSessionCount(),
uptime: `${Math.floor(process.uptime() / 60)}m ${Math.floor(process.uptime() % 60)}s`,
models: {
vision: 'Google Gemma 4 31B (free via OpenRouter โ multimodal vision)',
reasoning: 'K2 Think V2 โ MBZUAI-IFM/K2-Think-v2 (70B, deep reasoning)',
intent: 'Google Gemma 4 31B (free via OpenRouter โ fast text)',
k2_configured: !!process.env.K2_API_KEY,
openrouter_configured: !!process.env.OPENROUTER_API_KEY,
},
features: {
emergency_override: '9 languages, <50ms, no LLM',
vision_ocr: 'Gemma 4 Vision โ prescriptions, pills, reports',
deep_reasoning: 'K2 Think V2 โ medication analysis, document explanation',
drug_interactions: 'RxNorm + openFDA FAERS โ real death counts',
symptom_triage: 'Conversational 6-step + K2 assessment + MedlinePlus',
clinic_finder: 'ZIP โ nearest FQHCs with sliding fee scale',
pill_identification: 'Gemma 4 Vision โ K2 reasoning โ FDA verify',
discharge_explainer: 'K2 Think V2 โ medical jargon โ 5-year-old language',
medication_reminders: '3-tier escalation (initial โ missed โ caregiver)',
medication_safety_score: 'Green/Yellow/Red based on interactions',
cost_saving: 'GoodRx, CostPlusDrugs, Walmart $4, EMTALA rights',
languages: 'EN, ES, ZH, HI, AR, VI, KO, TL, PT + auto-detect 16+ scripts',
security: 'HMAC hashing, rate limiting, zero PHI storage'
}
}));
// Manual send endpoint
fastify.post('/send', async (request, reply) => {
const { to, message } = request.body as { to: string; message: string };
if (!to || !message) return reply.code(400).send({ error: 'Missing "to" or "message"' });
try {
await sendMessage(to, message);
return { sent: true, to, length: message.length };
} catch (err: any) {
return reply.code(400).send({ error: err.message });
}
});
async function main() {
console.log(`
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐ฅ HealthBridge โ AI Health Companion v3.1 โ
โ Dual-Model: Gemma 4 (Vision) + K2 Think V2 (Reasoning) โ
โ Production Mode ยท All Features Active โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ง AI Models:
๐๏ธ Vision: Google Gemma 4 31B (free via OpenRouter โ multimodal)
๐ง Reasoning: K2 Think V2 โ MBZUAI/IFM (70B deep reasoning)
๐ฏ Intent: Google Gemma 4 31B (free via OpenRouter)
K2 API Key: ${process.env.K2_API_KEY ? 'โ
configured' : 'โ missing โ add K2_API_KEY to .env'}
OpenRouter: ${process.env.OPENROUTER_API_KEY ? 'โ
configured' : 'โ missing โ add OPENROUTER_API_KEY to .env'}
๐ Active Features:
๐จ Emergency Override ......... 9 languages, <50ms, no AI needed
๐ธ Pill Identification ........ Gemma 4 Vision โ K2 reasoning โ FDA verify
๐ Document Reader ............ Prescriptions, discharge, labs, EOBs
๐ Drug Interactions .......... RxNorm + FDA FAERS (real death data)
๐ฉบ Symptom Assessment ......... 6-step conversational + K2 analysis
๐ฅ Clinic Finder .............. ZIP โ free/low-cost FQHCs
๐ Discharge Explainer ........ K2 Think V2 โ 5-year-old language
โฐ Medication Reminders ....... 3-tier escalation system
๐ก๏ธ Safety Score ............... Green/Yellow/Red interaction rating
๐ต Cost Saving ................ GoodRx, CostPlusDrugs, Walmart $4
๐ Languages .................. 16+ scripts auto-detected
๐ Security ................... HMAC, rate limiting, zero PHI
`);
// Start WhatsApp bot
await startWhatsAppBot(async (from, text, media) => {
try {
const mockReq = {
body: {
From: from,
Body: text,
MediaBuffer: media?.buffer || null,
MediaType: media?.mimeType || '',
}
};
const mockReply = {
code: (code: number) => ({
send: (body: any) => {
if (code >= 400) console.log(` โ ๏ธ [${code}]:`, JSON.stringify(body));
}
})
};
await handleWhatsApp(mockReq as any, mockReply as any);
} catch (err) {
console.error('โ Error:', err);
try { await sendMessage(from, 'โ ๏ธ Something went wrong. Please try again in a moment.'); } catch {}
}
});
await fastify.listen({ port: PORT, host: '0.0.0.0' });
console.log(`\nโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Server: http://localhost:${PORT}
QR: http://localhost:${PORT}/qr
Health: http://localhost:${PORT}/health
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\n`);
}
main().catch(console.error);