From 0427e03ff5df3089717d7d84b0da762b1875fd8c Mon Sep 17 00:00:00 2001 From: Hermes Date: Sun, 15 Nov 2026 21:27:42 +0000 Subject: [PATCH] =?UTF-8?q?dashboard:=20Konfigurationseditor=20mit=20Junct?= =?UTF-8?q?ion-Syntax,=20Oberfl=C3=A4che=20auf=20Englisch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Der Konfigurationstext bekommt eine Highlight-Ebene; die Vim-Syntax liegt unter syntax/ und wird als /static/junction.vim zum Download ausgeliefert. - UI-Texte und Kommentare sind auf Englisch (Repo-Konvention). - Snapshot, Requests, Spend und Config laufen über die vorhandenen Kontrollbefehle; /api/stream hält die Anzeige aktuell. --- syntax/junction.vim | 83 ++++++++++++ web/public/app.css | 53 ++++++++ web/public/app.js | 277 +++++++++++++++++++++++++--------------- web/public/index.html | 81 ++++++------ web/public/junction.vim | 83 ++++++++++++ web/server.js | 272 ++++++++++++++++++--------------------- 6 files changed, 560 insertions(+), 289 deletions(-) create mode 100644 syntax/junction.vim create mode 100644 web/public/junction.vim diff --git a/syntax/junction.vim b/syntax/junction.vim new file mode 100644 index 0000000..d350dfe --- /dev/null +++ b/syntax/junction.vim @@ -0,0 +1,83 @@ +" Vim syntax file +" Language: Junction router config (pf.conf-style) +" Maintainer: Junction +" Usage: put in ~/.vim/syntax/junction.vim and add to ftdetect: +" au BufRead,BufNewFile junction.conf,*.junction.conf set filetype=junction + +if exists("b:current_syntax") + finish +endif + +syn case match + +" Comments +syn match junctionComment "#.*$" contains=@Spell + +" Strings +syn region junctionString start=+"+ skip=+\\"+ end=+"+ oneline +syn region junctionString start=+'+ skip=+\\'+ end=+'+ oneline + +" Blocks +syn keyword junctionBlock endpoint pool vkey mcp nextgroup=junctionName skipwhite +syn match junctionName "\<[A-Za-z0-9_.:-]\+\>" contained + +" Top-level and rule keywords +syn keyword junctionKeyword listen connect_timeout_ms offline_hold_s max_body_bytes +syn keyword junctionKeyword max_inflight queue_timeout retry_num retry_backoff retry_max_wait +syn keyword junctionKeyword offline_wait spend_log guard request log_prefix +syn keyword junctionKeyword cache_ttl cache_entries cache_bytes cache tcp cache_secret_env cache_peer cache_peer_timeout_ms +syn keyword junctionKeyword so_reuseport drain_timeout mcp_auth auto_endpoints +syn keyword junctionKeyword probe_interval probe_timeout ctx_chars_per_token prices_path +syn keyword junctionKeyword metrics control control_unix control_tcp +syn keyword junctionKeyword balance compress compress_keep compress_min_bytes +syn keyword junctionKeyword mcp_cache_ttl cache_deterministic_only + +" Rule directives +syn keyword junctionRule req pass block +syn keyword junctionCondition for path need check retry ctx vision strip as +syn keyword junctionCheckValue hooks none +syn keyword junctionSpecial on_hard on_soft skip delay + +" Endpoint/block properties +syn keyword junctionProperty base kind context priority timeout idle_timeout cooldown +syn keyword junctionProperty hook hook_retry hook_backoff wake api_key_env +syn keyword junctionProperty auth_basic_user pass_cmd base_cmd usage_cmd usage_poll_s +syn keyword junctionProperty budget_soft budget_hard on_soft_delay_s on_hard_skip +syn keyword junctionProperty offpeak_from offpeak_to cost_weight +syn keyword junctionProperty tls_verify tls_ca cache_on header vision max_model_inflight probe_on +syn keyword junctionProperty connect_timeout_ms weight compress +syn keyword junctionProperty url cmd headers timeout_s retry_ms enabled +syn keyword junctionProperty token_env allow endpoints mcp_tools rpm budget_usd budget + +" Booleans / values +syn keyword junctionBoolean on off true false auto all none +syn keyword junctionBalance first round-robin least-usage cost +syn keyword junctionKind remote local opencode-go opencode + +" Numbers, durations, sizes, percents +syn match junctionNumber "\<\d\+\(\.\d\+\)\=\>" +syn match junctionOperator "[{},=<>*]" + +" Paths/URLs (simple heuristic) +syn match junctionPath "\(^\|\s\)\zs/\f\+" +syn match junctionUrl "\ document.querySelector(sel); const fmt = (v, d = 0) => (v === null || v === undefined || Number.isNaN(v)) @@ -11,35 +11,35 @@ function css(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); } -/* ------------------------------------------------------------------ Zeichnen */ +/* ------------------------------------------------------------------ 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(Number(canvas.getAttribute('height')) * 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: Number(canvas.getAttribute('height')) }; + return { ctx, w: rect.width, h: hAttr }; } -/* Mehrere Reihen übereinander, gemeinsame Skala. Flächen statt Linien: der - * Verlauf zeigt die Menge, die Linie die Bewegung. */ function drawSeries(canvas, rows, opts = {}) { - const { ctx, w, h } = setup(canvas); + 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); + 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; + 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); - - // Gitter ctx.strokeStyle = css('--line'); ctx.globalAlpha = 0.5; ctx.lineWidth = 1; @@ -55,15 +55,14 @@ function drawSeries(canvas, rows, opts = {}) { const xOf = (i) => pad.l + (iw * i) / Math.max(1, maxLen - 1); const yOf = (v) => pad.t + ih - (ih * Math.min(v, max)) / max; - // gestapelt zeichnen: unten die erste Reihe - let baseline = rows.map(() => pad.t + ih); for (let ri = 0; ri < rows.length; ri++) { const row = rows[ri]; - const n = row.values.length; + const vals = row.values || []; + const n = vals.length; if (!n) continue; ctx.beginPath(); - ctx.moveTo(xOf(0), yOf(row.values[0])); - for (let i = 1; i < n; i++) ctx.lineTo(xOf(i), yOf(row.values[i])); + 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(); @@ -78,55 +77,48 @@ function drawSeries(canvas, rows, opts = {}) { ctx.fill(); } - // Höchstwert als Zahl in der Ecke 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); } -/* ------------------------------------------------------------------ Zustand */ +/* ------------------------------------------------------------------ State */ let status = null; let series = null; function state() { const s = status || {}; - const reqs = s.requests || {}; - const usage = s.usage || {}; - const lat = s.latency || {}; - return { reqs, usage, lat }; + 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, usage, lat } = state(); + const { reqs, lat } = state(); const ser = series || {}; const lastOf = (k) => { - const a = (ser[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` : '—'; - $('#n-cost').textContent = (() => { - const c = lastOf('cost'); - return c === null ? '—' : `${fmt(c * 3600, 3)} $`; - })(); + 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 ? '—' : `läuft ${duration(up)}`; - - const dot = $('#state'); - dot.className = 'dot ' + (status ? 'live' : 'dead'); -} - -function duration(s) { - 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`; + $('#uptime').textContent = up === null ? '—' : `up ${duration(up)}`; + $('#state').className = 'dot ' + (status ? 'live' : 'dead'); } function renderCharts() { @@ -135,7 +127,7 @@ function renderCharts() { { values: series.requests || [] }, { values: series.failed || [] }, ], { unit: '/s', digits: 2, colors: [css('--accent'), css('--bad')] }); - $('#c-req').textContent = `jetzt ${fmt((series.requests || []).slice(-1)[0], 2)}/s · Fehler ${fmt((series.failed || []).slice(-1)[0], 2)}/s`; + $('#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 || [] }, @@ -143,7 +135,7 @@ function renderCharts() { ], { 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 = `ein ${fmt(ti)}/s · aus ${fmt(to)}/s`; + $('#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')] }); @@ -157,19 +149,19 @@ function renderEndpoints() { body.innerHTML = ''; for (const ep of eps) { const tr = document.createElement('tr'); - const state = ep.paused - ? 'pausiert' + const st = ep.paused + ? 'paused' : (ep.offline_s > 0 ? `offline ${ep.offline_s}s` - : (ep.exhausted ? 'erschöpft' : 'bereit')); + : (ep.exhausted ? 'exhausted' : 'ready')); tr.innerHTML = ` ${escapeHtml(ep.name)}
${escapeHtml(ep.kind || '')} - ${state} + ${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]')) { @@ -180,7 +172,6 @@ function renderEndpoints() { } } - function renderMcp(servers, tools) { const body = $('#t-mcp tbody'); if (!body) return; @@ -188,37 +179,36 @@ function renderMcp(servers, tools) { const list = servers || []; const toolList = tools || []; $('#c-mcp').textContent = list.length - ? `${list.length} angebunden · ${toolList.length} Werkzeuge` - : 'keiner angebunden'; + ? `${list.length} connected · ${toolList.length} tools` + : 'none connected'; for (const m of list) { const tr = document.createElement('tr'); - const state = !m.enabled - ? 'aus' + const st = !m.enabled + ? 'off' : (m.fail > 0 && m.tools === 0 - ? `${escapeHtml(m.last_error || 'keine Antwort')}` - : 'erreichbar'); + ? `${escapeHtml(m.last_error || 'unreachable')}` + : 'reachable'); tr.innerHTML = ` ${escapeHtml(m.name)} - ${escapeHtml(m.url)} + ${escapeHtml(m.url || m.cmd || '')} ${fmt(m.tools)} ${fmt(m.ok)} ${fmt(m.fail)} - ${state}`; + ${st}`; body.appendChild(tr); } - // Werkzeuge nach Server gruppieren: der Präfix vor "__" ist der Server. 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; - if (seen.has(name)) continue; - seen.add(name); const el = document.createElement('span'); el.className = 'tool'; el.innerHTML = `${escapeHtml(server)} ${escapeHtml(short)}`; @@ -242,14 +232,14 @@ function renderVkeys() { ${k.budget_usd > 0 ? '$' + k.budget_usd.toFixed(2) : '—'} $${(k.spent_usd || 0).toFixed(4)} ${fmt(k.hits)} - ${fmt(k.denied)}${over ? ' erschöpft' : ''}`; + ${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} Schlüssel${refused ? ' · ' + refused + ' vom Wächter abgelehnt' : ''}` - : 'keine virtuellen Schlüssel'; + ? `${keys.length} keys${refused ? ' · ' + refused + ' refused by guard' : ''}` + : 'no virtual keys'; } async function loadSpend() { @@ -257,28 +247,22 @@ async function loadSpend() { if (!box) return; try { const r = await fetch('/api/spend').then((x) => x.json()); - if (!r.ok || !r.spend) { - box.textContent = r.error || 'keine Auskunft'; - return; - } + if (!r.ok || !r.spend) { box.textContent = r.error || 'no data'; return; } const sp = r.spend; - if (sp.error) { - box.textContent = sp.error; - return; - } + if (sp.error) { box.textContent = sp.error; return; } const models = (sp.models || []).map((m) => - `${escapeHtml(m.model)} · $${m.cost_usd.toFixed(4)} · ${fmt(m.requests)}`).join(' '); - box.innerHTML = `${escapeHtml(sp.month)}: $${sp.total_usd.toFixed(4)}` - + ` über ${fmt(sp.requests)} Anfragen` + (models ? '
' + models : ''); + `${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 = 'keine Auskunft'; + box.textContent = 'no data'; } } function renderRules(rules) { const body = $('#t-rules tbody'); body.innerHTML = ''; - $('#c-rules').textContent = `${rules.length} aktiv`; + $('#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}` : ''] @@ -292,7 +276,7 @@ function renderRules(rules) { ${r.block ? 'block' : escapeHtml(r.targets || '')} ${need} ${ctx} - `; + `; body.appendChild(tr); }); for (const btn of body.querySelectorAll('button[data-rule]')) { @@ -311,14 +295,16 @@ async function loadRequests() { const lines = (r.ok && r.requests && r.requests.lines) || []; body.innerHTML = ''; if (!lines.length) { - const stats = $('#req-stats'); - if (stats) stats.textContent = (r.error || 'noch keine Anfragen im Log'); + $('#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 || '—')} @@ -326,20 +312,16 @@ async function loadRequests() { ${bad ? '' + l.status + '' : (l.status || '—')} ${l.latency_ms ?? '—'} ${escapeHtml(l.cache || '—')} - ${fmt(l.tokens_in)}/${fmt(l.tokens_out)} - ${(l.cost_usd || 0).toFixed(6)}`; + ${tin}/${tout} + ${cost.toFixed(6)}`; body.appendChild(tr); } - /* p95 und Trefferquote über genau diese Zeilen — nicht über den Tag. */ 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; - const stats = $('#req-stats'); - if (stats) stats.textContent = - `${lines.length} Anfragen · p95 ${p95} ms · Trefferquote ${Math.round(hits / lines.length * 100)} %`; + $('#req-stats').textContent = `${lines.length} requests · p95 ${p95} ms · hit rate ${Math.round(hits / lines.length * 100)} %`; } catch (e) { - const stats = $('#req-stats'); - if (stats) stats.textContent = 'keine Auskunft'; + $('#req-stats').textContent = 'no data'; } } @@ -347,7 +329,93 @@ function escapeHtml(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); } -/* ------------------------------------------------------------------ Daten */ +/* ---------------------------- 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 { @@ -382,7 +450,7 @@ function listen() { renderRules(data.rules || []); renderMcp((data.status && data.status.mcp) || [], data.tools || []); renderVkeys(); - } catch (e) { /* ein kaputter Rahmen darf die Anzeige nicht anhalten */ } + } catch (e) { /* a broken frame must not stop rendering */ } }; es.onerror = () => { es.close(); @@ -390,7 +458,7 @@ function listen() { }; } -/* ------------------------------------------------------------------ Formulare */ +/* ------------------------------------------------------------------ Forms */ $('#f-rule').onsubmit = async (e) => { e.preventDefault(); @@ -403,43 +471,40 @@ $('#f-rule').onsubmit = async (e) => { }).then((x) => x.json()); const hint = $('#rule-hint'); hint.className = 'hint ' + (r.ok ? 'ok' : 'bad'); - hint.textContent = r.ok ? 'gesetzt' : (r.error || 'fehlgeschlagen'); + hint.textContent = r.ok ? 'applied' : (r.error || 'failed'); if (r.ok) $('#rule-text').value = ''; refresh(); }; -$('#cfg-load').onclick = async () => { - const r = await fetch('/api/config').then((x) => x.json()); - const hint = $('#cfg-hint'); - if (r.ok) { - $('#config').value = r.text || ''; - hint.className = 'hint ok'; - hint.textContent = 'geladen'; - } else { - hint.className = 'hint bad'; - hint.textContent = r.error || 'nicht ladbar'; - } -}; +$('#cfg-load').onclick = () => loadConfig(false); $('#cfg-save').onclick = async () => { const hint = $('#cfg-hint'); hint.className = 'hint'; - hint.textContent = 'wird geprüft …'; + 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 ? 'gespeichert und übernommen' : (r.error || 'abgelehnt'); + hint.textContent = r.ok ? 'saved and applied' : (r.error || 'rejected'); + if (r.ok) loadConfig(true); refresh(); }; -window.addEventListener('resize', () => renderCharts()); +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); diff --git a/web/public/index.html b/web/public/index.html index 6785c71..e4a3088 100644 --- a/web/public/index.html +++ b/web/public/index.html @@ -1,5 +1,5 @@ - + @@ -14,113 +14,118 @@ —
-
—Anfragen/s
-
—Token/s
-
—Latenz
-
—Kosten/h
-
—Fehler
+
—Requests/s
+
—Tokens/s
+
—Latency
+
—Cost/h
+
—Errors
-

