feat(chat): a chat view in the console, over the engagement's own records

Backend: conversations persist under .neurosploit/chats, /api/chat/:id/send
drives `neurosploit chat` and relays its JSON lines over SSE. The first
message names the conversation, because a list of "New conversation" stops
being usable at about two.

Frontend: conversation list, message stream, model picker over the providers
that actually have a key, and an @ picker.

The @ picker is the point. It offers runs, targets and a findings search, and
those resolve server-side out of runs/ before the model sees anything — so an
answer quotes a finding that exists rather than describing the class of thing
it might be. Verified: asked how many findings a run had and at what severity,
it answered "2 findings, both Low", which is what that run holds.

What the resolver could NOT resolve is rendered in the answer's footer. A
reference that silently vanishes reads as the model not knowing, when it was
never told — and that is the failure an operator would misread as the target
being clean.

Answers render through a small markdown pass that escapes first, so a
finding's evidence cannot inject markup into the console.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Joas A SantosandClaude Opus 5 committed 2026-12-04 14:44:30 -03:00
1 parent 6cf9ffd5ed
commit 0076e8715e
4 files changed
+538 -1

No files matched your search

+320 -1
View File
@@ -156,7 +156,7 @@ function clearFieldErrors() { $$('.field-error').forEach((el) => { el.textConten
// view navigation
// ---------------------------------------------------------------------------
const ALL_VIEWS = ['homeView','dashView','wizardView','liveView','detailView','pentestsView','prreviewsView','issuesView','reposView','projectsView','domainsView','networksView','vaultView','guardrailsView','integrationsView','settingsView','c2View','phishView','mcpView','toolboxView'];
const ALL_VIEWS = ['homeView','dashView','wizardView','liveView','detailView','pentestsView','prreviewsView','issuesView','reposView','projectsView','domainsView','networksView','vaultView','guardrailsView','integrationsView','settingsView','c2View','phishView','mcpView','toolboxView','chatView'];
function switchView(viewName) {
state.activeView = viewName;
@@ -181,6 +181,7 @@ function switchView(viewName) {
if (viewName === 'integrations') loadIntegrations();
if (viewName === 'settings') loadSettings();
if (viewName === 'prreviews') loadPrReviews();
if (viewName === 'chat') loadChat();
if (viewName === 'vault') loadVault();
if (viewName === 'guardrails') loadGuardrails();
if (viewName === 'c2') loadC2();
@@ -10676,3 +10677,321 @@ $('#btnC2TaskRun')?.addEventListener('click', async () => {
if (out) out.textContent = `error: ${e.message}`;
}
});
// ---------------------------------------------------------------------------
// Chat — ask about the engagement, answered from its own runs and findings.
//
// The value over a general assistant is the `@` references: they resolve
// server-side out of runs/ before the model sees anything, so an answer can
// quote a finding that exists instead of describing the class of thing it
// might be. The resolver reports what it could NOT resolve, and that is shown,
// because a reference that silently vanishes reads as the model not knowing.
// ---------------------------------------------------------------------------
const chat = { id: null, list: [], refs: [], streaming: false, picker: null };
async function loadChat() {
try {
chat.list = await api('/api/chat');
} catch { chat.list = []; }
renderChatList();
await loadChatModels();
if (!chat.id && chat.list.length) openChat(chat.list[0].id);
else if (!chat.list.length) renderChatStream(null);
}
async function loadChatModels() {
const sel = $('#chatModel');
if (!sel || sel.dataset.filled) return;
try {
const [providers, keys] = await Promise.all([
api('/api/providers').catch(() => []),
api('/api/keys').catch(() => []),
]);
const withKey = new Set(keys.filter((k) => k.set).map((k) => k.provider));
const opts = ['<option value="">Default model</option>'];
for (const p of providers) {
if (!withKey.has(p.key)) continue;
for (const m of (p.models || []).slice(0, 12)) {
opts.push(`<option value="${esc(p.key)}:${esc(m)}">${esc(p.label)} · ${esc(m)}</option>`);
}
}
sel.innerHTML = opts.join('');
sel.dataset.filled = '1';
} catch { /* the default model still works */ }
}
function renderChatList() {
const el = $('#chatList');
if (!el) return;
if (!chat.list.length) {
el.innerHTML = '<div class="chat-list-empty">No conversations yet.</div>';
return;
}
el.innerHTML = chat.list.map((c) => `
<button class="chat-item${c.id === chat.id ? ' active' : ''}" data-chat="${esc(c.id)}">
<span class="chat-item-title">${esc(c.title)}</span>
<span class="chat-item-meta">${c.turns} message(s) · ${esc(timeAgo(c.at / 1000))}</span>
<span class="chat-item-del" data-chat-del="${esc(c.id)}" title="Delete">×</span>
</button>`).join('');
$$('[data-chat]', el).forEach((b) => b.addEventListener('click', (e) => {
if (e.target.dataset.chatDel) return;
openChat(b.dataset.chat);
}));
$$('[data-chat-del]', el).forEach((x) => x.addEventListener('click', async (e) => {
e.stopPropagation();
try {
await api(`/api/chat/${encodeURIComponent(x.dataset.chatDel)}`, { method: 'DELETE' });
if (chat.id === x.dataset.chatDel) { chat.id = null; renderChatStream(null); }
await loadChat();
} catch (err) { toast(err.message, 'error'); }
}));
}
async function openChat(id) {
try {
const c = await api(`/api/chat/${encodeURIComponent(id)}`);
chat.id = c.id;
chat.refs = [];
renderChatRefs();
renderChatList();
renderChatStream(c);
const t = $('#chatTitle'); if (t) t.textContent = c.title || 'Chat';
if (c.model) { const sel = $('#chatModel'); if (sel) sel.value = c.model; }
} catch (e) { toast(e.message, 'error'); }
}
function renderChatStream(c) {
const el = $('#chatStream');
if (!el) return;
if (!c) {
el.innerHTML = `<div class="chat-empty">
<b>Ask about this engagement</b>
<p>Answers come from your own runs and findings, not from what a model remembers about a vulnerability class.</p>
<p class="chat-empty-hint">Type <code>@</code> to attach a run, a finding or a target.</p>
</div>`;
return;
}
el.innerHTML = (c.messages || []).map(chatBubble).join('');
el.scrollTop = el.scrollHeight;
}
function chatBubble(m) {
const who = m.role === 'assistant' ? 'assistant' : 'user';
return `<div class="chat-msg ${who}">
<div class="chat-msg-body">${mdLite(m.content || '')}</div>
</div>`;
}
/// Enough markdown for an answer to read properly, escaped first so a finding's
/// evidence cannot inject markup into the console.
function mdLite(text) {
let h = esc(text);
h = h.replace(/```([\s\S]*?)```/g, (_, code) => `<pre class="chat-code">${code.trim()}</pre>`);
h = h.replace(/`([^`\n]+)`/g, '<code>$1</code>');
h = h.replace(/\*\*([^*\n]+)\*\*/g, '<b>$1</b>');
h = h.replace(/^### (.+)$/gm, '<h4>$1</h4>');
h = h.replace(/^## (.+)$/gm, '<h3>$1</h3>');
h = h.replace(/\n/g, '<br>');
return h;
}
function renderChatRefs() {
const el = $('#chatRefs');
if (!el) return;
el.hidden = !chat.refs.length;
el.innerHTML = chat.refs.map((r, i) =>
`<span class="chat-ref">@${esc(r.kind)}:${esc(r.id)}<b data-ref-del="${i}">×</b></span>`).join('');
$$('[data-ref-del]', el).forEach((b) => b.addEventListener('click', () => {
chat.refs.splice(Number(b.dataset.refDel), 1);
renderChatRefs();
}));
}
$('#btnChatNew')?.addEventListener('click', async () => {
try {
const c = await api('/api/chat', { method: 'POST' });
await loadChat();
openChat(c.id);
} catch (e) { toast(e.message, 'error'); }
});
// ── @ reference picker ──────────────────────────────────────────────────────
async function chatPickerOpen(query) {
const el = $('#chatPicker');
if (!el) return;
const q = query.toLowerCase();
const runs = (state.runs || [])
.filter((r) => !q || (r.id || '').toLowerCase().includes(q) || (r.target || '').toLowerCase().includes(q))
.slice(0, 8)
.map((r) => ({ kind: 'run', id: r.id, label: `${r.target || r.id}`, meta: `${r.findings ?? 0} finding(s)` }));
const targets = [...new Set((state.runs || []).map((r) => r.target).filter(Boolean))]
.filter((t) => !q || t.toLowerCase().includes(q))
.slice(0, 5)
.map((t) => ({ kind: 'target', id: t, label: t, meta: 'all runs against this target' }));
const findings = q
? [{ kind: 'finding', id: query, label: `findings matching "${query}"`, meta: 'searches every run' }]
: [];
const items = [...findings, ...runs, ...targets];
if (!items.length) { el.hidden = true; return; }
el.hidden = false;
el.innerHTML = items.map((it, i) => `
<button class="chat-pick${i === 0 ? ' active' : ''}" data-pick="${i}">
<span class="chat-pick-kind">@${esc(it.kind)}</span>
<span class="chat-pick-label">${esc(it.label)}</span>
<span class="chat-pick-meta">${esc(it.meta)}</span>
</button>`).join('');
chat.picker = items;
$$('[data-pick]', el).forEach((b) => b.addEventListener('mousedown', (e) => {
e.preventDefault();
chatPickerChoose(Number(b.dataset.pick));
}));
}
function chatPickerChoose(i) {
const it = chat.picker?.[i];
if (!it) return;
chat.refs.push({ kind: it.kind, id: it.id });
renderChatRefs();
const box = $('#chatBox');
if (box) {
box.value = box.value.replace(/@[^\s@]*$/, '');
box.focus();
}
const el = $('#chatPicker');
if (el) el.hidden = true;
chat.picker = null;
}
$('#chatBox')?.addEventListener('input', (e) => {
const m = e.target.value.match(/@([^\s@]*)$/);
if (m) chatPickerOpen(m[1]);
else { const el = $('#chatPicker'); if (el) el.hidden = true; chat.picker = null; }
e.target.style.height = 'auto';
e.target.style.height = `${Math.min(e.target.scrollHeight, 200)}px`;
});
$('#chatBox')?.addEventListener('keydown', (e) => {
if (chat.picker && (e.key === 'Enter' || e.key === 'Tab')) {
e.preventDefault();
chatPickerChoose(0);
return;
}
if (e.key === 'Escape') { const el = $('#chatPicker'); if (el) el.hidden = true; chat.picker = null; return; }
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
$('#chatForm')?.requestSubmit();
}
});
$('#chatForm')?.addEventListener('submit', async (e) => {
e.preventDefault();
if (chat.streaming) return;
const box = $('#chatBox');
const message = (box?.value || '').trim();
if (!message) return;
if (!chat.id) {
try {
const c = await api('/api/chat', { method: 'POST' });
chat.id = c.id;
} catch (err) { return toast(err.message, 'error'); }
}
const stream = $('#chatStream');
const refs = chat.refs.slice();
box.value = '';
box.style.height = 'auto';
chat.refs = [];
renderChatRefs();
if (stream) {
if (stream.querySelector('.chat-empty')) stream.innerHTML = '';
stream.insertAdjacentHTML('beforeend', chatBubble({ role: 'user', content: message }));
stream.insertAdjacentHTML('beforeend',
'<div class="chat-msg assistant pending" id="chatPending"><div class="chat-msg-body"><i class="spin"></i> thinking…</div></div>');
stream.scrollTop = stream.scrollHeight;
}
chat.streaming = true;
const sendBtn = $('#btnChatSend'); if (sendBtn) sendBtn.disabled = true;
try {
const r = await fetch(`/api/chat/${encodeURIComponent(chat.id)}/send`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(getAuthToken() ? { Authorization: `Bearer ${getAuthToken()}` } : {}),
},
body: JSON.stringify({ message, refs, model: $('#chatModel')?.value || '' }),
});
if (!r.ok) throw new Error(`send failed (${r.status})`);
const reader = r.body.getReader();
const dec = new TextDecoder();
let buf = '';
let answer = '';
let notes = '';
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
let i;
while ((i = buf.indexOf('\n\n')) >= 0) {
const frame = buf.slice(0, i);
buf = buf.slice(i + 2);
const line = frame.split('\n').find((l) => l.startsWith('data: '));
if (!line) continue;
let ev;
try { ev = JSON.parse(line.slice(6)); } catch { continue; }
if (ev.type === 'context') {
const bits = [];
if (ev.resolved?.length) bits.push(`${ev.resolved.length} reference(s) attached`);
// A reference that did not resolve has to be visible: otherwise the
// answer reads as the model not knowing, rather than not being told.
if (ev.missing?.length) bits.push(`<b>could not resolve: ${esc(ev.missing.join(', '))}</b>`);
if (bits.length) notes = `<div class="chat-note">${bits.join(' · ')}</div>`;
} else if (ev.type === 'text') {
answer += ev.text;
} else if (ev.type === 'error') {
answer += `\n\n**Error:** ${ev.message}`;
} else if (ev.type === 'usage' && ev.usd) {
notes += `<div class="chat-note">$${Number(ev.usd).toFixed(4)} spent this engagement</div>`;
}
const pend = $('#chatPending');
if (pend && answer) pend.querySelector('.chat-msg-body').innerHTML = mdLite(answer);
if (stream) stream.scrollTop = stream.scrollHeight;
}
}
const pend = $('#chatPending');
if (pend) {
pend.removeAttribute('id');
pend.classList.remove('pending');
pend.querySelector('.chat-msg-body').innerHTML = mdLite(answer || '(no answer)') + notes;
}
chat.list = await api('/api/chat').catch(() => chat.list);
renderChatList();
} catch (err) {
const pend = $('#chatPending');
if (pend) {
pend.removeAttribute('id');
pend.classList.remove('pending');
pend.querySelector('.chat-msg-body').innerHTML = `<span class="chat-err">${esc(err.message)}</span>`;
}
} finally {
chat.streaming = false;
if (sendBtn) sendBtn.disabled = false;
}
});
+29
View File
@@ -61,6 +61,7 @@
<button class="sb-nav-item" data-view="pentests"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="7.5"/><path d="M12 2.5v4M12 17.5v4M2.5 12h4M17.5 12h4"/></svg></span> Pentests</button>
<button class="sb-nav-item" data-view="issues"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M5 21V4M5 4.5h12l-2.2 3.5L17 11.5H5"/></svg></span> Findings</button>
<button class="sb-nav-item" data-view="prreviews"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="6" cy="5.5" r="2"/><circle cx="6" cy="18.5" r="2"/><circle cx="18" cy="8" r="2"/><path d="M6 7.5v9M18 10c0 4-6 3-11 7"/></svg></span> PR reviews</button>
<button class="sb-nav-item" data-view="chat"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M21 11.5a8.4 8.4 0 0 1-9 8.4 8.9 8.9 0 0 1-3.8-.9L3 20.5l1.6-4.8A8.4 8.4 0 0 1 12 3.1a8.4 8.4 0 0 1 9 8.4Z"/></svg></span> Chat</button>
<div class="sb-section">Assets</div>
<button class="sb-nav-item" data-view="projects"><span class="sb-nav-icon"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M3.5 7.5A1.5 1.5 0 0 1 5 6h4l2 2h8a1.5 1.5 0 0 1 1.5 1.5v8A1.5 1.5 0 0 1 19 19H5a1.5 1.5 0 0 1-1.5-1.5z"/></svg></span> Projects</button>
@@ -171,6 +172,34 @@
</section>
<!-- ============ PR REVIEWS ============ -->
<!-- ============ CHAT ============ -->
<section class="page-view" id="chatView" hidden>
<div class="chat-shell">
<aside class="chat-side">
<button class="btn btn-primary chat-new" id="btnChatNew">+ New conversation</button>
<div class="chat-list" id="chatList"></div>
</aside>
<div class="chat-main">
<header class="chat-head">
<div>
<div class="chat-title" id="chatTitle">Chat</div>
<div class="chat-sub" id="chatSub">Ask about this engagement — answered from its own runs and findings</div>
</div>
<div class="chat-head-right">
<select id="chatModel" class="input-sm" title="Model"></select>
</div>
</header>
<div class="chat-stream" id="chatStream"></div>
<div class="chat-refs" id="chatRefs" hidden></div>
<form class="chat-input" id="chatForm" autocomplete="off">
<textarea id="chatBox" rows="1" placeholder="Ask a question — @ to reference a run, finding or target. Enter to send."></textarea>
<button class="btn btn-primary" type="submit" id="btnChatSend" title="Send">↑</button>
</form>
<div class="chat-picker" id="chatPicker" hidden></div>
</div>
</div>
</section>
<section class="page-view" id="prreviewsView" hidden>
<header class="topbar">
<div>
+62
View File
@@ -3227,3 +3227,65 @@ details.ag-sec > summary::-webkit-details-marker { display: none; }
.dash-sev-med .dash-val-big { color: var(--sev-medium-fg, #fefcbf); }
.dash-sev-low { border-color: var(--sev-low-bar, #38a169); }
.dash-sev-low .dash-val-big { color: var(--sev-low-fg, #9ae6b4); }
/* ── Chat ─────────────────────────────────────────────────────────────── */
.chat-shell { display: grid; grid-template-columns: 268px 1fr; height: 100%; min-height: 0; }
.chat-side { border-right: 1px solid var(--border); display: flex; flex-direction: column; min-height: 0; padding: 14px; gap: 12px; }
.chat-new { width: 100%; }
.chat-list { overflow-y: auto; display: flex; flex-direction: column; gap: 4px; min-height: 0; }
.chat-list-empty { color: var(--text-faint); font-size: var(--fs-sm); padding: 12px 4px; }
.chat-item { position: relative; text-align: left; background: none; border: 1px solid transparent; border-radius: 8px; padding: 9px 11px; cursor: pointer; display: flex; flex-direction: column; gap: 3px; color: var(--text); }
.chat-item:hover { background: var(--surface-2); }
.chat-item.active { background: var(--surface-2); border-color: var(--border); }
.chat-item-title { font-size: var(--fs-sm); font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chat-item-meta { font-size: 11px; color: var(--text-faint); }
.chat-item-del { position: absolute; right: 7px; top: 7px; opacity: 0; color: var(--text-faint); padding: 0 4px; border-radius: 4px; }
.chat-item:hover .chat-item-del { opacity: 1; }
.chat-item-del:hover { background: var(--surface-3, var(--surface)); color: var(--sev-critical-fg); }
.chat-main { display: flex; flex-direction: column; min-height: 0; }
.chat-head { display: flex; align-items: center; justify-content: space-between; gap: 14px; padding: 16px 22px; border-bottom: 1px solid var(--border); }
.chat-title { font-size: var(--fs-lg); font-weight: 650; }
.chat-sub { font-size: var(--fs-xs); color: var(--text-faint); margin-top: 2px; }
.chat-head-right select { max-width: 280px; }
.chat-stream { flex: 1; overflow-y: auto; padding: 22px; display: flex; flex-direction: column; gap: 16px; min-height: 0; }
.chat-empty { margin: auto; text-align: center; max-width: 420px; color: var(--text-dim); }
.chat-empty b { display: block; font-size: var(--fs-lg); color: var(--text); margin-bottom: 8px; }
.chat-empty p { font-size: var(--fs-sm); margin: 6px 0; }
.chat-empty-hint { color: var(--text-faint); }
.chat-msg { display: flex; max-width: 100%; }
.chat-msg.user { justify-content: flex-end; }
.chat-msg-body { border-radius: 12px; padding: 11px 15px; font-size: var(--fs-sm); line-height: 1.6; max-width: 76%; word-wrap: break-word; overflow-wrap: anywhere; }
.chat-msg.user .chat-msg-body { background: var(--accent, #7c5cff); color: #fff; }
.chat-msg.assistant .chat-msg-body { background: var(--surface-2); border: 1px solid var(--border); }
.chat-msg.pending .chat-msg-body { color: var(--text-faint); }
.chat-msg-body code { background: var(--surface-3, var(--surface)); padding: 1px 5px; border-radius: 4px; font-size: 12px; }
.chat-msg.user .chat-msg-body code { background: rgba(255,255,255,.18); }
.chat-code { background: var(--surface-3, var(--surface)); border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px; overflow-x: auto; font-size: 12px; margin: 8px 0; }
.chat-msg-body h3, .chat-msg-body h4 { margin: 10px 0 5px; font-size: var(--fs-sm); }
.chat-note { margin-top: 9px; padding-top: 8px; border-top: 1px solid var(--border); font-size: 11px; color: var(--text-faint); }
.chat-err { color: var(--sev-critical-fg); }
.chat-refs { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 22px 10px; }
.chat-ref { font-size: 11px; background: var(--surface-2); border: 1px solid var(--border); border-radius: 6px; padding: 3px 8px; color: var(--text-dim); }
.chat-ref b { margin-left: 6px; cursor: pointer; color: var(--text-faint); }
.chat-ref b:hover { color: var(--sev-critical-fg); }
.chat-input { display: flex; gap: 10px; align-items: flex-end; padding: 14px 22px 20px; border-top: 1px solid var(--border); }
.chat-input textarea { flex: 1; resize: none; min-height: 42px; max-height: 200px; padding: 11px 14px; border-radius: 10px; font-family: inherit; font-size: var(--fs-sm); line-height: 1.5; }
.chat-input .btn { height: 42px; width: 42px; padding: 0; font-size: 17px; }
.chat-picker { position: absolute; bottom: 86px; left: 290px; right: 40px; max-height: 260px; overflow-y: auto; background: var(--surface); border: 1px solid var(--border); border-radius: 10px; box-shadow: var(--shadow-float); z-index: 40; }
.chat-pick { display: flex; align-items: baseline; gap: 10px; width: 100%; text-align: left; background: none; border: 0; padding: 9px 13px; cursor: pointer; color: var(--text); font-size: var(--fs-sm); }
.chat-pick:hover, .chat-pick.active { background: var(--surface-2); }
.chat-pick-kind { font-size: 11px; color: var(--accent, #7c5cff); font-weight: 650; min-width: 62px; }
.chat-pick-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chat-pick-meta { font-size: 11px; color: var(--text-faint); }
@media (max-width: 900px) {
.chat-shell { grid-template-columns: 1fr; }
.chat-side { display: none; }
.chat-picker { left: 20px; }
}
+127
View File
@@ -168,6 +168,71 @@ const WEB_DIR = __dirname;
const ROOT = path.resolve(WEB_DIR, '..'); // repo root — holds agents_md/, runs/
const AGENTS_DIR = path.join(ROOT, 'agents_md');
const RUNS_DIR = path.join(ROOT, 'runs');
// ---------------------------------------------------------------------------
// Chat — conversations about the engagement, answered from its own records.
// ---------------------------------------------------------------------------
const CHAT_DIR = path.join(ROOT, '.neurosploit', 'chats');
async function chatList() {
try {
const names = await fsp.readdir(CHAT_DIR);
const out = [];
for (const n of names) {
if (!n.endsWith('.json')) continue;
const c = await readJsonSafe(path.join(CHAT_DIR, n), null);
if (!c) continue;
out.push({
id: c.id,
title: c.title || 'New conversation',
at: c.at || 0,
turns: (c.messages || []).length,
model: c.model || '',
});
}
return out.sort((a, b) => b.at - a.at);
} catch { return []; }
}
async function chatRead(id) {
if (!/^[\w-]{1,64}$/.test(id)) return null;
return readJsonSafe(path.join(CHAT_DIR, `${id}.json`), null);
}
async function chatWrite(c) {
await fsp.mkdir(CHAT_DIR, { recursive: true });
await fsp.writeFile(path.join(CHAT_DIR, `${c.id}.json`), JSON.stringify(c, null, 2));
}
/// Drive `neurosploit chat`, which streams JSON lines. Resolved separately
/// from runCli because that one buffers to completion, and the point here is
/// that the operator sees the answer as it lands.
function chatAsk(request, onEvent) {
return new Promise((resolve) => {
if (!BIN) return resolve({ error: 'neurosploit binary not found' });
const child = spawn(BIN, ['chat'], { cwd: ROOT, env: { ...process.env, ...envOverrides() } });
let buf = '';
let stderr = '';
child.stdout.on('data', (d) => {
buf += d.toString('utf8');
let i;
while ((i = buf.indexOf('\n')) >= 0) {
const line = buf.slice(0, i).trim();
buf = buf.slice(i + 1);
if (!line.startsWith('{')) continue; // the CLI's [auto] banner lines
try { onEvent(JSON.parse(line)); } catch { /* not ours */ }
}
});
child.stderr.on('data', (d) => { stderr += d.toString('utf8'); });
child.on('close', (code) => resolve(code === 0 ? {} : { error: stripAnsi(stderr).trim() || `chat exited ${code}` }));
child.on('error', (e) => resolve({ error: e.message }));
child.stdin.write(JSON.stringify(request));
child.stdin.end();
});
}
const NAMES_FILE = path.join(ROOT, '.neurosploit', 'web-engagement-names.json');
// Engagement names are set by the operator in the wizard before launch (not
@@ -3472,6 +3537,68 @@ const server = http.createServer(async (req, res) => {
}
// ---- REPL (real CLI harness session) ----
// ── Chat ──────────────────────────────────────────────────────────────
if (req.method === 'GET' && p === '/api/chat') {
return sendJson(res, 200, await chatList());
}
if (req.method === 'POST' && p === '/api/chat') {
if (!sameOrigin(req)) return sendJson(res, 403, { error: 'cross-origin request refused' });
const c = { id: crypto.randomUUID(), title: 'New conversation', at: Date.now(), messages: [], model: '' };
await chatWrite(c);
return sendJson(res, 201, c);
}
{
const cm = p.match(/^\/api\/chat\/([\w-]{1,64})$/);
if (cm && req.method === 'GET') {
const c = await chatRead(cm[1]);
return c ? sendJson(res, 200, c) : sendJson(res, 404, { error: 'no such conversation' });
}
if (cm && req.method === 'DELETE') {
if (!sameOrigin(req)) return sendJson(res, 403, { error: 'cross-origin request refused' });
await fsp.rm(path.join(CHAT_DIR, `${cm[1]}.json`), { force: true });
return sendJson(res, 200, { ok: true });
}
}
{
const sm = p.match(/^\/api\/chat\/([\w-]{1,64})\/send$/);
if (sm && req.method === 'POST') {
if (!sameOrigin(req)) return sendJson(res, 403, { error: 'cross-origin request refused' });
const c = await chatRead(sm[1]);
if (!c) return sendJson(res, 404, { error: 'no such conversation' });
const body = await readBody(req);
const message = String(body.message || '').trim();
if (!message) return sendJson(res, 400, { error: 'empty message' });
c.messages.push({ role: 'user', content: message, at: Date.now() });
// The first message names the conversation: a list of "New
// conversation" is unusable once there are more than two.
if (c.title === 'New conversation') c.title = message.slice(0, 60);
if (body.model) c.model = String(body.model);
await chatWrite(c);
sseInit(res);
let answer = '';
const r = await chatAsk({
message,
history: c.messages.slice(0, -1).map(({ role, content }) => ({ role, content })),
refs: Array.isArray(body.refs) ? body.refs : [],
model: c.model || '',
}, (ev) => {
if (ev.type === 'text') answer += ev.text;
sseSend(res, 'data', ev);
});
if (r.error) sseSend(res, 'data', { type: 'error', message: r.error });
if (answer) {
c.messages.push({ role: 'assistant', content: answer, at: Date.now() });
c.at = Date.now();
await chatWrite(c);
}
sseSend(res, 'data', { type: 'saved' });
return res.end();
}
}
if (req.method === 'POST' && p === '/api/repl') {
const session = startRepl();
return sendJson(res, 200, { id: session.id });