Files
instantadpay/public/assets/admin-kb.js
T
martbost 1e040f21ff Chat knowledge base: the assistant answers from maintained entries, and support replies become entries
- kb.js: entries { id, title, questions, answer, tags, pattern, handoff, order, source, updated } in MySQL table kb_entries (created on boot) or DATA_DIR/kb.json without DATABASE_URL. BM25 over title, question variants and tags (answer at a low weight) with word bigrams; the top hits (within 30% of the best, score 3+) go into the system prompt as KNOWLEDGE BASE, and when nothing fits the prompt says to answer "I'm not sure, ask support".
- One source: chatbot.js CANNED seeds the KB (ids c-*, its regex becomes the entry's instant-answer pattern, same first-match order), kb-seed.js seeds the home FAQ, Platform Facts, wallets FAQ and the Coinbase support reply (f-*). The fast path now serves the KB entry, so an admin edit changes the instant answer; the in-code CANNED only answers if the KB store fails. Unedited seeds follow code changes, edited ones are left alone, deleted seeds stay deleted.
- Admin > Knowledge base: list, search, filter by source, add, edit, delete, and Try a question (instant answer or what the AI is given). Support tickets: "Save as KB entry" under each sent reply opens a draft with the member's question and the reply (greeting and sign-off trimmed). Em dashes in admin input become commas.
- chatbot.js: OPENROUTER_URL override for tests; solo-ads answer em dash removed; KNOWLEDGE_DATE 2026-10-20.
- qa/chatbot-sync.mjs: takes the later of KNOWLEDGE_DATE and /api/chat/kb-stamp (newest KB edit by a person, Central day; seed refreshes do not count).
- QA: qa/kb-retrieval.cjs (13 sample questions rank the right entry first, off-topic returns nothing), qa/kb-chat.mjs (local copy + mock OpenRouter: Coinbase answered from the KB, fast path without an AI call, admin CRUD, restart keeps edits), bash qa/run.sh kb; walk covers admin#kb and Save as KB entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:37:09 -05:00

109 lines
11 KiB
JavaScript

// Admin > Knowledge base (2026-10-20, kb.js on the server): list, search, add, edit and delete the
// entries the chat assistant answers from, try a question against them, and take a support reply
// straight into a new entry (admin.js calls IAPKB.compose from a ticket's "Save as KB entry").
(function () {
const $ = IAP.$;
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
async function api(path, body, method) {
const opts = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} };
if (body !== undefined) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body); }
const r = await (await fetch(path, opts)).json();
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
return r;
}
const ctDay = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', year: 'numeric' }) : '';
const SRC = { canned: 'from the code', faq: 'FAQ', ticket: 'from a ticket', admin: 'added here' };
let entries = [], filter = { q: '', src: '' }, wired = false;
function wire() {
if (wired) return; wired = true;
let t = null;
$('kbQ').addEventListener('input', () => { clearTimeout(t); t = setTimeout(() => { filter.q = $('kbQ').value.trim(); load().catch(e => IAP.status(e.message, 'bad')); }, 300); });
$('kbSrc').addEventListener('change', () => { filter.src = $('kbSrc').value; draw(); });
$('kbNew').addEventListener('click', () => compose({}));
$('kbTable').addEventListener('click', e => { const tr = e.target.closest('[data-kbid]'); if (tr) edit(tr.dataset.kbid).catch(err => IAP.status(err.message, 'bad')); });
const go = async () => {
const q = $('kbTry').value.trim(); if (!q) return $('kbTry').focus();
const r = await api('/api/admin/kb/test', { question: q });
$('kbTryOut').innerHTML = (r.fast ? '<p style="margin:6px 0"><b>Instant answer:</b> ' + esc(r.fast.title) + ' <span class="mono muted">' + esc(r.fast.id) + '</span> (no AI call)</p>' : '<p style="margin:6px 0">No instant answer, so this goes to the AI with:</p>')
+ (r.ranked.length ? '<ol style="margin:4px 0 0 18px;padding:0">' + r.ranked.map(h => '<li' + (h.used ? '' : ' class="muted"') + '><a href="#" data-kbopen="' + esc(h.id) + '">' + esc(h.title) + '</a> <span class="mono">' + h.score + '</span>' + (h.used ? ' <b>used</b>' : '') + '</li>').join('') + '</ol>'
: '<p class="muted" style="margin:4px 0">No entry matches, so the assistant is told to say it is not sure and point to support.</p>');
};
$('kbTryGo').addEventListener('click', () => go().catch(e => IAP.status(e.message, 'bad')));
$('kbTry').addEventListener('keydown', e => { if (e.key === 'Enter') go().catch(err => IAP.status(err.message, 'bad')); });
$('kbTryOut').addEventListener('click', e => { const a = e.target.closest('[data-kbopen]'); if (a) { e.preventDefault(); edit(a.dataset.kbopen).catch(err => IAP.status(err.message, 'bad')); } });
}
async function load() {
wire();
$('kbEdit').hidden = true; $('kbList').hidden = false;
const r = await api('/api/admin/kb' + (filter.q ? '?q=' + encodeURIComponent(filter.q) : ''));
entries = r.entries || [];
$('kbSub').textContent = (r.stamp ? r.stamp.count : entries.length) + ' entries' + (r.stamp && r.stamp.updated ? ' · last change ' + r.stamp.updated : '');
draw();
}
function draw() {
const rows = entries.filter(e => !filter.src || e.source === filter.src);
$('kbTable').innerHTML = '<tr><th>Entry</th><th>Asked as</th><th>Source</th><th>Updated</th></tr>'
+ (rows.length ? rows.map(e => '<tr data-kbid="' + esc(e.id) + '" style="cursor:pointer"><td><b>' + esc(e.title) + '</b>' + (e.score != null ? ' <span class="small muted mono">' + e.score + '</span>' : '')
+ '<div class="small muted">' + esc(String(e.answer).slice(0, 140)) + (String(e.answer).length > 140 ? '…' : '') + '</div>'
+ ((e.tags || []).length ? '<div class="small" style="margin-top:3px">' + e.tags.map(t => '<span class="house-tag" style="margin:0 4px 0 0">' + esc(t) + '</span>').join('') + '</div>' : '') + '</td>'
+ '<td class="small">' + (e.questions || []).slice(0, 3).map(esc).join('<br>') + ((e.questions || []).length > 3 ? '<br><span class="muted">+' + (e.questions.length - 3) + ' more</span>' : '') + '</td>'
+ '<td class="small">' + esc(SRC[e.source] || e.source) + (e.pattern ? '<div class="muted">instant</div>' : '') + (e.ticketRef ? '<div class="mono muted">' + esc(e.ticketRef) + '</div>' : '') + (e.edited && e.source !== 'admin' && e.source !== 'ticket' ? '<div class="muted">edited</div>' : '') + '</td>'
+ '<td class="small muted" style="white-space:nowrap">' + esc(ctDay(e.updated)) + '</td></tr>').join('')
: '<tr><td colspan="4" class="muted">No entries here.</td></tr>');
}
async function edit(id) { const r = await api('/api/admin/kb/' + encodeURIComponent(id)); compose(r.entry); }
// e: an existing entry (has id), or a prefill for a new one ({ title, questions, answer, tags, source, ticketRef })
function compose(e) {
wire();
e = e || {};
const isNew = !e.id;
$('kbList').hidden = true; $('kbEdit').hidden = false;
$('kbEdit').innerHTML = '<div class="card-head"><h3>' + (isNew ? 'New entry' : 'Edit entry') + '</h3><span class="sub mono">' + (isNew ? (e.ticketRef ? 'from ' + esc(e.ticketRef) : '') : esc(e.id) + ' · ' + esc(SRC[e.source] || e.source) + (e.ticketRef ? ' · ' + esc(e.ticketRef) : '') + ' · updated ' + esc(ctDay(e.updated))) + '</span></div>'
+ (e.source === 'ticket' && isNew ? '<p class="small" style="margin:0 0 10px;color:var(--amber,#ffb238)">Taken from a support reply. Take out names, emails, member numbers and anything about this one account before saving: entries are shown to the assistant for every member who asks something similar.</p>' : '')
+ (!isNew && (e.source === 'canned' || e.source === 'faq') && !e.edited ? '<p class="small muted" style="margin:0 0 10px">This entry comes from the code (chatbot.js or kb-seed.js) and follows it when the code changes. Saving it here makes it yours: later code changes to this entry are not applied.</p>' : '')
+ '<div style="display:grid;gap:10px">'
+ '<label class="small">Title<input id="kbTitle" maxlength="200" style="width:100%" value="' + esc(e.title || '') + '" placeholder="Can I use my regular Coinbase account?"></label>'
+ '<label class="small">Question variants, one per line (how members actually ask it)<textarea id="kbQs" rows="4" style="width:100%">' + esc((e.questions || []).join('\n')) + '</textarea></label>'
+ '<label class="small">Answer (plain words, no em dashes, never a promise of income; full https links)<textarea id="kbAns" rows="8" maxlength="4000" style="width:100%">' + esc(e.answer || '') + '</textarea></label>'
+ '<label class="small">Tags, comma separated<input id="kbTags" style="width:100%" value="' + esc((e.tags || []).join(', ')) + '" placeholder="coinbase, exchange account, wallet"></label>'
+ '<label class="small"><input type="checkbox" id="kbHandoff"' + (e.handoff ? ' checked' : '') + '> Offer "Send this to support" under this answer</label>'
+ '<details' + (e.pattern ? ' open' : '') + '><summary class="small">Instant answer (advanced)</summary>'
+ '<p class="small muted" style="margin:6px 0">A regular expression (case-insensitive). When a question matches it, this answer is sent as is, with no AI call. The lowest order number wins when several match; the code seeds use 10, 20, 30 and so on. Leave it empty to answer through the AI only.</p>'
+ '<div style="display:grid;grid-template-columns:1fr 110px;gap:8px"><input id="kbPat" class="mono small" value="' + esc(e.pattern || '') + '" placeholder="(coinbase account|regular coinbase)"><input id="kbOrd" class="small" type="number" value="' + (e.order == null ? '' : esc(e.order)) + '" placeholder="order"></div></details>'
+ '</div>'
+ '<p style="display:flex;gap:10px;flex-wrap:wrap;margin:14px 0 0"><button type="button" class="btn small" id="kbSave">' + (isNew ? 'Add entry' : 'Save') + '</button><button type="button" class="btn small sec" id="kbCancel">Cancel</button>'
+ (isNew ? '' : '<button type="button" class="btn small sec" id="kbDel" style="margin-left:auto">Delete</button>') + '</p>';
$('kbCancel').addEventListener('click', () => { load().catch(err => IAP.status(err.message, 'bad')); });
$('kbSave').addEventListener('click', async () => {
const b = $('kbSave'); if (b.disabled) return; b.disabled = true;
try {
const body = { title: $('kbTitle').value, questions: $('kbQs').value.split('\n'), answer: $('kbAns').value, tags: $('kbTags').value.split(','),
handoff: $('kbHandoff').checked, pattern: $('kbPat').value, order: $('kbOrd').value, source: e.source, ticketRef: e.ticketRef };
if (isNew) await api('/api/admin/kb', body); else await api('/api/admin/kb/' + encodeURIComponent(e.id), body, 'PUT');
IAP.status(isNew ? 'Entry added. The assistant uses it from the next question.' : 'Entry saved.', 'ok');
await load();
} catch (err) { IAP.status(err.message, 'bad'); } finally { b.disabled = false; }
});
if ($('kbDel')) $('kbDel').addEventListener('click', async () => {
if (!(await IAP.confirmBox('Delete "' + (e.title || e.id) + '"? The assistant stops using it right away.', { ok: 'Delete', cancel: 'Keep it' }))) return;
try { await api('/api/admin/kb/' + encodeURIComponent(e.id), undefined, 'DELETE'); IAP.status('Entry deleted.', 'ok'); await load(); } catch (err) { IAP.status(err.message, 'bad'); }
});
$('kbTitle').focus();
}
// a support reply, tidied into a draft: the greeting and sign-off go, the member's words become the question
function fromTicket(t, question, reply) {
const q = String(question || '').replace(/^[\s\S]*?\bMe: /, '').split(/\nAssistant: /)[0].replace(/\s+/g, ' ').trim().slice(0, 300);
const a = String(reply || '').replace(/^\s*(hi|hello|hey|dear|good (morning|afternoon|evening))\b[^\n]*\n+/i, '')
.replace(/\n+\s*(thanks|thank you|cheers|best|regards|kind regards|talk soon|marty)\b[\s\S]{0,80}$/i, '').trim();
const title = String(t.subject || '').replace(/^Chat:\s*/i, '').trim().slice(0, 200) || q.slice(0, 120);
const tags = String(t.category || '').toLowerCase().split(/\s*&\s*|\s*,\s*/).filter(x => x && x !== 'other');
return { title, questions: q ? [q] : [], answer: a, tags, source: 'ticket', ticketRef: t.ref };
}
window.IAPKB = { load: () => load(), compose, fromTicket };
})();