/* NEU — one box, three ways to get an answer, in order of what they cost. * * QUESTIONS come first, and are what the box opens on. Somebody at NEUON wrote * both the question and the answer in Backstage, so pressing one is instant, * free, and cannot come back with a wrong sentence. Most visitors never need * to go past this, which is the point: the questions people actually ask * should not be answered by a model at all. * * SEARCH is underneath them, and never leaves the page either: the list of * everything published is fetched once and typing filters it. No request per * keystroke, no model, no bill. * * ASK is the model, and it costs money per answer, so it is rationed: * * a visitor may ask when the switch is on in Backstage AND the month's * budget has something left. The server decides both and says so * on the wrapper as data-ask; this file never assumes. Asking is * a deliberate press on the Ask NEU row — Return goes to the best * matching page instead, so nobody spends anything by accident. * * staff type /unlock NEU-Agent and give a tier phrase. That opens the * chest, the document studio, and a much larger allowance. The * command is not the secret — the phrase is, and this file never * sees it: it is posted and checked server-side. * * Searching and reading an answer are two VIEWS of one box, not two boxes, and * a visitor can always get back to the search they came for. */ (function () { 'use strict'; var $ = function (s, r) { return (r || document).querySelector(s); }; var $$ = function (s, r) { return Array.prototype.slice.call((r || document).querySelectorAll(s)); }; var wrap = $('[data-nchat]'); if (!wrap) return; var panel = $('#nchatPanel'); var openBtn = $('[data-nchatopen]'); var form = $('[data-nchatform]'); var input = $('[data-nchatinput]'); var searchBox = $('[data-nchatsearch]'); var results = $('[data-nchatresults]'); var hint = $('[data-nchathint]'); var askSlot = $('[data-nchataskslot]'); var log = $('[data-nchatlog]'); var nameEl = $('[data-nchatname]'); var roleEl = $('[data-nchatrole]'); var footEl = $('[data-nchatfoot]'); var lockBtn = $('[data-nchatlock]'); var lockName = $('[data-nchatlockname]'); var backBtn = $('[data-nchatback]'); var lock = $('[data-nlock]'); /* MAY A VISITOR ACTUALLY GET AN ANSWER? * The server decides — the switch is on, there is a key, and there is budget * left this month — and says so on the wrapper. The page must never offer an * answer the server is going to refuse. */ var canAsk = wrap.getAttribute('data-ask') === '1'; /* ── THE QUESTIONS, ALREADY ANSWERED ── * Written by somebody at NEUON and carried with the page. Pressing one costs * nothing, waits for nothing, and cannot come back with a wrong sentence — * which is why they are what the box opens on, and the model is the thing * underneath for a question nobody anticipated. */ var FAQ = Array.isArray(window.NEUON_FAQ) ? window.NEUON_FAQ : []; var FAQ_SHOWN = 8; /* ── THE QUESTIONS ARE A MENU, NOT A LIST ── * Dr KC pointed at the Unifi chat: a few headings, press one, it opens into * the next few. Ten questions at once is a wall of text; four is a decision. * `menuAt` is which heading is open — null is the top. Typing searches the * whole tree at once, because somebody who types has already decided. */ var menuAt = null; var kidsOf = function (id) { return FAQ.filter(function (f) { return (f.parent || null) === id; }); }; var faqById = function (id) { for (var i = 0; i < FAQ.length; i++) if (FAQ[i].id === id) return FAQ[i]; return null; }; /* Searching and reading an answer are two views of one box. Staff open straight into the conversation; a visitor starts in search and goes to the conversation by asking something. */ var view = 'search'; /* set when the server hints there is a way to be interrupted less often; offered once, after an answer, never instead of one */ var askedToProveOnce = false; /* The way in for staff. Typed into the search box, where nothing advertises it. Spacing and case are forgiven — somebody reads this off a note. */ var COMMAND = /^\s*\/unlock\s+neu-?agent\s*$/i; /* "/make deck a pitch for JKR about RoadPlus" — staff only, and only in ask mode, because it costs money and a visitor never reaches it. */ var MAKE = /^\s*\/make\s+([a-z]+)\s+([\s\S]+)$/i; /* The list the box searches. The page arrives with a short one — the chapters and the standing pages — so the box is useful the instant it opens. The full list, everything the company has published, is fetched once on first open and cached by the browser after that. */ var INDEX = window.NEUON_SEARCH || []; var fetchedFull = false; function loadFullIndex() { if (fetchedFull) return; fetchedFull = true; fetch('/search-index.json') .then(function (r) { return r.ok ? r.json() : null; }) .then(function (list) { if (!list || !list.length) return; INDEX = list; /* redraw only if the person is still looking at search results */ if (!asking() && !panel.hidden) render(input.value); }) .catch(function () { /* the short list still works */ }); } var tier = wrap.getAttribute('data-tier') || 'public'; var history = []; var busy = false; /* ================= opening and closing ================= */ function show(on) { panel.hidden = !on; wrap.classList.toggle('is-open', on); if (openBtn) openBtn.setAttribute('aria-expanded', String(on)); document.body.classList.toggle('nchat-open', on); if (on) { loadFullIndex(); if (!asking()) render(''); setTimeout(function () { input.focus(); }, 60); } } if (openBtn) openBtn.addEventListener('click', function () { show(panel.hidden); }); $$('[data-nchatclose]').forEach(function (b) { b.addEventListener('click', function () { show(false); }); }); /* NEU's face in the top bar of the front page. It used to sit beside a magnifying glass and ask for a password; it is now the only button there and it opens this. */ var face = $('#navNeu'); if (face) { face.addEventListener('click', function () { show(panel.hidden); }); try { if (!localStorage.getItem('neu-seen')) { face.classList.add('is-new'); // one wave on a first visit localStorage.setItem('neu-seen', '1'); } } catch (e) { /* private browsing; a wave is not worth an error */ } } document.addEventListener('keydown', function (e) { if (e.key === 'Escape') { if (lock && !lock.hidden) { lock.hidden = true; return; } if (!panel.hidden) show(false); return; } /* "/" opens it, the shortcut the old search had */ if (e.key === '/' && panel.hidden && !/^(INPUT|TEXTAREA)$/.test(document.activeElement.tagName) && !document.activeElement.isContentEditable) { e.preventDefault(); show(true); } }); /* ================= which mode ================= */ function mode() { return tier === 'public' ? 'search' : 'ask'; } /* A tier that has unlocked the assistant is always in the conversation. A visitor is there only while reading an answer. */ function asking() { return mode() === 'ask' || view === 'chat'; } function goChat() { view = 'chat'; dress(); } function goSearch() { view = 'search'; menuAt = null; // back to the top of the menu, not wherever we were input.value = ''; dress(); render(''); input.focus(); } function dress() { var chat = asking(); var staff = mode() === 'ask'; searchBox.hidden = chat; log.hidden = !chat; wrap.setAttribute('data-tier', tier); input.placeholder = chat ? 'Ask NEU something…' : (canAsk ? 'Search, or ask me a question…' : 'Search the site…'); input.setAttribute('aria-label', chat ? 'Ask NEU something' : 'Search the site, or ask NEU'); nameEl.textContent = staff ? (tier === 'c' ? 'NEU-LEVEL C' : 'NEU-STAFF') : 'NEU'; roleEl.textContent = staff ? (tier === 'c' ? 'Everything, including the chest' : 'The working tier') /* NEU introduces itself. It used to open with an instruction — "Search the site" — which is what the box does, not who is offering. The placeholder in the input still says what typing will do. */ : 'Hi, I’m NEU — ask me anything, or search the site'; footEl.textContent = chat ? 'NEU is an AI and can be wrong.' : (canAsk ? 'Press a question, or ask NEU in your own words.' : 'Press a question, or type to search the site.'); if (lockBtn) { lockBtn.hidden = !staff; if (lockName) lockName.textContent = tier === 'c' ? 'NEU-LEVEL C' : 'NEU-STAFF'; } /* only a visitor needs the way back; staff have no search view to go to */ if (backBtn) backBtn.hidden = staff || view !== 'chat'; } /* ================= SEARCH ================= */ /* An empty box shows the whole list rather than nothing. That list IS the recommendation: somebody who opens this without a question in mind gets the running order of the site instead of a blinking cursor. */ /* HOW A RESULT IS SCORED. * * With a list of a dozen, "does the label contain it" was enough. With more * than a hundred it is not: typing "road" put a story whose body happens to * mention a road above RoadPlus itself. So a match is scored, best first — * the label counts for far more than the hidden keywords, and matching at * the START of a word counts for more than matching in the middle of one. * * Every word typed has to appear somewhere, so "jkr road" finds the story * that is about both rather than everything about either. */ var MAX_SHOWN = 40; function score(item, words) { var label = item.label.toLowerCase(); var keys = (item.keys || '').toLowerCase(); var total = 0; for (var i = 0; i < words.length; i++) { var w = words[i]; var inLabel = label.indexOf(w); var inKeys = keys.indexOf(w); if (inLabel < 0 && inKeys < 0) return 0; // every word must appear if (inLabel === 0) total += 100; // the label starts with it else if (inLabel > 0) { /* on a word boundary inside the label beats mid-word */ total += /[\s—·-]/.test(label.charAt(inLabel - 1)) ? 60 : 30; } else { total += (inKeys === 0 || /\s/.test(keys.charAt(inKeys - 1))) ? 12 : 6; } } if (label === words.join(' ')) total += 200; // typed it exactly return total; } function render(q) { var term = String(q || '').trim().toLowerCase(); var words = term ? term.split(/\s+/).filter(Boolean) : []; var hits; if (!words.length) { hits = INDEX; } else { hits = []; for (var i = 0; i < INDEX.length; i++) { var s = score(INDEX[i], words); if (s) hits.push({ s: s, i: i, it: INDEX[i] }); } /* ties keep the order the site publishes things in, which is somebody's deliberate ordering rather than an accident */ hits.sort(function (a, b) { return b.s - a.s || a.i - b.i; }); hits = hits.map(function (h) { return h.it; }); } var found = hits.length; if (found > MAX_SHOWN) hits = hits.slice(0, MAX_SHOWN); /* ── THE QUESTIONS COME FIRST ── * Somebody who opens this without a question in mind should be reading an * answer within one press, not composing a sentence. Matched on the * question itself and on the hidden words beside it, so "salary" finds * "Are you hiring?". */ var asked = []; if (mode() === 'search') { if (!words.length) { /* whichever level of the menu is open */ asked = kidsOf(menuAt).slice(0, FAQ_SHOWN); } else { /* typing searches the WHOLE tree at once, headings included — somebody who types has already decided what they want */ asked = FAQ .map(function (f, i) { return { s: score({ label: f.question, keys: f.keys }, words), i: i, f: f }; }) .filter(function (h) { return h.s; }) .sort(function (a, b) { return b.s - a.s || a.i - b.i; }) .slice(0, FAQ_SHOWN) .map(function (h) { return h.f; }); } } /* the heading of whichever level is open, so nobody loses their place */ var here = menuAt ? faqById(menuAt) : null; hint.textContent = term ? (asked.length ? 'Press a question, or a page' : found + (found === 1 ? ' match' : ' matches')) : (asked.length ? (here ? here.question : 'What can I help you with?') : 'Everything on this website. Type to narrow it.'); results.innerHTML = ''; /* the way back up, when a heading is open and nothing has been typed */ if (mode() === 'search' && menuAt && !term) { var up = faqById(menuAt); var liUp = document.createElement('li'); var bUp = document.createElement('button'); bUp.type = 'button'; bUp.className = 'nchat__faqrow nchat__faqrow--up'; bUp.setAttribute('data-faqup', ''); bUp.appendChild(document.createTextNode('← ' + (up && up.parent ? 'Back' : 'All topics'))); bUp.addEventListener('click', function () { menuAt = up ? (up.parent || null) : null; render(''); }); liUp.appendChild(bUp); results.appendChild(liUp); } asked.forEach(function (f) { var kids = kidsOf(f.id); var li = document.createElement('li'); var b = document.createElement('button'); b.type = 'button'; b.className = 'nchat__faqrow' + (kids.length ? ' nchat__faqrow--more' : ''); b.setAttribute('data-faqrow', String(f.id)); var k = document.createElement('span'); k.className = 'nchat__kind'; /* a heading says how many are under it; an answer says it is one */ k.textContent = kids.length ? 'Topic' : 'Question'; b.appendChild(k); b.appendChild(document.createTextNode(f.question)); if (kids.length) { var arrow = document.createElement('em'); arrow.className = 'nchat__faqmore'; arrow.textContent = '›'; b.appendChild(arrow); } b.addEventListener('click', function () { /* a heading opens; anything else answers */ if (kids.length && !f.answer) { menuAt = f.id; input.value = ''; render(''); return; } answer(f); }); li.appendChild(b); results.appendChild(li); }); /* ── AND THE WAY THROUGH TO NEU ITSELF ── * One control, clearly separate from the answers above it, for the * question nobody wrote down. It is a BUTTON, not a link: this is the only * thing in the public box that spends any of the company's money, and that * ought to take a deliberate press rather than a stray Return. * It appears only when the server says NEU may actually answer — the * switch is on, there is a key, and the month has budget left. */ if (askSlot) { askSlot.innerHTML = ''; askSlot.hidden = !(canAsk && mode() === 'search'); if (!askSlot.hidden) { var b0 = document.createElement('button'); b0.type = 'button'; b0.className = 'nchat__askrow'; b0.setAttribute('data-askrow', ''); var k0 = document.createElement('span'); k0.className = 'nchat__kind'; k0.textContent = 'Ask NEU'; b0.appendChild(k0); b0.appendChild(document.createTextNode(term ? '“' + String(q).trim() + '”' : 'Ask me something in your own words')); b0.addEventListener('click', function () { /* Both ways in go through the same question. Pressing this row with something typed asks that question; pressing it with an empty box opens the conversation ready for one — and either way NEU has to know who it is talking to first. */ if (term) askAsVisitor(String(q).trim()); else withConsent(function () { goChat(); input.focus(); }); }); askSlot.appendChild(b0); } } /* ── THE MENU IS THE MENU ── * With nothing typed, the whole of the site's page list underneath four * topics is a hundred and twenty rows to scroll past, which is the wall of * text the menu exists to avoid. The pages arrive the moment somebody * types, because typing is what searching looks like. */ if (!term && asked.length) return; if (!hits.length) { var none = document.createElement('li'); none.className = 'nchat__none'; none.textContent = canAsk ? 'No page matches “' + q + '” — but I can try to answer it.' : 'Nothing matches “' + q + '”.'; results.appendChild(none); return; } hits.forEach(function (i) { var li = document.createElement('li'); var a = document.createElement('a'); a.href = i.href; var k = document.createElement('span'); k.className = 'nchat__kind'; k.textContent = i.kind; a.appendChild(k); a.appendChild(document.createTextNode(i.label)); /* WHERE DOES THIS RESULT ACTUALLY GO? * * The old test was "does the href start with #", and if so it scrolled to * that id on whatever page you happened to be on. NEU is on every page, * so on a chapter page the ten front-page sections found no such id, and * the whole press amounted to closing the box. Nothing was broken, and * nothing happened — which is worse, because there is nothing to report. * * Now the link is resolved against the current address and the question * asked properly: same page, or another one? Only a place on THIS page is * intercepted. Everything else is left to the browser, which knows how to * follow a link. */ a.addEventListener('click', function (e) { var url; try { url = new URL(a.href, location.href); } catch (err) { return; } if (url.pathname !== location.pathname) return; // another page: let it go e.preventDefault(); show(false); var t = url.hash ? document.querySelector(url.hash) : null; if (t) { t.scrollIntoView({ behavior: 'smooth' }); /* window.history — `history` in this file is NEU's conversation */ window.history.replaceState(null, '', url.hash); } else { /* already here, and there is no such place on it: go to the top rather than reload the page under the reader */ window.scrollTo({ top: 0, behavior: 'smooth' }); } }); li.appendChild(a); results.appendChild(li); }); } /* ================= ASK ================= */ /* THE BOX SHOWS PLAIN TEXT, so anything the model writes as markdown arrives as punctuation. It was answering with "**Sovereign Applied AI**" and a visitor read four asterisks. The system prompt now asks for plain sentences; this is the second half of that, because a model is asked and not made to. Only the emphasis marks are touched — nothing that could be part of a real sentence. */ function plain(text) { return String(text == null ? '' : text) .replace(/\*\*([^*]+)\*\*/g, '$1') // **bold** .replace(/(^|\s)\*([^*\n]+)\*(?=\s|[.,!?;:)]|$)/g, '$1$2') // *italic* .replace(/(^|\n)\s*[*-]\s+/g, '$1• ') // - bullet -> • bullet .replace(/(^|\n)#{1,6}\s+/g, '$1'); // ## heading } function add(who, text) { var p = document.createElement('p'); p.className = 'nchat__msg is-' + who; p.textContent = who === 'neu' ? plain(text) : text; log.appendChild(p); log.scrollTop = log.scrollHeight; return p; } function seeds(list) { var box = document.createElement('div'); box.className = 'nchat__seeds'; list.forEach(function (t) { var b = document.createElement('button'); b.type = 'button'; b.textContent = t; /* a seed can be a command as easily as a question — same road in, or "/make deck …" would be sent to the model as something to answer */ b.addEventListener('click', function () { box.remove(); send(t); }); box.appendChild(b); }); log.appendChild(box); } /* Documents from the chest, under the answer. Cards rather than a sentence, because the model can get the sentence wrong and the list cannot. The link goes to the Backstage route, which still wants a login — knowing a phrase gets you the NAME of a document, never the document. */ function files(list) { var box = document.createElement('div'); box.className = 'nchat__files'; list.forEach(function (f) { var a = document.createElement('a'); a.className = 'nchat__file'; a.href = '/admin/chest/file/' + f.id; a.target = '_blank'; a.rel = 'noopener'; var b = document.createElement('b'); b.textContent = f.label; a.appendChild(b); if (f.where) { var em = document.createElement('em'); em.textContent = '… ' + f.where + ' …'; a.appendChild(em); } var meta = document.createElement('span'); meta.textContent = f.original + ' · level ' + f.clearance; a.appendChild(meta); box.appendChild(a); }); var note = document.createElement('p'); note.className = 'nchat__filenote'; note.textContent = 'Opening one needs a Backstage sign-in.'; box.appendChild(note); log.appendChild(box); log.scrollTop = log.scrollHeight; } /* A finished document, offered two ways: opened in a tab so it can be read and printed to PDF, or downloaded as plain text so it can be edited. */ function docCard(j) { var box = document.createElement('div'); box.className = 'nchat__files'; var a = document.createElement('a'); a.className = 'nchat__file'; a.href = '/api/neu/doc/' + j.id; a.target = '_blank'; a.rel = 'noopener'; var b = document.createElement('b'); b.textContent = j.title; a.appendChild(b); var em = document.createElement('em'); em.textContent = j.kindName + ' · ' + j.parts + ' ' + j.what; a.appendChild(em); var span = document.createElement('span'); span.textContent = 'Open it — then Print → Save as PDF'; a.appendChild(span); box.appendChild(a); var txt = document.createElement('a'); txt.className = 'nchat__file'; txt.href = '/api/neu/doc/' + j.id + '?t=md'; var tb = document.createElement('b'); tb.textContent = 'Download as plain text'; txt.appendChild(tb); var ts = document.createElement('span'); ts.textContent = 'to edit it yourself'; txt.appendChild(ts); box.appendChild(txt); var note = document.createElement('p'); note.className = 'nchat__filenote'; note.textContent = 'Also in Backstage → Studio. Read it before you send it.'; box.appendChild(note); log.appendChild(box); log.scrollTop = log.scrollHeight; } async function makeDoc(kind, brief) { if (busy) return; busy = true; add('you', '/make ' + kind + ' ' + brief); var wait = add('neu', ''); wait.className = 'nchat__msg is-neu is-waiting'; wait.innerHTML = ''; input.value = ''; try { var r = await fetch('/api/neu/make', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ kind: kind, brief: brief }), }); var j = await r.json(); wait.className = 'nchat__msg is-neu'; if (!j.ok) { wait.textContent = j.why || 'I could not make that one.'; } else { wait.textContent = 'Here is your ' + j.kindName.toLowerCase() + ' — ' + j.parts + ' ' + j.what + '. I wrote it from what NEUON has published, so check it before it leaves the building.'; docCard(j); } } catch (e) { wait.className = 'nchat__msg is-neu'; wait.textContent = 'I could not reach my brain just then. Try once more?'; } busy = false; log.scrollTop = log.scrollHeight; } /* The one road in for anything typed or pressed in ask mode. A command has to be recognised HERE and not at the form, or a seed button carrying one sends it to the model as a question — which costs money and answers nothing. */ function send(text) { var m = MAKE.exec(text || ''); if (m) { makeDoc(m[1].toLowerCase(), m[2].trim()); return; } ask(text); } /* ── AN ANSWER THAT WAS WRITTEN, NOT GENERATED ── * No request, no model, no wait, no bill — the words came down with the page * and go straight into the conversation. This is the path most visitors will * take, and it is the one that costs the company nothing however busy the * site gets. * * Every part is built as a text node or an element. The answer is somebody's * typing from a Backstage box, so it is never handed to innerHTML — the same * rule the story popup follows. */ /* ── WHERE THIS ANSWER COMES FROM ─────────────────────────────────────── * * Taufik, 23 August 2026: "for faq, make it able to see at where is the * answer come from." * * The same rule Dr KC asked for on the pages, applied to the one part of * the site that talks back. An answer a stranger is reading in a chat box * looks exactly as authoritative whether somebody checked it last week or * typed it from memory two years ago, and this is what tells them which. * * A folding block rather than a line of text, for the same reason the * pages' marks fold: most readers want the answer, and the one reader in * twenty who wants to check it wants the address in full. * * It prints NOTHING when there is nothing behind it. A "sources" line under * an answer that has none is what teaches everybody to stop reading them. */ function whereFrom(f) { var cites = f.cites || []; if (!f.from && !cites.length) return; var wrap = document.createElement('details'); wrap.className = 'nchat__from'; var head = document.createElement('summary'); head.textContent = '🔖 Where this comes from'; wrap.appendChild(head); var body = document.createElement('div'); body.className = 'nchat__fromin'; /* a DRAWN answer names the place it was drawn from, and that place is on this site, so it is a link rather than an address to copy out */ if (f.from) { var p = document.createElement('p'); p.appendChild(document.createTextNode('Read from ')); if (f.from.at) { var a = document.createElement('a'); a.href = f.from.at; a.textContent = f.from.label; p.appendChild(a); } else { p.appendChild(document.createTextNode(f.from.label)); } /* the tail sentence belongs to the SOURCE, not to this function: the certificates are a list of rows and a pillar is part of a page, and one sentence describing both was wrong about one of them */ if (f.from.tail) p.appendChild(document.createTextNode(' ' + f.from.tail)); body.appendChild(p); } cites.forEach(function (c) { var p = document.createElement('p'); p.appendChild(document.createTextNode((c.mark || '') + ' ')); if (c.note) p.appendChild(document.createTextNode(c.note + ' ')); if (c.at) { var a = document.createElement('a'); a.href = c.at; a.textContent = c.at; if (c.at.charAt(0) !== '/') { a.target = '_blank'; a.rel = 'noopener noreferrer'; } p.appendChild(a); } body.appendChild(p); }); wrap.appendChild(body); log.appendChild(wrap); } function answer(f) { goChat(); add('you', f.question); String(f.answer || '').split('\n').forEach(function (para) { if (para.trim()) add('neu', para.trim()); }); whereFrom(f); if (f.go) { var box = document.createElement('div'); box.className = 'nchat__seeds'; var a = document.createElement('a'); a.className = 'nchat__more'; a.href = f.go; a.textContent = f.cta || 'Read more →'; /* somewhere else on this site opens here; anywhere else opens away */ if (!/^\/(?!\/)/.test(f.go)) { a.target = '_blank'; a.rel = 'noopener noreferrer'; } box.appendChild(a); log.appendChild(box); } /* the next step down, if this question has one — a topic may carry both an answer and the questions underneath it */ var deeper = kidsOf(f.id); if (deeper.length) { var more = document.createElement('div'); more.className = 'nchat__seeds'; deeper.slice(0, 4).forEach(function (kid) { var b = document.createElement('button'); b.type = 'button'; b.textContent = kid.question; b.addEventListener('click', function () { more.remove(); answer(kid); }); more.appendChild(b); }); log.appendChild(more); } /* the next thing to do, offered rather than assumed */ var next = document.createElement('div'); next.className = 'nchat__seeds'; var back = document.createElement('button'); back.type = 'button'; back.textContent = '← Other questions'; back.addEventListener('click', function () { history = []; log.innerHTML = ''; goSearch(); }); next.appendChild(back); if (canAsk) { var mine = document.createElement('button'); mine.type = 'button'; mine.textContent = 'Ask something in my own words'; mine.addEventListener('click', function () { next.remove(); goChat(); input.focus(); }); next.appendChild(mine); } log.appendChild(next); log.scrollTop = log.scrollHeight; } /* ═══════════════ THE GATE — Dr KC's flow ═══════════════ * When the free questions run out and there is a way to carry on, NEU asks * who it is talking to rather than simply stopping. Three steps, each one * inside the conversation so nobody has to leave the page and lose what they * were reading. * * Nothing here is a form on a page. It is NEU asking, and the person * answering — which is the whole reason it works better than a pop-up. */ /* THE WORK. A challenge from the server, and the browser must find a number whose hash starts with enough zeros. A person waits a fraction of a second and sees nothing; a script pays that fraction EVERY attempt, which is what stops one machine posting a thousand addresses. No third-party CAPTCHA: nothing about a visitor leaves this site. */ /* SHA-256, written out, because the browser's own one is the wrong shape for this. crypto.subtle.digest returns a promise, so a search doing a quarter of a million of them awaits a quarter of a million times: measured at about ELEVEN THOUSAND a second, which turns this into a six-second freeze. The same loop with a synchronous hash runs fifty times faster, so the work can stay meaningful — a script has to pay it too — while a person waits less than a second. Verified against the server's own hashes below. */ var K256 = [ 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]; function sha256Bytes(bytes) { var h = [0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]; var len = bytes.length; var withPad = (((len + 8) >> 6) + 1) << 4; // 32-bit words, padded var w = new Int32Array(withPad); for (var i = 0; i < len; i++) w[i >> 2] |= bytes[i] << ((3 - (i & 3)) << 3); w[len >> 2] |= 0x80 << ((3 - (len & 3)) << 3); w[withPad - 1] = len << 3; var blk = new Int32Array(64); for (var off = 0; off < withPad; off += 16) { for (var t = 0; t < 16; t++) blk[t] = w[off + t]; for (t = 16; t < 64; t++) { var x = blk[t - 15], y = blk[t - 2]; var s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3); var s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10); blk[t] = (blk[t - 16] + s0 + blk[t - 7] + s1) | 0; } var a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; for (t = 0; t < 64; t++) { var S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); var ch = (e & f) ^ (~e & g); var t1 = (hh + S1 + ch + K256[t] + blk[t]) | 0; var S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); var mj = (a & b) ^ (a & c) ^ (b & c); var t2 = (S0 + mj) | 0; hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } h[0] = (h[0] + a) | 0; h[1] = (h[1] + b) | 0; h[2] = (h[2] + c) | 0; h[3] = (h[3] + d) | 0; h[4] = (h[4] + e) | 0; h[5] = (h[5] + f) | 0; h[6] = (h[6] + g) | 0; h[7] = (h[7] + hh) | 0; } return h; } /* how many zero bits the hash starts with — the whole test */ function zerosOf(h) { var n = 0; for (var i = 0; i < 8; i++) { var v = h[i] >>> 0; if (v === 0) { n += 32; continue; } while ((v & 0x80000000) === 0) { n++; v = (v << 1) >>> 0; } break; } return n; } var ASCII = function (s) { var out = new Uint8Array(s.length); for (var i = 0; i < s.length; i++) out[i] = s.charCodeAt(i) & 0xff; return out; }; async function proveHuman(challenge, bits) { var t0 = Date.now(); for (var nonce = 0; nonce < 20000000; nonce++) { if (zerosOf(sha256Bytes(ASCII(challenge + ':' + nonce))) >= bits) return nonce; /* let the page breathe, so nothing ever looks frozen even on a slow phone */ if ((nonce & 0x3fff) === 0x3fff) { await new Promise(function (r) { setTimeout(r, 0); }); if (Date.now() - t0 > 30000) return null; } } return null; } /* One small form inside the conversation. Returns what was typed. */ function askFor(fields, submitSays, onSend) { var box = document.createElement('form'); box.className = 'nchat__gate'; var inputs = {}; fields.forEach(function (f) { var l = document.createElement('label'); l.textContent = f.label; var i = document.createElement('input'); i.type = f.type || 'text'; if (f.placeholder) i.placeholder = f.placeholder; if (f.maxlength) i.maxLength = f.maxlength; if (f.mode) i.inputMode = f.mode; if (f.required) i.required = true; if (f.autocomplete) i.autocomplete = f.autocomplete; inputs[f.name] = i; l.appendChild(i); box.appendChild(l); }); var note = document.createElement('p'); note.className = 'nchat__gatenote'; box.appendChild(note); var go = document.createElement('button'); go.type = 'submit'; go.className = 'nchat__gatego'; go.textContent = submitSays; box.appendChild(go); box.addEventListener('submit', function (e) { e.preventDefault(); var vals = {}; Object.keys(inputs).forEach(function (k) { vals[k] = inputs[k].value; }); go.disabled = true; var wasSaying = go.textContent; go.textContent = 'One moment…'; note.textContent = ''; onSend(vals, function (problem) { go.disabled = false; go.textContent = wasSaying; if (problem) { note.textContent = problem; inputs[fields[0].name].focus(); } }, box); }); log.appendChild(box); log.scrollTop = log.scrollHeight; setTimeout(function () { inputs[fields[0].name].focus(); }, 60); return box; } /* STEP ONE — where to reach you. */ function askForEmail() { askFor( [{ name: 'email', label: 'Your email', type: 'email', mode: 'email', placeholder: 'you@company.com', required: true, autocomplete: 'email', maxlength: 200 }], 'Send me a code', async function (v, done, box) { try { var ch = await fetch('/api/neu/challenge').then(function (r) { return r.json(); }); var nonce = await proveHuman(ch.challenge, ch.bits); var r = await fetch('/api/neu/gate', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: v.email, challenge: ch.challenge, nonce: nonce, page: location.pathname }), }); var j = await r.json(); if (!j.ok) return done(j.why || 'That did not work. Try once more.'); box.remove(); if (j.already) { add('neu', 'We have met — carry on.'); return dress(); } add('neu', 'Sent. Look for a six-digit code from NEUON AI — it is good for ten minutes. ' + 'If it is not in your inbox, look in the spam folder.'); askForCode(); } catch (e) { done('I could not reach the server just then. Try once more.'); } } ); } /* STEP TWO — the code. */ function askForCode() { askFor( [{ name: 'code', label: 'The six-digit code', mode: 'numeric', placeholder: '000000', required: true, maxlength: 6, autocomplete: 'one-time-code' }], 'That is it', async function (v, done, box) { try { var j = await fetch('/api/neu/verify', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: v.code }), }).then(function (r) { return r.json(); }); if (!j.ok) return done(j.why || 'That is not the code.'); box.remove(); add('neu', 'Thank you — that is you. Ask me anything you like now.'); askWhatFor(); dress(); } catch (e) { done('I could not reach the server just then. Try once more.'); } } ); } /* STEP THREE — what they came for. Skippable ON PURPOSE: they have already proved an address, and the conversation is already open. Demanding a form at this point would lose the person who was about to tell us something useful anyway. */ function askWhatFor() { var box = askFor( [{ name: 'name', label: 'Your name', maxlength: 120, autocomplete: 'name' }, { name: 'org', label: 'Organisation', maxlength: 160, autocomplete: 'organization' }, { name: 'want', label: 'What brings you to NEUON AI?', placeholder: 'a project, a partnership, a job, curiosity…', maxlength: 400 }], 'Send it', async function (v, done, b) { try { await fetch('/api/neu/interest', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: v.name, org: v.org, want: v.want, page: location.pathname }), }); b.remove(); add('neu', 'Got it — somebody at NEUON will see that. Carry on asking me things in the meantime.'); } catch (e) { done('I could not send that. Try once more.'); } } ); var skip = document.createElement('button'); skip.type = 'button'; skip.className = 'nchat__gateskip'; skip.textContent = 'Not now'; skip.addEventListener('click', function () { box.remove(); }); box.appendChild(skip); } /* ═══════════ WHO AM I TALKING TO, AND MAY I KEEP A NOTE? ═══════════ * * Pressing a prepared question asks nothing of anybody: no name, no tick, * no record, and no request to the server at all. That is the path most * people take and it should stay free. * * Typing your own words is a conversation, and NEUON keeps conversations. * So NEU asks first, in its own voice rather than in the voice of a privacy * policy, and does not start until there is a name AND a tick. It is one * step, before the first word — not a notice under a box somebody has * already typed into, which is the version that is worth nothing. * * Staff who have unlocked the assistant with a phrase are not asked: they * are already identified, and this is a record of visitors. */ var talkName = null; function askToBegin(then) { var box = document.createElement('form'); box.className = 'nchat__gate nchat__hello'; var hi = document.createElement('p'); hi.className = 'nchat__hellosay'; hi.textContent = 'Hi — NEU here. Before we start: what should I call you? ' + 'I keep a note of our conversation so I can be more use to ' + 'you now, and better at this next time.'; box.appendChild(hi); var l = document.createElement('label'); l.textContent = 'Your name'; var who = document.createElement('input'); who.type = 'text'; who.maxLength = 80; who.required = true; who.autocomplete = 'name'; who.placeholder = 'What shall I call you?'; l.appendChild(who); box.appendChild(l); var tickWrap = document.createElement('label'); tickWrap.className = 'nchat__tick'; var tick = document.createElement('input'); tick.type = 'checkbox'; tickWrap.appendChild(tick); var tickSay = document.createElement('span'); tickSay.textContent = 'Yes — keep a note of what we say. NEUON AI may use it ' + 'to answer better and to improve NEU. You can download ' + 'the whole conversation at any point.'; tickWrap.appendChild(tickSay); box.appendChild(tickWrap); var note = document.createElement('p'); note.className = 'nchat__gatenote'; box.appendChild(note); var go = document.createElement('button'); go.type = 'submit'; go.className = 'nchat__gatego'; go.textContent = 'Start talking to NEU'; box.appendChild(go); /* the way out. Somebody who does not want to be recorded is not somebody to argue with — the prepared questions are still there and still free */ var no = document.createElement('button'); no.type = 'button'; no.className = 'nchat__gateskip'; no.textContent = 'No thanks — just show me the questions'; no.addEventListener('click', function () { box.remove(); goSearch(); }); box.appendChild(no); box.addEventListener('submit', async function (e) { e.preventDefault(); if (!who.value.trim()) { note.textContent = 'Tell me what to call you first.'; who.focus(); return; } if (!tick.checked) { note.textContent = 'I need the tick before I can start taking notes.'; tick.focus(); return; } go.disabled = true; var was = go.textContent; go.textContent = 'One moment…'; try { var j = await fetch('/api/neu/hello', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: who.value, consent: true, page: location.pathname }), }).then(function (r) { return r.json(); }); if (!j.ok) { go.disabled = false; go.textContent = was; note.textContent = j.why || 'That did not work. Try once more.'; return; } talkName = j.name; box.remove(); add('neu', 'Thank you, ' + talkName + '. Ask me anything you like — ' + 'and when we are done you can save the whole thing as a PDF.'); if (then) then(); } catch (err) { go.disabled = false; go.textContent = was; note.textContent = 'I could not reach the server just then. Try once more.'; } }); log.appendChild(box); log.scrollTop = log.scrollHeight; setTimeout(function () { who.focus(); }, 60); return box; } /* Everything that starts a free-text conversation comes through here, so there is exactly one place the question gets asked. */ function withConsent(then) { if (mode() === 'ask' || talkName) { then(); return; } goChat(); askToBegin(then); } /* THE FILE. Offered once there is something in it, and again at the foot of every answer would be nagging — so it is a single row that moves down as the conversation grows. */ var saveRow = null; function offerSave() { if (saveRow) saveRow.remove(); saveRow = document.createElement('div'); saveRow.className = 'nchat__seeds nchat__save'; var a = document.createElement('a'); a.className = 'nchat__more'; a.href = '/api/neu/mychat.pdf'; a.setAttribute('download', ''); a.textContent = '⤓ Save our conversation (PDF)'; saveRow.appendChild(a); log.appendChild(saveRow); log.scrollTop = log.scrollHeight; } /* A visitor asking. The panel turns into the conversation and the way back appears; /make is deliberately not reachable from here, so a stranger cannot commission a document. */ function askAsVisitor(text) { if (!text || busy) return; withConsent(function () { goChat(); ask(text); }); } async function ask(q, proof, reuse) { if ((busy && !proof) || !q.trim()) return; busy = true; var s = log.querySelector('.nchat__seeds'); if (s) s.remove(); /* on a retry the question is already on screen and the dots are already spinning — do not say it twice */ var wait = reuse; if (!wait) { add('you', q); history.push({ role: 'user', content: q }); input.value = ''; wait = add('neu', ''); wait.className = 'nchat__msg is-neu is-waiting'; wait.innerHTML = ''; } try { var r = await fetch('/api/neu/ask', { method: 'POST', headers: { 'content-type': 'application/json' }, /* the page the question is asked on: "email" on /careers is an applicant's question */ body: JSON.stringify({ q: q, history: history.slice(0, -1), proof: proof || undefined, page: location.pathname }), }); var j = await r.json(); /* ── EVERY SO OFTEN, PROVE THERE IS A PERSON HERE ── * Not a puzzle and not a refusal. The server asks for a small sum, the * page does it, and the same question goes again by itself. A visitor * sees one line and a short pause; a script pays this over and over, * which is the entire point. */ if (j.needWork) { if (proof) { // already tried once — do not loop wait.className = 'nchat__msg is-neu'; wait.textContent = 'I could not finish checking just then. Ask me again?'; busy = false; return; } var note = add('note', 'Just checking there is a person here…'); var nonce = await proveHuman(j.challenge, j.bits); note.remove(); if (nonce === null) { wait.className = 'nchat__msg is-neu'; wait.textContent = 'That check did not finish on this device. Try once more?'; busy = false; return; } if (j.offerGate) askedToProveOnce = true; return ask(q, { challenge: j.challenge, nonce: nonce }, wait); } wait.className = 'nchat__msg is-neu'; /* THIS is the bubble the model's own words land in — the one that showed "**Sovereign Applied AI**" — so it takes the same cleaning as `add`. The HISTORY keeps the original: what the model said is what should go back to it next turn, not the tidied version shown on screen. */ wait.textContent = plain(j.text || 'I could not answer that one.'); history.push({ role: 'assistant', content: j.text || '' }); /* ── AND SOMEWHERE TO GO ── * "Who is the CEO?" ends with a way to the board, the same as a written * answer does. The address is chosen BY THE SERVER from the list of real * places on this site — the model is never asked for a link, because a * language model will eventually invent a beautiful one that 404s. */ if (j.go) { var box2 = document.createElement('div'); box2.className = 'nchat__seeds'; var a2 = document.createElement('a'); a2.className = 'nchat__more'; a2.href = j.go; a2.textContent = j.cta || 'Read more →'; if (!/^\/(?!\/)/.test(j.go)) { a2.target = '_blank'; a2.rel = 'noopener noreferrer'; } box2.appendChild(a2); log.appendChild(box2); } if (j.files && j.files.length) files(j.files); /* something was written down, so there is something to take away */ if (j.noted) offerSave(); if (typeof j.left === 'number' && j.left <= 3 && j.left > 0) { add('note', j.left + (j.left === 1 ? ' question left' : ' questions left') + ' this hour.'); } /* Mentioned ONCE, after an answer rather than instead of one: there is a way to be interrupted far less often. Nobody is made to take it. */ if (askedToProveOnce) { askedToProveOnce = false; var offer = document.createElement('div'); offer.className = 'nchat__seeds'; var b = document.createElement('button'); b.type = 'button'; b.textContent = 'Tell NEU who you are, and be asked less often'; b.addEventListener('click', function () { offer.remove(); askForEmail(); }); offer.appendChild(b); log.appendChild(offer); } /* THE DIAMOND IN THE DRAWING. Out of free questions, and there is a way to carry on — so ask who this is, inside the conversation, instead of closing the door on somebody who was in the middle of something. */ if (j.gate) { askForEmail(); busy = false; return; } /* The server may say it is only a search box now — the switch is off, the month's budget is gone, or this visitor has had their allowance. Believe it, and stop offering an answer that will be refused. */ if (j.mode === 'search' || j.done) { if (mode() === 'ask' && j.done) form.hidden = true; // staff, out of turns else { canAsk = false; dress(); } // visitor, back to searching } } catch (err) { wait.className = 'nchat__msg is-neu'; wait.textContent = 'I could not reach my brain just then. Try once more?'; } busy = false; log.scrollTop = log.scrollHeight; } /* ================= the one input ================= */ input.addEventListener('input', function () { if (!asking()) render(input.value); }); form.addEventListener('submit', function (e) { e.preventDefault(); var v = input.value; /* The door. Checked before anything else, so it works in either mode and never reaches the model as a question. */ if (COMMAND.test(v)) { input.value = ''; if (!asking()) render(''); openLock(); return; } /* Reading a written answer is not being in a conversation. If NEU is not allowed to answer — the switch is off, or the month is spent — then typing here goes back to looking things up rather than to a refusal. */ if (asking() && mode() === 'search' && !canAsk) { history = []; log.innerHTML = ''; view = 'search'; dress(); render(v); return; } if (asking()) { /* a visitor typing their own words, before agreeing to a note being kept — the same question is asked here as on the Ask NEU row, because both are the same thing arrived at two ways */ if (mode() !== 'ask' && !talkName) { var pending = v; input.value = ''; withConsent(function () { send(pending); }); return; } send(v); return; } /* Search: Return goes to the best matching PAGE when there is one, the way the old box did — and that ordering is the point. Pressing Return must never spend money by accident, so asking is what happens only when nothing on the site matches at all. The Ask NEU row is always there for somebody who means it. */ var first = results.querySelector('a'); if (first) { first.click(); return; } if (canAsk && v.trim()) askAsVisitor(v.trim()); }); if (backBtn) { backBtn.addEventListener('click', function () { history = []; log.innerHTML = ''; goSearch(); }); } /* ================= the tier dialog ================= */ function openLock() { if (!lock) return; var no = $('[data-nlockno]'); if (no) no.hidden = true; var w = $('[data-nlockword]'); if (w) w.value = ''; lock.hidden = false; setTimeout(function () { if (w) w.focus(); }, 30); } if (lock) { $$('[data-nlockclose]', lock).forEach(function (b) { b.addEventListener('click', function () { lock.hidden = true; }); }); $('[data-nlockform]').addEventListener('submit', async function (e) { e.preventDefault(); var no = $('[data-nlockno]'); no.hidden = true; try { var r = await fetch('/api/neu/unlock', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ word: $('[data-nlockword]').value }), }); var j = await r.json(); if (!j.ok) { no.textContent = j.why || 'That is not one of the phrases.'; no.hidden = false; return; } /* No reload. The panel is already on the page — it was only ever a search box — so switching tier is a change of clothes, not a new document. That also keeps whatever was being read behind it. */ tier = j.tier; lock.hidden = true; history = []; log.innerHTML = ''; dress(); show(true); add('neu', 'Hello. You are signed in as ' + j.name + '. Ask me about NEUON AI' + (j.chest ? ', or for a document in the chest.' : '.') + '\n\nI can also write you one. Type /make and one of: deck, proposal, storyboard, note — ' + 'then what it is about.'); seeds(j.chest ? ['What does NEUON AI actually do?', 'Find the JKR agreement', '/make deck a pitch for JKR about RoadPlus'] : ['What does NEUON AI actually do?', 'What is RoadPlus?', '/make deck a pitch for JKR about RoadPlus']); } catch (err) { no.hidden = false; } }); } /* Leaving a tier is not closing the box. Closing hides the panel and NEU is still signed in for this browser; leaving hands the phrase back, so the next person to pick up the laptop has to know it again. */ if (lockBtn) { lockBtn.addEventListener('click', async function () { lockBtn.disabled = true; try { await fetch('/api/neu/close', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' }); } catch (e) { /* going back to search either way */ } lockBtn.disabled = false; tier = 'public'; view = 'search'; history = []; log.innerHTML = ''; input.value = ''; dress(); render(''); }); } /* ================= start ================= */ dress(); render(''); })();