Durchsatz

+

Throughput

-

Token

+

Tokens

-

Latenz

+

Latency

-

Anfragedaten

+

Request data

-

Endpunkte

+

Endpoints

- - + +
NameZustandokFehlerlaufendletzte msNameStateokErrorsinflightlast ms
-

MCP-Server

+

MCP Servers

- - + +
NameAdresseWerkzeugeAbrufeFehlerzuletztNameAddressToolsFetchesErrorsLast
-

Ein Agent verbindet sich mit /mcp - und sieht alle Werkzeuge unten — mit dem Servernamen als Präfix.

+

An agent connects to /mcp + and sees all tools below — with the server name as prefix.

-

Schlüssel & Monat

+

Keys & Month

- - - + + +
SchlüsselModellerpmBudgetverbrauchtAnfragenabgelehntKeyModelsrpmBudgetspentRequestsdenied
-

Kosten aus dem Spend-Log, nicht geschätzt. Ein Schlüssel ohne Grenze - steht mit 0 — das heißt „kein Limit“, nicht „unbekannt“.

+

Costs come from the spend log, not estimates. A key without a limit + shows 0 — meaning “no limit”, not “unknown”.

-

Letzte Anfragen

+

Recent Requests

- - + +
ZeitModellZielStatusmsCacheein/aus$TimeModelTargetStatusmsCachein/out$
-

