diff --git a/web/public/app.js b/web/public/app.js
index 4d5972c..5cde9ca 100644
--- a/web/public/app.js
+++ b/web/public/app.js
@@ -733,6 +733,7 @@ async function loadProviders() {
if (cfg.reactive === 'off') rbox.checked = false;
else if (cfg.reactive === 'on') rbox.checked = true;
}
+ applyModelDefaults(cfg);
if (cfg.defaultModel) {
const parts = cfg.defaultModel.split(':');
if (parts.length >= 2) {
@@ -749,6 +750,37 @@ async function loadProviders() {
} catch {}
onProviderChange();
}
+/// Seed a new run from the saved routing defaults. These only ever pre-fill:
+/// anything the operator already typed into the wizard wins, because a default
+/// that overwrites a deliberate choice is worse than no default.
+function applyModelDefaults(cfg) {
+ if (!cfg) return;
+ if (Array.isArray(cfg.fallbackModels) && cfg.fallbackModels.length && !state.extraModels?.length) {
+ state.extraModels = cfg.fallbackModels.map((ref) => {
+ const i = ref.indexOf(':');
+ if (i < 0) return null;
+ let model = ref.slice(i + 1);
+ let authMode = 'api';
+ if (model.endsWith(':sub')) { model = model.slice(0, -4); authMode = 'subscription'; }
+ return { provider: ref.slice(0, i), model, authMode };
+ }).filter(Boolean);
+ if (typeof renderExtraModels === 'function') renderExtraModels();
+ }
+ if (cfg.budget) { const b = $('#fieldBudget'); if (b && !b.value) b.value = cfg.budget; }
+ const tl = $('#fieldTokenLimit');
+ if (tl && !Number(tl.value) && cfg.tokenLimit) tl.value = String(cfg.tokenLimit);
+ // Temperature has no field of its own in the wizard: it lives in the extra
+ // options bag the launcher reads, so that is where the default belongs.
+ if (cfg.temperature !== '' && cfg.temperature !== undefined && cfg.temperature !== null
+ && state.extra && state.extra.temperature === undefined) {
+ const t = Number(cfg.temperature);
+ if (Number.isFinite(t) && t >= 0 && t <= 2) {
+ state.extra.temperature = t;
+ if (typeof renderExtraOptions === 'function') renderExtraOptions();
+ }
+ }
+}
+
function sanitizeModelSelect(prefer) {
const ms = $('#fieldModelSelect');
if (!ms) return;
@@ -7173,6 +7205,13 @@ async function saveSettings() {
autonomy: $('#settingAutonomy')?.value || 'standard',
mcpProfile: $('#settingMcpProfile')?.value || '',
reactive: $('#settingReactive')?.value || 'off',
+ // The run launcher has taken these since budgets existed; only the wizard
+ // could set them, one run at a time. These are the defaults it starts from.
+ fallbackModels: ($('#settingFallback')?.value || '')
+ .split('\n').map((s) => s.trim()).filter(Boolean),
+ budget: $('#settingBudget')?.value || '',
+ tokenLimit: Number($('#settingTokenLimit')?.value || 0) || 0,
+ temperature: $('#settingTemp')?.value === '' ? '' : Number($('#settingTemp')?.value),
};
try { await api('/api/config/settings', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); toast('Settings saved', 'ok'); }
catch (e) { toast(`Failed: ${e.message}`, 'error'); }
@@ -7903,6 +7942,52 @@ loadSettings = async function loadSettingsV5() {
Save defaults
+
+
+
+
Model routing & budget
+
Defaults for every new pentest. The run can still override them.
+
+
+
+
+
+
+
+
+
+
Custom LLM providers
+
Any OpenAI- or Anthropic-compatible endpoint — a private gateway, vLLM, LM Studio, Ollama, a router. Registered here it becomes selectable everywhere, as name:model.
+
+
Add provider
+
+
+
+
+
Model keys
${connected ? `${connected} provider${connected === 1 ? '' : 's'} connected` : 'No provider connected yet'}
@@ -7923,6 +8008,7 @@ loadSettings = async function loadSettingsV5() {
`;
+ renderCustomProviders();
// Two-step picker: provider → model, with the live catalog when available.
{
const provSel = $('#settingProvider');
@@ -8127,6 +8213,184 @@ function syncAiSummary() {
$('.ai-card')?.classList.toggle('needs-key', !sub && !hasKey);
}
+// ---------------------------------------------------------------------------
+// custom LLM providers
+//
+// `neurosploit provider add` has taken a full profile for a while; the console
+// only ever offered a key box against the fixed provider list, so registering a
+// gateway meant dropping to a terminal. Every field the CLI accepts is here,
+// and nothing here is cosmetic — each one changes how a request is made, what
+// it costs or how fast it is allowed to go.
+// ---------------------------------------------------------------------------
+
+const CP_FIELDS = [
+ { k: 'base_url', label: 'Base URL', ph: 'https://gateway.internal/v1', req: true,
+ help: 'Endpoint root. The wire path (/chat/completions) is appended.' },
+ { k: 'models', label: 'Models', ph: 'gpt-4o, llama-3.1-70b',
+ help: 'Comma-separated, to fill the pickers. Any id can still be typed, so this is convenience, not a limit.' },
+];
+const CP_ADVANCED = [
+ { k: 'proxy', label: 'Proxy', ph: 'socks5://127.0.0.1:1080',
+ help: 'Routes only this provider. Empty connects directly.' },
+ { k: 'session_header', label: 'Session header', ph: 'X-Session-Id',
+ help: 'For gateways that pin prompt-cache routing on a stable per-run id.' },
+ { k: 'user_agent', label: 'User-Agent', ph: 'NeuroSploit/4.6' },
+];
+const CP_LIMITS = [
+ { k: 'rps', label: 'Requests / second', ph: '0', help: '0 = unlimited' },
+ { k: 'rpm', label: 'Requests / minute', ph: '0', help: '0 = unlimited' },
+ { k: 'context_k', label: 'Context (K tokens)', ph: '0', help: '0 = global default' },
+];
+const CP_PRICES = [
+ { k: 'price_input', label: 'Input' }, { k: 'price_output', label: 'Output' },
+ { k: 'price_cache_read', label: 'Cache read' }, { k: 'price_cache_write', label: 'Cache write' },
+];
+
+async function renderCustomProviders() {
+ const list = $('#cpList');
+ if (!list) return;
+ let all = [];
+ try { all = await api('/api/custom-providers'); } catch (e) {
+ list.innerHTML = `Could not read the registry: ${esc(e.message)}
`;
+ return;
+ }
+ list.innerHTML = all.length ? `${all.map((c) => `
+
+
+ ${esc(c.name)}
+ ${esc(c.base_url || '(no base URL)')}
+
+
+ ${esc(c.format || 'openai')}
+ ${c.key_set ? 'key set' : 'no key'}
+ ${c.proxy ? 'proxied ' : ''}
+ ${(c.rps || c.rpm) ? 'rate-limited ' : ''}
+ ${(c.price_input || c.price_output) ? 'priced ' : 'unpriced '}
+ ${c.models?.length ? `${c.models.length} model${c.models.length === 1 ? '' : 's'} ` : ''}
+
+
+ Edit
+ Remove
+
+
`).join('')}
`
+ : 'None registered. Everything the CLI takes is here — base URL, wire format, proxy, rate limits and per-million-token prices.
';
+
+ state.customProviders = all;
+ $$('[data-cp-edit]', list).forEach((b) =>
+ b.addEventListener('click', () => cpOpenForm(all.find((x) => x.name === b.dataset.cpEdit))));
+ $$('[data-cp-del]', list).forEach((b) => b.addEventListener('click', async () => {
+ const name = b.dataset.cpDel;
+ if (!confirm(`Remove provider "${name}"? Runs that reference ${name}: will stop resolving. Its API key is removed separately.`)) return;
+ try {
+ await api(`/api/custom-providers/${encodeURIComponent(name)}`, { method: 'DELETE' });
+ toast(`${name} removed`, 'ok');
+ state.providers = await api('/api/providers').catch(() => state.providers);
+ renderCustomProviders();
+ } catch (e) { toast(e.message, 'error'); }
+ }));
+}
+
+function cpOpenForm(existing) {
+ const form = $('#cpForm');
+ if (!form) return;
+ const c = existing || {};
+ const editing = !!existing;
+ const val = (k) => (c[k] === undefined || c[k] === 0 ? '' : String(c[k]));
+ const text = (f, pre = '') => `
+ `;
+
+ form.innerHTML = `
+ ${editing ? `Editing ${esc(c.name)} ` : 'New provider'}
+
+
+
+ Wire format
+
+ OpenAI (chat/completions)
+ Anthropic (messages)
+
+
+
+ ${CP_FIELDS.map((f) => text(f)).join('')}
+
+
+ Transport
+ ${CP_ADVANCED.map((f) => text(f)).join('')}
+
+
+ Rate limits and context
+ ${CP_LIMITS.map((f) => text(f)).join('')}
+
+
+ Pricing — USD per million tokens
+ Without these the cost ledger guesses from the model name, which tells it nothing about a private gateway.
+ ${CP_PRICES.map((f) => text({ ...f, ph: '0.00' })).join('')}
+
+
+ ${editing ? 'Save changes' : 'Register provider'}
+ Cancel
+
`;
+ form.hidden = false;
+ form.dataset.editing = editing ? '1' : '';
+ $('#cpCancel', form).addEventListener('click', () => { form.hidden = true; });
+ $('#cp_name', form)?.focus();
+}
+
+// Delegated: the settings body is re-rendered wholesale on every load, so a
+// handler bound to the button itself would be thrown away with it.
+document.addEventListener('click', (e) => {
+ if (e.target?.id === 'btnCpNew') cpOpenForm(null);
+});
+document.addEventListener('submit', async (e) => {
+ if (e.target?.id !== 'cpForm') return;
+ e.preventDefault();
+ const form = e.target;
+ const v = (k) => $(`#cp_${k}`, form)?.value.trim() ?? '';
+ const name = v('name');
+ if (!name) return toast('Name is required', 'error');
+ // On a new provider the base URL is what makes it callable; on an edit an
+ // empty field means "leave it alone", so it must not be sent as a blank.
+ if (!form.dataset.editing && !v('base_url')) return toast('Base URL is required', 'error');
+
+ const body = { name, format: v('format') };
+ for (const k of ['base_url', 'proxy', 'session_header', 'user_agent', 'api_key']) {
+ if (v(k)) body[k] = v(k);
+ }
+ const models = v('models');
+ if (models) body.models = models.split(/[,\n]/).map((s) => s.trim()).filter(Boolean);
+ for (const k of ['rps', 'rpm', 'context_k', 'price_input', 'price_output', 'price_cache_read', 'price_cache_write']) {
+ if (v(k) !== '') body[k] = Number(v(k));
+ }
+
+ const btn = $('button[type=submit]', form);
+ if (btn) { btn.disabled = true; btn.textContent = 'Saving…'; }
+ try {
+ const r = await api('/api/custom-providers', { method: 'POST', body: JSON.stringify(body) });
+ toast(r.warning || `${name} saved`, r.warning ? 'warn' : 'ok');
+ form.hidden = true;
+ // Refresh the catalog so the new provider is immediately selectable.
+ state.providers = await api('/api/providers').catch(() => state.providers);
+ renderCustomProviders();
+ } catch (err) {
+ toast(err.message, 'error');
+ } finally {
+ if (btn) { btn.disabled = false; btn.textContent = form.dataset.editing ? 'Save changes' : 'Register provider'; }
+ }
+});
+
$('#btnAiAddKey')?.addEventListener('click', () => openProviderKeysModal());
$('#fieldProvider')?.addEventListener('change', syncAiSummary);
$('#fieldModelSelect')?.addEventListener('change', () => {
diff --git a/web/public/style.css b/web/public/style.css
index 944b311..2314a1c 100644
--- a/web/public/style.css
+++ b/web/public/style.css
@@ -3299,6 +3299,26 @@ a.chat-cite:hover { border-color: var(--accent, #7c5cff); color: var(--accent, #
.chat-tools-toggle { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; color: var(--text-dim); cursor: pointer; user-select: none; }
.chat-tools-toggle input { accent-color: var(--accent, #7c5cff); }
+/* Custom LLM providers */
+.cp-list { display: flex; flex-direction: column; gap: 7px; }
+.cp-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding: 10px 12px; background: var(--surface-2); border: 1px solid var(--border); border-radius: 8px; }
+.cp-row-main { display: flex; flex-direction: column; gap: 2px; min-width: 180px; flex: 1; }
+.cp-name { font-weight: 600; font-size: var(--fs-sm); }
+.cp-url { font-size: 11px; color: var(--text-dim); background: none; padding: 0; overflow: hidden; text-overflow: ellipsis; }
+.cp-tags { display: flex; flex-wrap: wrap; gap: 5px; }
+.cp-tag { font-size: 10px; text-transform: uppercase; letter-spacing: .04em; padding: 2px 7px; border-radius: 4px; background: var(--surface-3, var(--surface)); border: 1px solid var(--border); color: var(--text-dim); }
+.cp-tag.ok { border-color: var(--sev-low-fg, #4ba3d4); color: var(--sev-low-fg, #4ba3d4); }
+.cp-tag.warn { border-color: var(--sev-medium-fg, #d4a84b); color: var(--sev-medium-fg, #d4a84b); }
+.cp-row-act { display: flex; gap: 5px; margin-left: auto; }
+
+.cp-form { display: flex; flex-direction: column; gap: 12px; margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--border); }
+.cp-form-head { font-size: var(--fs-sm); font-weight: 600; }
+.cp-form input[readonly] { opacity: .65; cursor: not-allowed; }
+.cp-adv { background: var(--surface-2); border: 1px solid var(--border); border-radius: 8px; padding: 0 12px; }
+.cp-adv > summary { cursor: pointer; padding: 9px 0; font-size: var(--fs-sm); color: var(--text-dim); }
+.cp-adv[open] > summary { border-bottom: 1px solid var(--border); margin-bottom: 11px; }
+.cp-adv > :last-child { padding-bottom: 12px; }
+
.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); }
diff --git a/web/server.js b/web/server.js
index fec5e9b..1de49d6 100644
--- a/web/server.js
+++ b/web/server.js
@@ -1827,19 +1827,45 @@ async function listTree(abs, rel, depth = 0) {
/// Run the real CLI against a run directory and capture its output. The web
/// console never re-implements harness logic — it shells out, like `rebuild`.
-function runCli(args) {
+/// `timeoutMs` bounds commands that reach the network — verifying a key against
+/// an operator-supplied gateway can hang on a host that never answers, and an
+/// HTTP request of ours must not hang with it. 0 means wait indefinitely, which
+/// stays the default so existing callers are unchanged.
+function runCli(args, timeoutMs = 0) {
return new Promise((resolve) => {
if (!BIN) return resolve({ code: -1, buf: 'neurosploit binary not found — run `cargo build --release` in neurosploit-rs/' });
const child = spawn(BIN, args, { cwd: ROOT, env: { ...process.env, ...envOverrides() } });
let stdout = '';
let stderr = '';
+ let timer = null;
+ let timedOut = false;
+ const done = (r) => { if (timer) clearTimeout(timer); resolve(r); };
+ if (timeoutMs > 0) {
+ timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, timeoutMs);
+ }
child.stdout.on('data', (c) => { stdout += c.toString('utf8'); });
child.stderr.on('data', (c) => { stderr += c.toString('utf8'); });
- child.on('close', (code) => resolve({ code, buf: stripAnsi(stdout), stderr: stripAnsi(stderr) }));
- child.on('error', (e) => resolve({ code: -1, buf: e.message, stderr: '' }));
+ child.on('close', (code) => done({
+ code: timedOut ? -1 : code,
+ buf: stripAnsi(stdout),
+ stderr: timedOut ? `timed out after ${timeoutMs}ms` : stripAnsi(stderr),
+ }));
+ child.on('error', (e) => done({ code: -1, buf: e.message, stderr: '' }));
});
}
+/// The reason a CLI call failed, fit to show a person. The binary prints an
+/// `[auto] …` configuration banner before anything else, and pasting that into
+/// a toast buries the one line that says what went wrong.
+function cliError(r, fallback) {
+ const lines = `${r.stderr || ''}\n${r.buf || ''}`
+ .split('\n')
+ .map((l) => l.trim())
+ .filter((l) => l && !l.startsWith('[auto]') && !l.startsWith('[*]'));
+ const named = lines.find((l) => l.startsWith('Error:') || l.startsWith('error:'));
+ return (named ? named.replace(/^[Ee]rror:\s*/, '') : lines[0]) || fallback;
+}
+
/// The attack graph a run produced: chains, the dependency todolist and the
/// graph itself. Live files (written during the run) win while it runs.
async function runGraph(dir) {
@@ -4358,7 +4384,21 @@ const server = http.createServer(async (req, res) => {
// ---- providers / API keys (persisted to .neurosploit/keys.json) ----
if (req.method === 'GET' && p === '/api/providers') {
- return sendJson(res, 200, PROVIDERS.map(({ key, label, kind, models }) => ({ key, label, kind, models })));
+ // Custom providers are listed alongside the built-ins, which is the
+ // whole point of registering one: it becomes selectable everywhere a
+ // model is chosen, instead of only working if you type `name:model`.
+ const raw = await readJsonSafe(path.join(ROOT, '.neurosploit', 'custom_providers.json'), {});
+ const builtinKeys = new Set(PROVIDERS.map((x) => x.key));
+ const custom = Object.entries(raw || {})
+ .filter(([name]) => !builtinKeys.has(name)) // a custom name never shadows a built-in
+ .map(([name, v]) => {
+ const prof = typeof v === 'string' ? { base_url: v } : (v || {});
+ return { key: name, label: `${name} (custom)`, kind: 'custom', models: prof.models || [], custom: true };
+ });
+ return sendJson(res, 200, [
+ ...PROVIDERS.map(({ key, label, kind, models }) => ({ key, label, kind, models })),
+ ...custom,
+ ]);
}
{
// Full catalog for any provider (live when a key/public endpoint exists,
@@ -4366,11 +4406,106 @@ const server = http.createServer(async (req, res) => {
const pm = p.match(/^\/api\/providers\/([\w-]+)\/models$/);
if (req.method === 'GET' && pm) {
const key = pm[1];
- if (!PROVIDERS.some((x) => x.key === key)) return sendJson(res, 404, { error: 'unknown provider' });
+ if (!PROVIDERS.some((x) => x.key === key)) {
+ // A registered custom provider answers with the ids the operator
+ // listed. An empty list is not an error: any id can still be typed.
+ const raw = await readJsonSafe(path.join(ROOT, '.neurosploit', 'custom_providers.json'), {});
+ const v = raw && raw[key];
+ if (v === undefined) return sendJson(res, 404, { error: 'unknown provider' });
+ const prof = typeof v === 'string' ? {} : (v || {});
+ return sendJson(res, 200, { key, models: prof.models || [], source: 'custom' });
+ }
const r = await providerModels(key);
return sendJson(res, 200, { key, models: r.models, source: r.source });
}
}
+ // ---- custom providers -------------------------------------------------
+ // Reads go straight to the registry the harness itself reads. Writes go
+ // through `neurosploit provider`, so the CLI keeps owning validation, the
+ // built-in-name collision check and the merge-don't-replace semantics —
+ // reimplementing those here is how the two drift apart.
+ if (p === '/api/custom-providers') {
+ if (req.method === 'GET') {
+ const raw = await readJsonSafe(path.join(ROOT, '.neurosploit', 'custom_providers.json'), {});
+ const keys = await readJsonSafe(path.join(ROOT, '.neurosploit', 'keys.json'), {});
+ const out = Object.entries(raw || {}).map(([name, v]) => {
+ // The registry started as {name: base_url}; both forms are live.
+ const prof = typeof v === 'string' ? { base_url: v } : (v || {});
+ return {
+ name,
+ base_url: prof.base_url || '',
+ format: prof.format || 'openai',
+ models: prof.models || [],
+ proxy: prof.proxy || '',
+ session_header: prof.session_header || '',
+ user_agent: prof.user_agent || '',
+ rps: prof.rps || 0,
+ rpm: prof.rpm || 0,
+ context_k: prof.context_k || 0,
+ price_input: prof.price_input || 0,
+ price_output: prof.price_output || 0,
+ price_cache_read: prof.price_cache_read || 0,
+ price_cache_write: prof.price_cache_write || 0,
+ key_set: !!(keys && keys[name]),
+ };
+ });
+ return sendJson(res, 200, out);
+ }
+ if (req.method === 'POST') {
+ if (!sameOrigin(req)) return sendJson(res, 403, { error: 'cross-origin request refused' });
+ const b = await readBody(req);
+ const name = String(b.name || '').trim();
+ if (!/^[a-z0-9][a-z0-9_-]{0,31}$/i.test(name)) {
+ return sendJson(res, 400, { error: 'name must be 1-32 chars: letters, digits, dash, underscore' });
+ }
+ const args = ['provider', 'add', name];
+ const str = { base_url: '--base-url', format: '--format', proxy: '--proxy',
+ session_header: '--session-header', user_agent: '--user-agent' };
+ for (const [k, flag] of Object.entries(str)) {
+ const v = String(b[k] ?? '').trim();
+ if (v) args.push(flag, v);
+ }
+ const num = { rps: '--rps', rpm: '--rpm', context_k: '--context-k',
+ price_input: '--price-input', price_output: '--price-output',
+ price_cache_read: '--price-cache-read', price_cache_write: '--price-cache-write' };
+ for (const [k, flag] of Object.entries(num)) {
+ // Only send what the form actually set: an omitted flag leaves the
+ // stored value alone, which is what makes editing one field safe.
+ if (b[k] === undefined || b[k] === null || b[k] === '') continue;
+ const n = Number(b[k]);
+ if (!Number.isFinite(n) || n < 0) return sendJson(res, 400, { error: `${k} must be a non-negative number` });
+ args.push(flag, String(n));
+ }
+ const models = Array.isArray(b.models) ? b.models
+ : String(b.models || '').split(/[,\n]/).map((s) => s.trim()).filter(Boolean);
+ for (const m of models) args.push('--model', m);
+
+ const r = await runCli(args);
+ if (r.code !== 0) {
+ return sendJson(res, 400, { error: cliError(r, 'provider add failed') });
+ }
+ // The key is a normal keystore entry under the provider's own name.
+ if (b.api_key) {
+ // Verification calls the operator's own gateway: bound it, and treat
+ // a failure as a warning rather than losing the saved provider.
+ const kr = await runCli(['key', 'add', '--provider', name, String(b.api_key)], 30000);
+ if (kr.code !== 0) {
+ return sendJson(res, 200, { ok: true, warning: `provider saved, key not verified: ${(kr.stderr || kr.buf).trim().slice(0, 300)}` });
+ }
+ }
+ return sendJson(res, 200, { ok: true, message: (r.buf || '').trim() });
+ }
+ }
+ {
+ const cpm = p.match(/^\/api\/custom-providers\/([\w-]{1,32})$/);
+ if (cpm && req.method === 'DELETE') {
+ if (!sameOrigin(req)) return sendJson(res, 403, { error: 'cross-origin request refused' });
+ const r = await runCli(['provider', 'remove', cpm[1]]);
+ if (r.code !== 0) return sendJson(res, 400, { error: cliError(r, 'remove failed') });
+ return sendJson(res, 200, { ok: true });
+ }
+ }
+
if (req.method === 'GET' && p === '/api/subscriptions') {
return sendJson(res, 200, SUB_CLIS.map((c) => ({
provider: c.provider, label: c.label, bin: c.bin, login: c.login,