// The site assistant's engine (Marty 2026-11-15: a chatbot on every rebuilt network site), ported from LinkSpin's chatbot.js. // The site's own chatbot.js holds what it knows (CANNED instant answers + FACTS, written from that site's code); this file // holds how it answers, the same on every site: // 1. the knowledge base's instant answers (kb.js, seeded from CANNED; first matching pattern wins, no AI call) // (since 2026-11-16 only a hand-off pattern answers outright; any other pattern hit is checked against step 1b) // 1b. the hub's semantic match by meaning (netkb.route, core2 embeddings): answers with this site's entry when it is sure, // keeps or overrules a pattern hit, and picks the prompt context; fails soft to the old path within NETKB_MATCH_MS // 2. retrieval over the merged NETWORK knowledge base (this site's entries boosted, netkb.js), into the system prompt // 3. OpenRouter (deepseek/deepseek-v4-flash:nitro, reasoning OFF, retried once), house rules in the prompt and on the way out // Account problems go to the network support desk on InstantAdPay (handoff: true makes the widget offer it). // Routes: POST /api/chat, GET /api/chat/kb-stamp, admin GET/POST /api/admin/kb, GET/PUT/DELETE /api/admin/kb/, // POST /api/admin/kb/test, GET /api/admin/kb/network (x-admin-token, the site's own isAdmin). // The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL. 'use strict'; const fs = require('fs'); const path = require('path'); const https = require('https'); const http = require('http'); const kb = require('./kb'); const netkb = require('./netkb'); const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro'; let S = null; // the site: { id, hubSite, name, url, dataDir, canned, faq, facts(), about, supportUrl, linkFor, quickTopics } function key() { if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); if (!S || !S.dataDir) return ''; try { return fs.readFileSync(path.join(S.dataDir, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } } const enabled = () => !!key(); // CANNED + FAQ in the shape kb.js stores (order keeps the first-match-wins sequence) function seeds() { return S.canned.map((c, i) => ({ id: 'c-' + c.id, title: c.title, questions: c.q || [], answer: c.a, tags: c.tags || [], pattern: c.re ? c.re.source : '', handoff: !!c.handoff, order: (i + 1) * 10, source: 'canned' })).concat(S.faq || []); } const supportUrl = () => S.supportUrl || 'https://instantadpay.com/support'; // asking for a person, or one person's own account problem: every site's first CANNED entry uses this (handoff: true) const SUPPORT_RE = /((contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|someone|a (human|person|real person))|real person|\bhuman\b|customer (service|support)|open a ticket|support (ticket|desk|team|email)|help ?desk|(my|the) (boost|purchase|payment|payout|order|account|sign.?in|log.?in|pro|upgrade|ad|banner|pick)s? (is |was |has |did |does )?(not|never|n.?t|missing|stuck|wrong|failed|broken|lost|gone)|(did ?n.?t|did not|never|has ?n.?t|have ?n.?t) (show|arriv|appear|receiv|get paid|go through|work|confirm)|i (was|got) (charged|scammed)|charged twice)/i; const HOUSE_RULES = () => `RULES: - 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page. - Your main job is ${S.name}. Questions about another network site: answer from that site's knowledge-base entry, say which site it is about, and give that site's link exactly as the entry gives it. Never mix two sites' prices, splits or rules. - NEVER promise or estimate income, and never state a maximum or total anyone can earn. This is advertising with a referral program, never an investment. Nobody earns unless real purchases happen in their line. Crypto payments are final. - Whenever ad credits come up, say: Ad credits buy advertising, not income. - Wallets: say "SafePal or any other crypto wallet". Never recommend MetaMask. - Never mention RM Circle. It is not part of this network. - No em dashes. If you do not know, say so plainly; never guess a price, a percentage or a rule. - Anything about one person's own account (a missing payout, a sign-in that will not work, a purchase that did not show, a bug) you cannot look up: say so and send them to network support at ${supportUrl()}.`; function networkLine() { const list = netkb.sites(); if (!list.length) return ''; return '\nNETWORK SITES (one network account works across them; link to use for each):\n' + list.map(s => '- ' + s.name + ': ' + s.go).join('\n') + '\n'; } function systemPrompt(kbBlock) { return S.intro + '\n\nFACTS (checked against this site\'s code on ' + S.knowledgeDate + '):\n' + S.facts() + '\n' + networkLine() + '\n' + HOUSE_RULES() + (kbBlock ? '\n\n' + kbBlock : ''); } function endpoint() { try { return new URL(process.env.OPENROUTER_URL || 'https://openrouter.ai/api/v1/chat/completions'); } catch (e) { return new URL('https://openrouter.ai/api/v1/chat/completions'); } } function askOnce(message, historyText, kbBlock) { return new Promise((resolve, reject) => { const body = JSON.stringify({ model: MODEL, reasoning: { enabled: false }, // deepseek-v4-flash reasons by default and can spend the whole max_tokens on it (2026-10-16) max_tokens: 320, messages: [ { role: 'system', content: systemPrompt(kbBlock) }, ...(historyText ? [{ role: 'user', content: 'Earlier context: ' + String(historyText).slice(0, 800) }] : []), { role: 'user', content: String(message).slice(0, 600) } ] }); const ep = endpoint(); const req = (ep.protocol === 'http:' ? http : https).request({ hostname: ep.hostname, port: ep.port || undefined, path: ep.pathname + ep.search, method: 'POST', headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body), 'HTTP-Referer': S.url, 'X-Title': S.name + ' assistant' }, timeout: 30000 }, res => { let d = ''; res.on('data', c => { d += c; }); res.on('end', () => { // OpenRouter can pad a slow upstream with keepalive lines before the JSON (IAP, 2026-09-17): find the object const i = d.indexOf('{'); let txt = ''; try { txt = String(JSON.parse(i < 0 ? d : d.slice(i)).choices[0].message.content || '').trim(); } catch (e) { return reject(new Error('openrouter ' + res.statusCode + ': ' + d.slice(0, 150))); } if (!txt) return reject(new Error('openrouter ' + res.statusCode + ': empty content')); resolve(txt); }); }); req.on('error', reject); req.on('timeout', () => req.destroy(new Error('openrouter timeout'))); req.end(body); }); } async function askAI(message, historyText, kbBlock) { try { return await askOnce(message, historyText, kbBlock); } catch (e) { await new Promise(r => setTimeout(r, 700)); return askOnce(message, historyText, kbBlock); } // one provider dropping it is the usual cause } // house rules on the way out, whatever the model wrote const RMC_RE = /\brm ?circle\b|rmcircle/i; function scrub(t) { let s = String(t || '').replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', '); s = s.replace(/\*\*(.+?)\*\*/g, '$1').replace(/^#+\s*/gm, ''); s = s.replace(/\bMeta ?Mask\b(\s*(,|or|and)\s*)?/gi, '').replace(/\s{2,}/g, ' ').trim(); return s; } const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unable to help|no way for me|i (can|could) ?not (see|check|look)|contact support|network support|support desk|\/support\b)/i; async function answer(message, historyText) { const r = await answerRaw(message, historyText); if (r && typeof r.reply === 'string') { r.reply = scrub(r.reply); if (RMC_RE.test(r.reply)) r.reply = 'I can only help with ' + S.name + ' and the network sites. For anything else, network support at ' + supportUrl() + ' can point you the right way.'; } return r; } async function answerRaw(message, historyText) { const msg = String(message || '').trim().slice(0, 600); if (!msg) return { error: 'Say something first.' }; let hit = null, kbOk = true, other = []; try { await kb.load(); // a question about another network site (named, and this site not named) skips this site's instant answers, except a hand-off other = kb.namesOther(msg, S.hubSite); if (other.length && new RegExp('\\b' + S.name.replace(/[^A-Za-z0-9]+/g, '\\s*') + '\\b', 'i').test(msg)) other = []; hit = await kb.fastPath(msg); if (hit && other.length && !hit.handoff) hit = null; } catch (e) { kbOk = false; console.error('kb fast path', e.message); } // a hand-off (support, one person's account problem) always answers from its exact pattern, before anything else if (hit && hit.handoff) return { reply: hit.answer, canned: true, kb: hit.id, handoff: true }; // then meaning (2026-11-16, netkb.route): the hub's semantic match over the network KB answers, keeps or overrules the // pattern hit, and picks the prompt context. Hub or model slow or down: null, and the pattern + BM25 path below runs as before. let sem = null; if (kbOk) { try { sem = await netkb.route(msg, { fast: hit, own: await kb.own(), prefer: other }); } catch (e) { sem = null; } } if (sem) hit = sem.hit; if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, sem ? { via: sem.via } : {}, hit.handoff ? { handoff: true } : {}); if (!kbOk) for (const c of S.canned) if (c.re && c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {}); let kbBlock = '', kbIds = [], hits = []; try { const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg; hits = sem && sem.hits.length ? sem.hits : await kb.context(query, 6); kbBlock = kb.promptBlock(hits); kbIds = hits.map(h => h.entry.id); } catch (e) { console.error('kb search', e.message); } if (!enabled()) { // no AI: the best matching entry, if it is a clear match, else the honest fallback if (hits.length) { const e = hits[0].entry; return { reply: e.answer + (e.site ? ' More at ' + e.go : ''), kb: [e.id] }; } return { reply: S.fallback || ('Good question. The quick answers I have cover how ' + S.name + ' works, what it costs and how payouts work. For anything else, network support at ' + supportUrl() + ' will help.'), handoff: true }; } try { const reply = await askAI(msg, historyText, kbBlock); return Object.assign({ reply }, kbIds.length ? { kb: kbIds } : {}, UNSURE_RE.test(reply) ? { handoff: true } : {}); } catch (e) { console.error('chat AI failed', e.message); if (hits.length) { const x = hits[0].entry; return { reply: x.answer + (x.site ? ' More at ' + x.go : ''), kb: [x.id] }; } return { reply: 'I hit a snag answering that one, on our side. The live ledger at ' + S.url + '/ledger and the contract page at ' + S.url + '/contract cover most deep questions, or network support at ' + supportUrl() + ' will answer.', handoff: true }; } } // ---- rate limit: per visitor, in memory ---- const hits = new Map(); function limited(ip) { const now = Date.now(); const h = hits.get(ip) || { m: 0, mAt: now, d: 0, dAt: now }; if (now - h.mAt > 60000) { h.m = 0; h.mAt = now; } if (now - h.dAt > 86400000) { h.d = 0; h.dAt = now; } h.m++; h.d++; hits.set(ip, h); if (hits.size > 20000) hits.clear(); return h.m > 12 || h.d > 300; } const ipOf = req => String(req.headers['cf-connecting-ip'] || String(req.headers['x-forwarded-for'] || '').split(',')[0] || (req.socket && req.socket.remoteAddress) || 'x').trim(); // h: { json(res, code, obj, extra), readBody(req), isAdmin(req) }; returns true when it answered async function handle(req, res, p, u, h) { if (p === '/api/chat' && req.method === 'POST') { if (limited(ipOf(req))) { h.json(res, 429, { error: 'Give it a minute, then ask again.' }); return true; } const b = await h.readBody(req); const hist = Array.isArray(b.history) ? b.history.map(x => String(x || '')).join(' ').slice(-800) : String(b.history || '').slice(-800); const r = await answer(b.message, hist); if (r.handoff) r.support = supportLink(b.message); h.json(res, r.error ? 400 : 200, r); return true; } if (p === '/api/chat/config' && req.method === 'GET') { h.json(res, 200, { name: S.name, support: supportUrl(), topics: S.quickTopics || [] }, { 'Cache-Control': 'public, max-age=300' }); return true; } if (p === '/api/chat/kb-stamp' && req.method === 'GET') { h.json(res, 200, Object.assign(await kb.stamp(), { knowledgeDate: S.knowledgeDate }), { 'Cache-Control': 'no-store' }); return true; } if (!p.startsWith('/api/admin/kb')) return false; if (!h.isAdmin(req)) { h.json(res, 401, { error: 'no' }); return true; } if (p === '/api/admin/kb') { if (req.method === 'GET') { h.json(res, 200, { entries: await kb.list(u.searchParams.get('q') || ''), stamp: await kb.stamp() }); return true; } if (req.method === 'POST') { const r = await kb.create(await h.readBody(req)); h.json(res, r.error ? 400 : 200, r); return true; } } if (p === '/api/admin/kb/test' && req.method === 'POST') { const b = await h.readBody(req); h.json(res, 200, Object.assign(await kb.test(b.question), b.answer ? { answer: await answer(b.question) } : {})); return true; } if (p === '/api/admin/kb/network' && req.method === 'GET') { if (u.searchParams.get('refresh') === '1') await netkb.refresh(); if (u.searchParams.get('publish') === '1') await netkb.publish(); h.json(res, 200, Object.assign(netkb.view(), { ai: enabled(), model: MODEL })); return true; } const m = /^\/api\/admin\/kb\/([A-Za-z0-9._:-]{1,80})$/.exec(p); if (m) { if (req.method === 'GET') { const e = await kb.get(m[1]); h.json(res, e ? 200 : 404, e ? { entry: e } : { error: 'Entry not found.' }); return true; } if (req.method === 'PUT') { const r = await kb.update(m[1], await h.readBody(req)); h.json(res, r.error ? (r.error === 'Entry not found.' ? 404 : 400) : 200, r); return true; } if (req.method === 'DELETE') { const r = await kb.remove(m[1]); h.json(res, r.error ? 404 : 200, r); return true; } } h.json(res, 404, { error: 'Not found' }); return true; } // the support desk link the widget offers: InstantAdPay's public form, told which site and question it came from function supportLink(q) { const qs = new URLSearchParams({ from: S.id, subject: (S.name + ': ' + String(q || '').replace(/\s+/g, ' ').trim()).slice(0, 120) }); return supportUrl() + '?' + qs.toString(); } // the link to another network site: its LinkSpin tracked link with ?src= (netsites.js), else its plain address const hostOf = x => { try { return new URL(x).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } }; function linkVia(netId) { return url => { try { const ns = require('./netsites'); const h = hostOf(url); const m = ns.list().concat(ns.FALLBACK || []).find(s => hostOf(s.url) === h); return (m && netId && m.id !== netId && ns.tracked(m.id, netId)) || url; } catch (e) { return url; } }; } // site: see S above. Call after docstore.init (kb.json is a MySQL document there). function init(site) { S = site; if (!S.linkFor) S.linkFor = linkVia(S.netId); const ready = kb.init({ dataDir: site.dataDir, seeds: seeds(), siteUrl: site.url, helpText: 'network support at ' + supportUrl() }); netkb.init({ dataDir: site.dataDir, site: site.hubSite, name: site.name, url: site.url, entries: () => kb.own(), linkFor: site.linkFor }); return ready; } module.exports = { init, handle, answer, enabled, seeds, systemPrompt, scrub, supportLink, linkVia, SUPPORT_RE, _limited: limited };