feat(settings): configure an LLM provider from the console, not a terminal (#137)

`neurosploit provider add` has taken a full profile for a while — base URL,
wire format, proxy, session header, user agent, rate limits, context window and
per-million-token prices. The console never caught up: Settings offered a key
box against a fixed provider list, so registering a gateway meant dropping to a
terminal, which is the opposite of the point.

Every field the CLI accepts is now in Settings. Reads go straight to
.neurosploit/custom_providers.json — the registry the harness itself reads —
and 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 in JavaScript is how the two drift apart.

A registered provider is now listed by /api/providers and serves its model
list, so it is selectable everywhere a model is chosen rather than only working
if you happen to type `name:model`. That was the actual ask: register once,
use everywhere.

Four more knobs the launcher has always accepted and only the wizard could
set, one run at a time: the fallback model chain (which also enables voting on
a disputed finding), the reasoning budget, the token ceiling and temperature.
They are defaults now, and they only pre-fill — a default that overwrites what
the operator already typed is worse than no default.

Two things found while wiring it. Verifying a key calls the operator's own
gateway, and runCli had no timeout, so a host that never answers would hang the
HTTP request; runCli takes an optional bound and the key check uses 30s, with a
rejected key leaving the provider registered rather than losing it. And CLI
errors reached the UI with the binary's `[auto] …` banner glued to the front,
burying the one line that says what went wrong.

Verified against the running console: registered a provider with proxy, rate
limit, context and prices; confirmed it appears in /api/providers and its
models endpoint; confirmed `provider show` reports the same record; confirmed
editing one field leaves base URL, models, proxy, prices and context intact;
confirmed the rejections — shadowing a built-in, a path-traversal name, a
cross-origin POST and a negative rate — all hold.

Co-authored-by: Joas A Santos <34966120+CyberSecurityUP@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-05 01:13:15 -03:00
1 parent 18b97faeff
commit caa6042554
3 files changed
+424 -5

No files matched your search

+264
View File
@@ -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() {
<div class="page-actions"><button class="btn btn-primary" id="btnSettingsSave">Save defaults</button></div>
</section>
<section class="card" id="modelRoutingCard">
<div class="card-head">
<div>
<div class="card-title">Model routing &amp; budget</div>
<div class="card-desc">Defaults for every new pentest. The run can still override them.</div>
</div>
</div>
<div class="form-group">
<label for="settingFallback">Fallback models</label>
<textarea id="settingFallback" rows="3" spellcheck="false"
placeholder="anthropic:claude-sonnet-5&#10;mygw:llama-3.1-70b">${esc((cfg.fallbackModels || []).join('\n'))}</textarea>
<div class="field-help">One <code>provider:model</code> per line, tried in order after the default above. More than one also enables voting on a disputed finding. Append <code>:sub</code> to use a subscription CLI instead of an API key.</div>
</div>
<div class="field-row">
<div class="form-group">
<label for="settingBudget">Reasoning budget</label>
<select id="settingBudget">
${opt('', cfg.budget || '', 'Unlimited (full run)')}${opt('eco', cfg.budget, 'Eco')}${opt('balanced', cfg.budget, 'Balanced')}${opt('aggressive', cfg.budget, 'Aggressive')}
</select>
<div class="field-help">How to spend reasoning, not how much exists.</div>
</div>
<div class="form-group">
<label for="settingTokenLimit">Token ceiling</label>
<input id="settingTokenLimit" type="number" min="0" step="1000" value="${esc(String(cfg.tokenLimit || 0))}">
<div class="field-help">Hard cap per run. 0 = none.</div>
</div>
<div class="form-group">
<label for="settingTemp">Temperature</label>
<input id="settingTemp" type="number" min="0" max="2" step="0.1" placeholder="0.2" value="${cfg.temperature === '' || cfg.temperature === undefined ? '' : esc(String(cfg.temperature))}">
<div class="field-help">0 is deterministic. API path only — subscription CLIs expose no such knob.</div>
</div>
</div>
</section>
<section class="card" id="customProvidersCard">
<div class="card-head">
<div>
<div class="card-title">Custom LLM providers</div>
<div class="card-desc">Any OpenAI- or Anthropic-compatible endpoint — a private gateway, vLLM, LM Studio, Ollama, a router. Registered here it becomes selectable everywhere, as <code>name:model</code>.</div>
</div>
<button class="btn btn-sm" id="btnCpNew">Add provider</button>
</div>
<div id="cpList"><div class="field-help">Loading…</div></div>
<form class="cp-form" id="cpForm" hidden></form>
</section>
<div class="settings-side">
<section class="card">
<div class="card-head"><div><div class="card-title">Model keys</div><div class="card-desc">${connected ? `${connected} provider${connected === 1 ? '' : 's'} connected` : 'No provider connected yet'}</div></div>
@@ -7923,6 +8008,7 @@ loadSettings = async function loadSettingsV5() {
</section>
</div>
</div>`;
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 = `<div class="field-help">Could not read the registry: ${esc(e.message)}</div>`;
return;
}
list.innerHTML = all.length ? `<div class="cp-list">${all.map((c) => `
<div class="cp-row">
<div class="cp-row-main">
<span class="cp-name">${esc(c.name)}</span>
<code class="cp-url">${esc(c.base_url || '(no base URL)')}</code>
</div>
<div class="cp-tags">
<span class="cp-tag">${esc(c.format || 'openai')}</span>
<span class="cp-tag ${c.key_set ? 'ok' : 'warn'}">${c.key_set ? 'key set' : 'no key'}</span>
${c.proxy ? '<span class="cp-tag">proxied</span>' : ''}
${(c.rps || c.rpm) ? '<span class="cp-tag">rate-limited</span>' : ''}
${(c.price_input || c.price_output) ? '<span class="cp-tag">priced</span>' : '<span class="cp-tag warn" title="The cost ledger will guess from the model name, which tells it nothing about a private gateway">unpriced</span>'}
${c.models?.length ? `<span class="cp-tag">${c.models.length} model${c.models.length === 1 ? '' : 's'}</span>` : ''}
</div>
<div class="cp-row-act">
<button class="btn btn-ghost btn-sm" data-cp-edit="${esc(c.name)}">Edit</button>
<button class="btn btn-ghost btn-sm" data-cp-del="${esc(c.name)}">Remove</button>
</div>
</div>`).join('')}</div>`
: '<div class="field-help">None registered. Everything the CLI takes is here — base URL, wire format, proxy, rate limits and per-million-token prices.</div>';
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}:<model> 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 = '') => `
<div class="form-group">
<label for="cp_${f.k}">${esc(f.label)}${f.req ? ' <span class="req">required</span>' : ''}</label>
<input id="cp_${f.k}" type="text" spellcheck="false" placeholder="${esc(f.ph || '')}"
value="${esc(f.k === 'models' ? (c.models || []).join(', ') : val(f.k))}">
${f.help ? `<div class="field-help">${esc(f.help)}</div>` : ''}${pre}
</div>`;
form.innerHTML = `
<div class="cp-form-head">${editing ? `Editing <b>${esc(c.name)}</b>` : 'New provider'}</div>
<div class="field-row">
<div class="form-group">
<label for="cp_name">Name${editing ? '' : ' <span class="req">required</span>'}</label>
<input id="cp_name" type="text" spellcheck="false" placeholder="mygw" value="${esc(c.name || '')}" ${editing ? 'readonly' : ''}>
<div class="field-help">Used as <code>name:model</code>. Cannot shadow a built-in provider.</div>
</div>
<div class="form-group">
<label for="cp_format">Wire format</label>
<select id="cp_format">
<option value="openai"${(c.format || 'openai') === 'openai' ? ' selected' : ''}>OpenAI (chat/completions)</option>
<option value="anthropic"${c.format === 'anthropic' ? ' selected' : ''}>Anthropic (messages)</option>
</select>
</div>
</div>
${CP_FIELDS.map((f) => text(f)).join('')}
<div class="form-group">
<label for="cp_api_key">API key${editing ? ` <span class="req">${c.key_set ? 'set — leave blank to keep' : 'not set'}</span>` : ''}</label>
<input id="cp_api_key" type="password" spellcheck="false" placeholder="${editing && c.key_set ? '•••••••• (unchanged)' : 'Key, or any value for a local endpoint'}">
<div class="field-help">Verified against the endpoint when saved, with a 30s bound. A rejected key still leaves the provider registered.</div>
</div>
<details class="cp-adv">
<summary>Transport</summary>
${CP_ADVANCED.map((f) => text(f)).join('')}
</details>
<details class="cp-adv">
<summary>Rate limits and context</summary>
<div class="field-row">${CP_LIMITS.map((f) => text(f)).join('')}</div>
</details>
<details class="cp-adv">
<summary>Pricing — USD per million tokens</summary>
<div class="field-help" style="margin-bottom:8px">Without these the cost ledger guesses from the model name, which tells it nothing about a private gateway.</div>
<div class="field-row">${CP_PRICES.map((f) => text({ ...f, ph: '0.00' })).join('')}</div>
</details>
<div class="btn-row">
<button class="btn btn-primary" type="submit">${editing ? 'Save changes' : 'Register provider'}</button>
<button class="btn btn-ghost" type="button" id="cpCancel">Cancel</button>
</div>`;
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', () => {
+20
View File
@@ -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); }
+140 -5
View File
@@ -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,