'use strict'; /* Draws what the server sends. No library: three chart kinds are enough, * and drawing a curve by hand is less code than pulling in a chart library — * and works offline. */ const $ = (sel) => document.querySelector(sel); const fmt = (v, d = 0) => (v === null || v === undefined || Number.isNaN(v)) ? '—' : Number(v).toFixed(d); function css(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); } /* ------------------------------------------------------------------ Drawing */ function setup(canvas) { if (!canvas) return null; const dpr = window.devicePixelRatio || 1; const rect = canvas.getBoundingClientRect(); const hAttr = Number(canvas.getAttribute('height')) || 120; canvas.width = Math.max(1, Math.floor(rect.width * dpr)); canvas.height = Math.max(1, Math.floor(hAttr * dpr)); const ctx = canvas.getContext('2d'); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); return { ctx, w: rect.width, h: hAttr }; } function drawSeries(canvas, rows, opts = {}) { const s = setup(canvas); if (!s) return; const { ctx, w, h } = s; const pad = { l: 6, r: 6, t: 8, b: 16 }; const iw = w - pad.l - pad.r; const ih = h - pad.t - pad.b; const colors = opts.colors || [css('--accent'), css('--warn'), css('--bad')]; const maxLen = Math.max(...rows.map((r) => (r.values || []).length), 2); let max = 0; for (const r of rows) for (const v of (r.values || [])) if (v > max) max = v; if (max <= 0) max = 1; ctx.clearRect(0, 0, w, h); ctx.strokeStyle = css('--line'); ctx.globalAlpha = 0.5; ctx.lineWidth = 1; for (let i = 0; i <= 3; i++) { const y = pad.t + (ih / 3) * i; ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + iw, y); ctx.stroke(); } ctx.globalAlpha = 1; const xOf = (i) => pad.l + (iw * i) / Math.max(1, maxLen - 1); const yOf = (v) => pad.t + ih - (ih * Math.min(v, max)) / max; for (let ri = 0; ri < rows.length; ri++) { const row = rows[ri]; const vals = row.values || []; const n = vals.length; if (!n) continue; ctx.beginPath(); ctx.moveTo(xOf(0), yOf(vals[0])); for (let i = 1; i < n; i++) ctx.lineTo(xOf(i), yOf(vals[i])); ctx.strokeStyle = colors[ri % colors.length]; ctx.lineWidth = 1.6; ctx.stroke(); ctx.lineTo(xOf(n - 1), pad.t + ih); ctx.lineTo(xOf(0), pad.t + ih); ctx.closePath(); const grad = ctx.createLinearGradient(0, pad.t, 0, pad.t + ih); grad.addColorStop(0, colors[ri % colors.length] + '55'); grad.addColorStop(1, colors[ri % colors.length] + '05'); ctx.fillStyle = grad; ctx.fill(); } ctx.fillStyle = css('--dim'); ctx.font = '11px ui-monospace, monospace'; ctx.fillText(opts.unit ? `${fmt(max, opts.digits || 0)} ${opts.unit}` : fmt(max, opts.digits || 0), pad.l + 2, pad.t + 10); } /* ------------------------------------------------------------------ State */ let status = null; let series = null; function state() { const s = status || {}; return { reqs: s.requests || {}, usage: s.usage || {}, lat: s.latency || {} }; } function duration(s) { if (s == null) return '—'; if (s < 60) return `${Math.round(s)} s`; if (s < 3600) return `${Math.floor(s / 60)} min`; if (s < 86400) return `${Math.floor(s / 3600)} h ${Math.floor((s % 3600) / 60)} min`; return `${Math.floor(s / 86400)} d ${Math.floor((s % 86400) / 3600)} h`; } function renderHeader() { const { reqs, lat } = state(); const ser = series || {}; const lastOf = (k) => { const a = ser[k] || []; return a.length ? a[a.length - 1] : null; }; $('#n-req').textContent = fmt(lastOf('requests'), 2); $('#n-tok').textContent = fmt((lastOf('tokensIn') || 0) + (lastOf('tokensOut') || 0), 0); $('#n-lat').textContent = lat.avg_ms >= 0 ? `${fmt(lat.avg_ms, 0)} ms` : '—'; const c = lastOf('cost'); $('#n-cost').textContent = c === null ? '—' : `${fmt(c * 3600, 3)} $`; $('#n-fail').textContent = fmt(reqs.fail || 0); $('#n-fail').style.color = (reqs.fail || 0) > 0 ? css('--bad') : ''; const up = status && status.uptime_s !== undefined ? status.uptime_s : null; $('#uptime').textContent = up === null ? '—' : `up ${duration(up)}`; $('#state').className = 'dot ' + (status ? 'live' : 'dead'); } function renderCharts() { if (!series) return; drawSeries($('#g-requests'), [ { values: series.requests || [] }, { values: series.failed || [] }, ], { unit: '/s', digits: 2, colors: [css('--accent'), css('--bad')] }); $('#c-req').textContent = `now ${fmt((series.requests || []).slice(-1)[0], 2)}/s · errors ${fmt((series.failed || []).slice(-1)[0], 2)}/s`; drawSeries($('#g-tokens'), [ { values: series.tokensIn || [] }, { values: series.tokensOut || [] }, ], { unit: 'tok/s', digits: 0, colors: [css('--ok'), css('--accent')] }); const ti = (series.tokensIn || []).slice(-1)[0] || 0; const to = (series.tokensOut || []).slice(-1)[0] || 0; $('#c-tok').textContent = `in ${fmt(ti)}/s · out ${fmt(to)}/s`; drawSeries($('#g-latency'), [{ values: (series.latency || []).map((v) => (v < 0 ? 0 : v)) }], { unit: 'ms', digits: 0, colors: [css('--warn')] }); drawSeries($('#g-traffic'), [{ values: series.traffic || [] }], { unit: 'B/s', digits: 0, colors: [css('--accent')] }); } function renderEndpoints() { const body = $('#t-eps tbody'); const eps = (status && status.endpoints) || []; body.innerHTML = ''; for (const ep of eps) { const tr = document.createElement('tr'); const st = ep.paused ? 'paused' : (ep.offline_s > 0 ? `offline ${ep.offline_s}s` : (ep.exhausted ? 'exhausted' : 'ready')); tr.innerHTML = ` ${escapeHtml(ep.name)}
${escapeHtml(ep.kind || '')} ${st} ${fmt(ep.ok)} ${fmt(ep.fail)} ${fmt(ep.inflight)} ${fmt(ep.last_ms)} `; body.appendChild(tr); } for (const btn of body.querySelectorAll('button[data-ep]')) { btn.onclick = async () => { await fetch(`/api/endpoint/${encodeURIComponent(btn.dataset.ep)}/${btn.dataset.act}`, { method: 'POST' }); refresh(); }; } } function renderMcp(servers, tools) { const body = $('#t-mcp tbody'); if (!body) return; body.innerHTML = ''; const list = servers || []; const toolList = tools || []; $('#c-mcp').textContent = list.length ? `${list.length} connected · ${toolList.length} tools` : 'none connected'; for (const m of list) { const tr = document.createElement('tr'); const st = !m.enabled ? 'off' : (m.fail > 0 && m.tools === 0 ? `${escapeHtml(m.last_error || 'unreachable')}` : 'reachable'); tr.innerHTML = ` ${escapeHtml(m.name)} ${escapeHtml(m.url || m.cmd || '')} ${fmt(m.tools)} ${fmt(m.ok)} ${fmt(m.fail)} ${st}`; body.appendChild(tr); } const box = $('#mcp-tools'); box.innerHTML = ''; const seen = new Set(); for (const t of toolList) { const name = t.name || ''; if (seen.has(name)) continue; seen.add(name); const cut = name.indexOf('__'); const server = cut > 0 ? name.slice(0, cut) : '—'; const short = cut > 0 ? name.slice(cut + 2) : name; const el = document.createElement('span'); el.className = 'tool'; el.innerHTML = `${escapeHtml(server)} ${escapeHtml(short)}`; if (t.description) el.title = t.description; box.appendChild(el); } } function renderVkeys() { const body = $('#t-vkeys tbody'); if (!body) return; const keys = (status && status.vkeys) || []; body.innerHTML = ''; for (const k of keys) { const tr = document.createElement('tr'); const over = k.budget_usd > 0 && k.spent_usd >= k.budget_usd; tr.innerHTML = ` ${escapeHtml(k.name)} ${escapeHtml(k.allow || '*')} ${k.rpm > 0 ? k.rpm : '—'} ${k.budget_usd > 0 ? '$' + k.budget_usd.toFixed(2) : '—'} $${(k.spent_usd || 0).toFixed(4)} ${fmt(k.hits)} ${fmt(k.denied)}${over ? ' exhausted' : ''}`; body.appendChild(tr); } const refused = (status && status.guard_refused) || 0; const c = $('#c-spend'); if (c) c.textContent = keys.length ? `${keys.length} keys${refused ? ' · ' + refused + ' refused by guard' : ''}` : 'no virtual keys'; } async function loadSpend() { const box = $('#spend-detail'); if (!box) return; try { const r = await fetch('/api/spend').then((x) => x.json()); if (!r.ok || !r.spend) { box.textContent = r.error || 'no data'; return; } const sp = r.spend; if (sp.error) { box.textContent = sp.error; return; } const models = (sp.models || []).map((m) => `${escapeHtml(m.model)} · $${(m.cost_usd || 0).toFixed(4)} · ${fmt(m.requests)}`).join(' '); box.innerHTML = `${escapeHtml(sp.month || '')}: $${(sp.total_usd || 0).toFixed(4)}` + ` over ${fmt(sp.requests)} requests` + (models ? '
' + models : ''); } catch (e) { box.textContent = 'no data'; } } function renderRules(rules) { const body = $('#t-rules tbody'); body.innerHTML = ''; $('#c-rules').textContent = `${rules.length} active`; rules.forEach((r, i) => { const tr = document.createElement('tr'); const need = [r.need_min >= 0 ? `≥${r.need_min}` : '', r.need_max >= 0 ? `≤${r.need_max}` : ''] .filter(Boolean).join(' ') || '—'; const ctx = [r.ctx_min >= 0 ? `≥${r.ctx_min}` : '', r.ctx_max >= 0 ? `≤${r.ctx_max}` : ''] .filter(Boolean).join(' ') || '—'; tr.innerHTML = ` ${r.index ?? i} ${escapeHtml(r.model || '*')} ${escapeHtml(r.path || '*')} ${r.block ? 'block' : escapeHtml(r.targets || '')} ${need} ${ctx} `; body.appendChild(tr); }); for (const btn of body.querySelectorAll('button[data-rule]')) { btn.onclick = async () => { await fetch(`/api/rules?index=${encodeURIComponent(btn.dataset.rule)}`, { method: 'DELETE' }); refresh(); }; } } async function loadRequests() { const body = $('#t-req tbody'); if (!body) return; try { const r = await fetch('/api/requests?count=25').then((x) => x.json()); const lines = (r.ok && r.requests && r.requests.lines) || []; body.innerHTML = ''; if (!lines.length) { $('#req-stats').textContent = r.error || 'no requests in log yet'; return; } for (const l of lines) { const tr = document.createElement('tr'); const when = l.ts ? new Date(l.ts * 1000).toLocaleTimeString() : '—'; const bad = l.status && l.status >= 400; const tin = (l.tokens_in != null ? l.tokens_in : '—'); const tout = (l.tokens_out != null ? l.tokens_out : '—'); const cost = (l.cost_usd != null ? Number(l.cost_usd) : 0); tr.innerHTML = ` ${when} ${escapeHtml(l.model || '—')} ${escapeHtml(l.endpoint || '—')} ${bad ? '' + l.status + '' : (l.status || '—')} ${l.latency_ms ?? '—'} ${escapeHtml(l.cache || '—')} ${tin}/${tout} ${cost.toFixed(6)}`; body.appendChild(tr); } const ms = lines.map((l) => Number(l.latency_ms) || 0).sort((a, b) => a - b); const p95 = ms.length ? ms[Math.min(ms.length - 1, Math.ceil(ms.length * 0.95) - 1)] : 0; const hits = lines.filter((l) => ['hit', 'peer', 'joined'].includes(l.cache)).length; $('#req-stats').textContent = `${lines.length} requests · p95 ${p95} ms · hit rate ${Math.round(hits / lines.length * 100)} %`; } catch (e) { $('#req-stats').textContent = 'no data'; } } function escapeHtml(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); } /* ---------------------------- Config editor highlight (Junction syntax) */ function highlightJunction(text) { const esc = (s) => escapeHtml(s); let i = 0; let out = ''; const keywords = new Set(['listen','connect_timeout_ms','offline_hold_s','max_body_bytes','max_inflight','queue_timeout','retry_num','retry_backoff','retry_max_wait','offline_wait','spend_log','guard','request','log_prefix','cache_ttl','cache_entries','cache_bytes','cache_secret_env','cache_peer','cache_peer_timeout_ms','so_reuseport','drain_timeout','mcp_auth','auto_endpoints','probe_interval','probe_timeout','ctx_chars_per_token','prices_path','metrics','control','control_unix','control_tcp','balance','compress_keep','compress_min_bytes','mcp_cache_ttl','cache_deterministic_only','req','pass','block','endpoint','pool','vkey','mcp','for','path','need','check','retry','ctx','vision','strip','as','base','kind','context','priority','timeout','idle_timeout','cooldown','hook','hook_retry','hook_backoff','wake','api_key_env','auth_basic_user','pass_cmd','base_cmd','usage_cmd','usage_poll_s','budget_soft','budget_hard','on_soft_delay_s','on_hard_skip','offpeak_from','offpeak_to','cost_weight','tls_verify','tls_ca','cache_on','header','max_model_inflight','probe_on','connect_timeout_ms','weight','url','cmd','headers','timeout_s','retry_ms','enabled','token_env','allow','endpoints','mcp_tools','rpm','budget_usd','budget','on_hard','on_soft','skip','delay','cache']); const bools = new Set(['on','off','true','false','auto','all','none','first','round-robin','least-usage','cost','remote','local','opencode-go','opencode','hooks']); const lines = String(text || '').split('\n'); for (let li = 0; li < lines.length; li++) { let line = lines[li]; let j = 0; while (j < line.length) { const ch = line[j]; if (ch === '#') { out += `${esc(line.slice(j))}`; break; } if (ch === '"' || ch === "'") { const q = ch; let k = j + 1; while (k < line.length) { if (line[k] === '\\') { k += 2; continue; } if (line[k] === q) { k++; break; } k++; } out += `${esc(line.slice(j, k))}`; j = k; continue; } if (/\s/.test(ch)) { out += esc(ch); j++; continue; } let k = j; while (k < line.length && !/\s/.test(line[k]) && !/[#"'{}]/.test(line[k])) k++; // split braces/operators attached if (k === j) { out += `${esc(ch)}`; j++; continue; } const tok = line.slice(j, k); // handle attached braces let core = tok, suffix = ''; const m = tok.match(/^([^{},]+)([{},]+)$/); if (m) { core = m[1]; suffix = m[2]; } const lower = core.toLowerCase(); let cls = ''; if (/^\d+(\.\d+)?$/.test(core)) cls = 'tok-num'; else if (/^https?:\/\//.test(core)) cls = 'tok-url'; else if (/^\//.test(core)) cls = 'tok-path'; else if (bools.has(lower) || bools.has(core)) cls = 'tok-bool'; else if (keywords.has(lower) || keywords.has(core)) cls = 'tok-kw'; else cls = ''; if (cls) out += `${esc(core)}`; else out += esc(core); if (suffix) out += `${esc(suffix)}`; j = k; } if (li < lines.length - 1) out += '\n'; } return out + '\n'; } function syncConfigHighlight() { const ta = $('#config'); const hl = $('#config-hl'); if (!ta || !hl) return; hl.innerHTML = highlightJunction(ta.value); hl.scrollTop = ta.scrollTop; hl.scrollLeft = ta.scrollLeft; } async function loadConfig(auto = false) { const hint = $('#cfg-hint'); try { const r = await fetch('/api/config').then((x) => x.json()); if (r.ok) { $('#config').value = r.text || ''; syncConfigHighlight(); hint.className = 'hint ok'; hint.textContent = auto ? 'loaded' : 'reloaded'; } else { hint.className = 'hint bad'; hint.textContent = r.error || 'not loadable'; if (!auto) return; } } catch (e) { hint.className = 'hint bad'; hint.textContent = 'not loadable'; } } /* ------------------------------------------------------------------ Data */ async function refresh() { try { const r = await fetch('/api/snapshot'); const data = await r.json(); status = data.ok ? data.status : null; series = data.series || series; renderHeader(); renderCharts(); renderEndpoints(); renderRules(data.rules || []); renderMcp((data.status && data.status.mcp) || [], data.tools || []); renderVkeys(); loadSpend(); loadRequests(); } catch (e) { status = null; renderHeader(); } } function listen() { const es = new EventSource('/api/stream'); es.onmessage = (ev) => { try { const data = JSON.parse(ev.data); status = data.ok ? data.status : null; if (data.series) series = data.series; renderHeader(); renderCharts(); renderEndpoints(); renderRules(data.rules || []); renderMcp((data.status && data.status.mcp) || [], data.tools || []); renderVkeys(); } catch (e) { /* a broken frame must not stop rendering */ } }; es.onerror = () => { es.close(); setTimeout(listen, 3000); }; } /* ------------------------------------------------------------------ Forms */ $('#f-rule').onsubmit = async (e) => { e.preventDefault(); const text = $('#rule-text').value.trim(); if (!text) return; const r = await fetch('/api/rules', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }), }).then((x) => x.json()); const hint = $('#rule-hint'); hint.className = 'hint ' + (r.ok ? 'ok' : 'bad'); hint.textContent = r.ok ? 'applied' : (r.error || 'failed'); if (r.ok) $('#rule-text').value = ''; refresh(); }; $('#cfg-load').onclick = () => loadConfig(false); $('#cfg-save').onclick = async () => { const hint = $('#cfg-hint'); hint.className = 'hint'; hint.textContent = 'validating…'; const r = await fetch('/api/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: $('#config').value }), }).then((x) => x.json()); hint.className = 'hint ' + (r.ok ? 'ok' : 'bad'); hint.textContent = r.ok ? 'saved and applied' : (r.error || 'rejected'); if (r.ok) loadConfig(true); refresh(); }; const cfg = $('#config'); if (cfg) { cfg.addEventListener('input', syncConfigHighlight); cfg.addEventListener('scroll', syncConfigHighlight); } window.addEventListener('resize', () => { renderCharts(); syncConfigHighlight(); }); const mcpUrl = $('#mcp-url'); if (mcpUrl) mcpUrl.textContent = `${location.origin.replace(/:\d+$/, '')}:8090/mcp`; refresh(); listen(); loadConfig(true); setInterval(refresh, 5000);