Eine Zeile je bedienter Anfrage aus dem Anfrage-Log. p95 und - Trefferquote gelten für die angezeigten Zeilen, nicht für den ganzen Tag — - was nicht im Log steht, wird hier nicht behauptet.

+

One row per served request from the request log. p95 and + hit rate apply to the displayed rows, not the whole day — what is not in + the log is not claimed here.

-

Regeln

+

Rules

- +
#ModellPfadZiel#ModelPathTarget needctx
- - + +

-

Konfiguration wird beim Speichern sofort übernommen

- +

Configuration applied immediately on save

+
+ + +
- - + + + Download junction.vim (Vim syntax)
+

Current configuration loads automatically. Syntax highlighting follows Junction syntax (see syntax/junction.vim).

diff --git a/web/public/junction.vim b/web/public/junction.vim new file mode 100644 index 0000000..d350dfe --- /dev/null +++ b/web/public/junction.vim @@ -0,0 +1,83 @@ +" Vim syntax file +" Language: Junction router config (pf.conf-style) +" Maintainer: Junction +" Usage: put in ~/.vim/syntax/junction.vim and add to ftdetect: +" au BufRead,BufNewFile junction.conf,*.junction.conf set filetype=junction + +if exists("b:current_syntax") + finish +endif + +syn case match + +" Comments +syn match junctionComment "#.*$" contains=@Spell + +" Strings +syn region junctionString start=+"+ skip=+\\"+ end=+"+ oneline +syn region junctionString start=+'+ skip=+\\'+ end=+'+ oneline + +" Blocks +syn keyword junctionBlock endpoint pool vkey mcp nextgroup=junctionName skipwhite +syn match junctionName "\<[A-Za-z0-9_.:-]\+\>" contained + +" Top-level and rule keywords +syn keyword junctionKeyword listen connect_timeout_ms offline_hold_s max_body_bytes +syn keyword junctionKeyword max_inflight queue_timeout retry_num retry_backoff retry_max_wait +syn keyword junctionKeyword offline_wait spend_log guard request log_prefix +syn keyword junctionKeyword cache_ttl cache_entries cache_bytes cache tcp cache_secret_env cache_peer cache_peer_timeout_ms +syn keyword junctionKeyword so_reuseport drain_timeout mcp_auth auto_endpoints +syn keyword junctionKeyword probe_interval probe_timeout ctx_chars_per_token prices_path +syn keyword junctionKeyword metrics control control_unix control_tcp +syn keyword junctionKeyword balance compress compress_keep compress_min_bytes +syn keyword junctionKeyword mcp_cache_ttl cache_deterministic_only + +" Rule directives +syn keyword junctionRule req pass block +syn keyword junctionCondition for path need check retry ctx vision strip as +syn keyword junctionCheckValue hooks none +syn keyword junctionSpecial on_hard on_soft skip delay + +" Endpoint/block properties +syn keyword junctionProperty base kind context priority timeout idle_timeout cooldown +syn keyword junctionProperty hook hook_retry hook_backoff wake api_key_env +syn keyword junctionProperty auth_basic_user pass_cmd base_cmd usage_cmd usage_poll_s +syn keyword junctionProperty budget_soft budget_hard on_soft_delay_s on_hard_skip +syn keyword junctionProperty offpeak_from offpeak_to cost_weight +syn keyword junctionProperty tls_verify tls_ca cache_on header vision max_model_inflight probe_on +syn keyword junctionProperty connect_timeout_ms weight compress +syn keyword junctionProperty url cmd headers timeout_s retry_ms enabled +syn keyword junctionProperty token_env allow endpoints mcp_tools rpm budget_usd budget + +" Booleans / values +syn keyword junctionBoolean on off true false auto all none +syn keyword junctionBalance first round-robin least-usage cost +syn keyword junctionKind remote local opencode-go opencode + +" Numbers, durations, sizes, percents +syn match junctionNumber "\<\d\+\(\.\d\+\)\=\>" +syn match junctionOperator "[{},=<>*]" + +" Paths/URLs (simple heuristic) +syn match junctionPath "\(^\|\s\)\zs/\f\+" +syn match junctionUrl "\ { - console.log(`verbunden mit junction über ${TCP || SOCKET}`); + console.log(`connected to junction via ${TCP || SOCKET}`); }); sock.on('data', (chunk) => { buffer += chunk; @@ -54,16 +54,16 @@ function connect() { try { done.resolve(JSON.parse(line)); } catch (e) { - done.reject(new Error('unlesbare Antwort: ' + line.slice(0, 120))); + done.reject(new Error('unreadable response: ' + line.slice(0, 120))); } pump(); } }); sock.on('error', (err) => { - console.error('Steuerkanal:', err.message); + console.error('control channel:', err.message); }); sock.on('close', () => { - console.error('Steuerkanal geschlossen, neuer Versuch in 2 s'); + console.error('control channel closed, retrying in 2 s'); if (pending) { pending.reject(new Error('channel closed')); pending = null; @@ -85,7 +85,7 @@ function ask(payload, timeoutMs = 8000) { queue.push(entry); const timer = setTimeout(() => { queue = queue.filter((q) => q !== entry); - reject(new Error('Zeitüberschreitung')); + reject(new Error('timeout')); }, timeoutMs); const wrapResolve = (v) => { clearTimeout(timer); resolve(v); }; const wrapReject = (e) => { clearTimeout(timer); reject(e); }; @@ -95,7 +95,7 @@ function ask(payload, timeoutMs = 8000) { }); } -/* ------------------------------------------------------------------ Verlauf */ +/* ------------------------------------------------------------------ History */ const series = { t: [], requests: [], failed: [], tokensIn: [], tokensOut: [], @@ -103,10 +103,6 @@ const series = { }; let last = null; -/* Der Verlauf soll einen Neustart überleben: sonst steht nach jedem - * Dienst-Neustart ein Loch im Diagramm, obwohl der Router weiterlief. Gespeichert - * wird der Ringpuffer plus der letzte Zählerstand, sonst springt die Rate beim - * ersten Messpunkt nach dem Start auf den Gesamtzuwachs. */ function loadHistory() { try { const raw = JSON.parse(fs.readFileSync(HISTORY_FILE, 'utf8')); @@ -117,9 +113,9 @@ function loadHistory() { } if (raw && raw.last) last = raw.last; const n = (series.t || []).length; - console.log(`Verlauf geladen: ${n} Messpunkte`); + console.log(`history loaded: ${n} samples`); } catch (e) { - if (e.code !== 'ENOENT') console.error('Verlauf nicht lesbar:', e.message); + if (e.code !== 'ENOENT') console.error('history not readable:', e.message); } } @@ -128,11 +124,11 @@ function saveHistory() { const payload = JSON.stringify({ saved: Date.now(), series, last }); try { fs.mkdirSync(path.dirname(HISTORY_FILE), { recursive: true }); - const tmp = HISTORY_FILE + '.neu'; + const tmp = HISTORY_FILE + '.new'; fs.writeFileSync(tmp, payload); fs.renameSync(tmp, HISTORY_FILE); } catch (e) { - console.error('Verlauf nicht speicherbar:', e.message); + console.error('history not writable:', e.message); } } @@ -162,7 +158,6 @@ function sample(status) { cost: tok.cost_usd ?? 0, }; - // Raten aus den Differenzen zum letzten Messpunkt; beim ersten Mal 0. const d = (cur, prev) => (last === null ? 0 : Math.max(0, cur - prev)); const dt = last ? (now - last.t) / 1000 : 1; @@ -192,6 +187,7 @@ const MIME = { '.js': 'application/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', + '.vim': 'text/plain; charset=utf-8', }; function send(res, code, body, type = 'application/json; charset=utf-8') { @@ -211,14 +207,10 @@ function body(req) { let data = ''; req.on('data', (c) => { data += c; - if (data.length > 4 * 1024 * 1024) reject(new Error('zu groß')); + if (data.length > 4 * 1024 * 1024) reject(new Error('too large')); }); req.on('end', () => { - try { - resolve(data ? JSON.parse(data) : {}); - } catch (e) { - reject(e); - } + try { resolve(data ? JSON.parse(data) : {}); } catch (e) { reject(e); } }); req.on('error', reject); }); @@ -233,123 +225,120 @@ async function snapshot() { sample(r.status); return { ok: true, status: r.status, series }; } - return { ok: false, error: r.error || 'kein Status', series }; + return { ok: false, error: r.error || 'no status', series }; } catch (e) { return { ok: false, error: e.message, series }; } } const server = http.createServer(async (req, res) => { - const url = new URL(req.url, 'http://x'); + try { + const url = new URL(req.url, 'http://x'); + if (!authorized(req)) return send(res, 401, JSON.stringify({ error: 'unauthorized' })); - if (!authorized(req)) return send(res, 401, JSON.stringify({ error: 'unauthorized' })); + if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) { + const file = path.join(__dirname, 'public', 'index.html'); + return send(res, 200, fs.readFileSync(file), MIME['.html']); + } + if (req.method === 'GET' && url.pathname.startsWith('/static/')) { + const name = path.basename(url.pathname); + const file = path.join(__dirname, 'public', name); + if (!fs.existsSync(file)) return send(res, 404, '{}'); + return send(res, 200, fs.readFileSync(file), MIME[path.extname(file)] || 'text/plain'); + } - if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) { - const file = path.join(__dirname, 'public', 'index.html'); - return send(res, 200, fs.readFileSync(file), MIME['.html']); + if (req.method === 'GET' && url.pathname === '/api/snapshot') { + const [snap, rules, tools] = await Promise.all([ + snapshot(), + ask({ cmd: 'rules.list' }).catch((f) => ({ ok: false, error: f.message })), + ask({ cmd: 'mcp.tools' }, 15000).catch((f) => ({ ok: false, error: f.message })), + ]); + return send(res, 200, JSON.stringify({ + ...snap, + rules: rules.rules || [], + rulesError: rules.error, + tools: tools.tools || [], + })); + } + + if (req.method === 'GET' && url.pathname === '/api/requests') { + const count = url.searchParams.get('count') || '25'; + const r = await ask({ cmd: 'requests.tail', count }).catch((f) => ({ ok: false, error: f.message })); + return send(res, 200, JSON.stringify(r.ok + ? { ok: true, requests: r.requests } + : { ok: false, error: r.error || 'no data' })); + } + + if (req.method === 'GET' && url.pathname === '/api/spend') { + const month = url.searchParams.get('month') || ''; + const r = await ask({ cmd: 'spend.get', month }).catch((f) => ({ ok: false, error: f.message })); + return send(res, 200, JSON.stringify(r.ok + ? { ok: true, spend: r.spend } + : { ok: false, error: r.error || 'no data' })); + } + + if (req.method === 'GET' && url.pathname === '/api/stream') { + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-store', + Connection: 'keep-alive', + }); + res.write(': connected\n\n'); + sseClients.add(res); + req.on('close', () => sseClients.delete(res)); + return; + } + + if (req.method === 'GET' && url.pathname === '/api/mcp') { + const [st, tools] = await Promise.all([ + ask({ cmd: 'status' }).catch((f) => ({ ok: false, error: f.message })), + ask({ cmd: 'mcp.tools' }, 15000).catch((f) => ({ ok: false, error: f.message })), + ]); + return send(res, 200, JSON.stringify({ + ok: st.ok && tools.ok, + servers: (st.status && st.status.mcp) || [], + tools: tools.tools || [], + error: st.error || tools.error || null, + })); + } + + if (req.method === 'GET' && url.pathname === '/api/config') { + const r = await ask({ cmd: 'config.get' }); + return send(res, 200, JSON.stringify(r)); + } + + if (req.method === 'POST' && url.pathname === '/api/config') { + const b = await body(req); + const r = await ask({ cmd: 'config.set', text: b.text || '' }, 20000); + return send(res, 200, JSON.stringify(r)); + } + + if (req.method === 'POST' && url.pathname === '/api/rules') { + const b = await body(req); + const r = await ask({ cmd: 'rules.set', text: b.text || '' }); + return send(res, 200, JSON.stringify(r)); + } + + if (req.method === 'DELETE' && url.pathname === '/api/rules') { + const index = url.searchParams.get('index'); + const name = url.searchParams.get('name'); + const r = await ask({ cmd: 'rules.delete', index: index !== null ? Number(index) : undefined, name: name || undefined }); + return send(res, 200, JSON.stringify(r)); + } + + if (req.method === 'POST' && url.pathname.startsWith('/api/endpoint/')) { + const [, , , name, action] = url.pathname.split('/'); + const cmd = action === 'resume' ? 'endpoint.resume' : 'endpoint.pause'; + const r = await ask({ cmd, name }); + return send(res, 200, JSON.stringify(r)); + } + + send(res, 404, JSON.stringify({ error: 'not found' })); + } catch (e) { + send(res, 500, JSON.stringify({ error: e.message || 'error' })); } - if (req.method === 'GET' && url.pathname.startsWith('/static/')) { - const name = path.basename(url.pathname); - const file = path.join(__dirname, 'public', name); - if (!fs.existsSync(file)) return send(res, 404, '{}'); - return send(res, 200, fs.readFileSync(file), MIME[path.extname(file)] || 'text/plain'); - } - - if (req.method === 'GET' && url.pathname === '/api/snapshot') { - const [snap, rules, tools] = await Promise.all([ - snapshot(), - ask({ cmd: 'rules.list' }).catch((f) => ({ ok: false, error: f.message })), - ask({ cmd: 'mcp.tools' }, 15000).catch((f) => ({ ok: false, error: f.message })), - ]); - return send(res, 200, JSON.stringify({ - ...snap, - rules: rules.rules || [], - rulesError: rules.error, - tools: tools.tools || [], - })); - } - - if (req.method === 'GET' && url.pathname === '/api/requests') { - /* Die letzten Zeilen des Anfrage-Logs, über den Steuerkanal: das Dashboard liest - * keine Datei, die junction nicht auch selbst ausliefern würde. */ - const count = url.searchParams.get('count') || '25'; - const r = await ask({ cmd: 'requests.tail', count }).catch((f) => ({ ok: false, error: f.message })); - return send(res, 200, JSON.stringify(r.ok - ? { ok: true, requests: r.requests } - : { ok: false, error: r.error || 'keine Auskunft' })); - } - - if (req.method === 'GET' && url.pathname === '/api/spend') { - /* Dieselbe Auskunft wie GET /spend an junction, nur über den Steuerkanal: das - * Dashboard spricht ausschließlich mit dem Socket, nicht mit dem Modell-Port. */ - const month = url.searchParams.get('month') || ''; - const r = await ask({ cmd: 'spend.get', month }).catch((f) => ({ ok: false, error: f.message })); - return send(res, 200, JSON.stringify(r.ok - ? { ok: true, spend: r.spend } - : { ok: false, error: r.error || 'keine Auskunft' })); - } - - if (req.method === 'GET' && url.pathname === '/api/stream') { - res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-store', - Connection: 'keep-alive', - }); - res.write(': verbunden\n\n'); - sseClients.add(res); - req.on('close', () => sseClients.delete(res)); - return; - } - - if (req.method === 'GET' && url.pathname === '/api/mcp') { - const [st, tools] = await Promise.all([ - ask({ cmd: 'status' }).catch((f) => ({ ok: false, error: f.message })), - ask({ cmd: 'mcp.tools' }, 15000).catch((f) => ({ ok: false, error: f.message })), - ]); - return send(res, 200, JSON.stringify({ - ok: st.ok && tools.ok, - servers: (st.status && st.status.mcp) || [], - tools: tools.tools || [], - error: st.error || tools.error || null, - })); - } - - if (req.method === 'GET' && url.pathname === '/api/config') { - const r = await ask({ cmd: 'config.get' }); - return send(res, 200, JSON.stringify(r)); - } - - if (req.method === 'POST' && url.pathname === '/api/config') { - const b = await body(req); - const r = await ask({ cmd: 'config.set', text: b.text || '' }, 20000); - return send(res, 200, JSON.stringify(r)); - } - - if (req.method === 'POST' && url.pathname === '/api/rules') { - const b = await body(req); - const r = await ask({ cmd: 'rules.set', text: b.text || '' }); - return send(res, 200, JSON.stringify(r)); - } - - if (req.method === 'DELETE' && url.pathname === '/api/rules') { - const index = url.searchParams.get('index'); - const name = url.searchParams.get('name'); - const r = await ask({ cmd: 'rules.delete', index: index !== null ? Number(index) : undefined, name: name || undefined }); - return send(res, 200, JSON.stringify(r)); - } - - if (req.method === 'POST' && url.pathname.startsWith('/api/endpoint/')) { - const [, , , name, action] = url.pathname.split('/'); - const cmd = action === 'resume' ? 'endpoint.resume' : 'endpoint.pause'; - const r = await ask({ cmd, name }); - return send(res, 200, JSON.stringify(r)); - } - - send(res, 404, JSON.stringify({ error: 'not found' })); }); -/* ------------------------------------------------------------------ Takt */ - setInterval(async () => { const snap = await snapshot(); if (sseClients.size === 0) return; @@ -359,23 +348,16 @@ setInterval(async () => { ]); const payload = JSON.stringify({ ...snap, rules: rules.rules || [], tools: tools.tools || [] }); for (const client of sseClients) { - try { - client.write(`data: ${payload}\n\n`); - } catch (e) { - sseClients.delete(client); - } + try { client.write(`data: ${payload}\n\n`); } catch (e) { sseClients.delete(client); } } }, SAMPLE_MS); loadHistory(); connect(); server.listen(PORT, BIND, () => { - console.log(`Dashboard auf http://${BIND}:${PORT}`); + console.log(`Dashboard listening on http://${BIND}:${PORT}`); }); for (const sig of ['SIGTERM', 'SIGINT']) { - process.on(sig, () => { - saveHistory(); - process.exit(0); - }); + process.on(sig, () => { saveHistory(); process.exit(0); }); }