dashboard: Konfigurationseditor mit Junction-Syntax, Oberfläche auf Englisch

- 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.
This commit is contained in:
Hermes committed 2026-11-15 21:27:42 +00:00
1 parent f94420ccc9
commit 0427e03ff5
6 files changed
+560 -289

No files matched your search

+83
View File
@@ -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 "\<https\?://\f\+"
hi def link junctionComment Comment
hi def link junctionString String
hi def link junctionBlock Structure
hi def link junctionName Identifier
hi def link junctionKeyword Keyword
hi def link junctionRule Statement
hi def link junctionCondition Conditional
hi def link junctionCheckValue Constant
hi def link junctionSpecial Special
hi def link junctionProperty Type
hi def link junctionBoolean Boolean
hi def link junctionBalance Constant
hi def link junctionKind Constant
hi def link junctionNumber Number
hi def link junctionOperator Operator
hi def link junctionPath Underlined
hi def link junctionUrl Underlined
let b:current_syntax = "junction"
+53
View File
@@ -147,3 +147,56 @@ textarea {
}
.tool b { color: var(--accent); font-weight: 600; }
.tool span { color: var(--dim); }
/* Config editor with syntax highlighting (overlay) */
.editor-wrap {
position: relative;
min-height: 360px;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--card-2);
overflow: hidden;
}
.config-layer {
margin: 0;
padding: 12px;
border: 0;
width: 100%;
min-height: 360px;
font: 13px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
tab-size: 2;
white-space: pre;
overflow: auto;
box-sizing: border-box;
}
#config-hl {
position: absolute;
inset: 0;
color: var(--text);
pointer-events: none;
}
#config {
position: relative;
background: transparent;
color: transparent;
caret-color: var(--text);
resize: vertical;
outline: none;
}
#config::selection { background: rgba(106,169,255,0.35); }
.tok-cmt { color: #6b7a90; font-style: italic; }
.tok-str { color: #9bd36b; }
.tok-kw { color: #6aa9ff; font-weight: 600; }
.tok-bool{ color: #ffb454; }
.tok-num { color: #d7a8ff; }
.tok-op { color: #8fa3bf; }
.tok-path,.tok-url { color: #45d19a; }
@media (prefers-color-scheme: light) {
.tok-cmt { color: #6d7684; }
.tok-str { color: #2f7d32; }
.tok-kw { color: #1f5fbf; }
.tok-bool{ color: #a85a00; }
.tok-num { color: #7a3db8; }
.tok-op { color: #5c6f8a; }
.tok-path,.tok-url { color: #0b7a5a; }
}
+171 -106
View File
@@ -1,7 +1,7 @@
'use strict';
/* Zeichnet, was der Server schickt. Keine Bibliothek: drei Diagrammarten reichen,
* und eine Kurve von Hand zu zeichnen ist weniger Code als das Einbinden einer
* Chart-Bibliothek — und funktioniert ohne Netz. */
/* 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))
@@ -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
? '<span class="tag paused">pausiert</span>'
const st = ep.paused
? '<span class="tag paused">paused</span>'
: (ep.offline_s > 0
? `<span class="tag bad">offline ${ep.offline_s}s</span>`
: (ep.exhausted ? '<span class="tag bad">erschöpft</span>' : '<span class="tag ok">bereit</span>'));
: (ep.exhausted ? '<span class="tag bad">exhausted</span>' : '<span class="tag ok">ready</span>'));
tr.innerHTML = `
<td>${escapeHtml(ep.name)}<br><span class="muted" style="font-size:11px">${escapeHtml(ep.kind || '')}</span></td>
<td>${state}</td>
<td>${st}</td>
<td class="num">${fmt(ep.ok)}</td>
<td class="num">${fmt(ep.fail)}</td>
<td class="num">${fmt(ep.inflight)}</td>
<td class="num">${fmt(ep.last_ms)}</td>
<td class="num"><button class="ghost" data-ep="${escapeHtml(ep.name)}" data-act="${ep.paused ? 'resume' : 'pause'}">${ep.paused ? 'aufnehmen' : 'pausieren'}</button></td>`;
<td class="num"><button class="ghost" data-ep="${escapeHtml(ep.name)}" data-act="${ep.paused ? 'resume' : 'pause'}">${ep.paused ? 'resume' : 'pause'}</button></td>`;
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
? '<span class="tag">aus</span>'
const st = !m.enabled
? '<span class="tag">off</span>'
: (m.fail > 0 && m.tools === 0
? `<span class="tag bad">${escapeHtml(m.last_error || 'keine Antwort')}</span>`
: '<span class="tag ok">erreichbar</span>');
? `<span class="tag bad">${escapeHtml(m.last_error || 'unreachable')}</span>`
: '<span class="tag ok">reachable</span>');
tr.innerHTML = `
<td>${escapeHtml(m.name)}</td>
<td class="muted" style="font-size:12px">${escapeHtml(m.url)}</td>
<td class="muted" style="font-size:12px">${escapeHtml(m.url || m.cmd || '')}</td>
<td class="num">${fmt(m.tools)}</td>
<td class="num">${fmt(m.ok)}</td>
<td class="num">${fmt(m.fail)}</td>
<td>${state}</td>`;
<td>${st}</td>`;
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 = `<span>${escapeHtml(server)}</span> <b>${escapeHtml(short)}</b>`;
@@ -242,14 +232,14 @@ function renderVkeys() {
<td class="num">${k.budget_usd > 0 ? '$' + k.budget_usd.toFixed(2) : '—'}</td>
<td class="num">$${(k.spent_usd || 0).toFixed(4)}</td>
<td class="num">${fmt(k.hits)}</td>
<td class="num">${fmt(k.denied)}${over ? ' <span class="tag bad">erschöpft</span>' : ''}</td>`;
<td class="num">${fmt(k.denied)}${over ? ' <span class="tag bad">exhausted</span>' : ''}</td>`;
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) =>
`<span class="tool">${escapeHtml(m.model)} · $${m.cost_usd.toFixed(4)} · ${fmt(m.requests)}</span>`).join(' ');
box.innerHTML = `<b>${escapeHtml(sp.month)}</b>: $${sp.total_usd.toFixed(4)}`
+ ` über ${fmt(sp.requests)} Anfragen` + (models ? '<br>' + models : '');
`<span class="tool">${escapeHtml(m.model)} · $${(m.cost_usd || 0).toFixed(4)} · ${fmt(m.requests)}</span>`).join(' ');
box.innerHTML = `<b>${escapeHtml(sp.month || '')}</b>: $${(sp.total_usd || 0).toFixed(4)}`
+ ` over ${fmt(sp.requests)} requests` + (models ? '<br>' + 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) {
<td>${r.block ? '<span class="tag bad">block</span>' : escapeHtml(r.targets || '')}</td>
<td class="num">${need}</td>
<td class="num">${ctx}</td>
<td class="num"><button class="ghost" data-rule="${r.index ?? i}">löschen</button></td>`;
<td class="num"><button class="ghost" data-rule="${r.index ?? i}">delete</button></td>`;
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 = `
<td class="muted">${when}</td>
<td>${escapeHtml(l.model || '—')}</td>
@@ -326,20 +312,16 @@ async function loadRequests() {
<td class="num">${bad ? '<span class="tag bad">' + l.status + '</span>' : (l.status || '—')}</td>
<td class="num">${l.latency_ms ?? '—'}</td>
<td>${escapeHtml(l.cache || '—')}</td>
<td class="num">${fmt(l.tokens_in)}/${fmt(l.tokens_out)}</td>
<td class="num">${(l.cost_usd || 0).toFixed(6)}</td>`;
<td class="num">${tin}/${tout}</td>
<td class="num">${cost.toFixed(6)}</td>`;
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) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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 += `<span class="tok-cmt">${esc(line.slice(j))}</span>`;
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 += `<span class="tok-str">${esc(line.slice(j, k))}</span>`;
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 += `<span class="tok-op">${esc(ch)}</span>`; 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 += `<span class="${cls}">${esc(core)}</span>`; else out += esc(core);
if (suffix) out += `<span class="tok-op">${esc(suffix)}</span>`;
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);
+43 -38
View File
@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="de">
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
@@ -14,113 +14,118 @@
<span class="sub" id="uptime">—</span>
</div>
<div class="numbers">
<div class="n"><b id="n-req">—</b><span>Anfragen/s</span></div>
<div class="n"><b id="n-tok">—</b><span>Token/s</span></div>
<div class="n"><b id="n-lat">—</b><span>Latenz</span></div>
<div class="n"><b id="n-cost">—</b><span>Kosten/h</span></div>
<div class="n"><b id="n-fail">—</b><span>Fehler</span></div>
<div class="n"><b id="n-req">—</b><span>Requests/s</span></div>
<div class="n"><b id="n-tok">—</b><span>Tokens/s</span></div>
<div class="n"><b id="n-lat">—</b><span>Latency</span></div>
<div class="n"><b id="n-cost">—</b><span>Cost/h</span></div>
<div class="n"><b id="n-fail">—</b><span>Errors</span></div>
</div>
</header>
<main>
<section class="card wide">
<h2>Durchsatz <small id="c-req"></small></h2>
<h2>Throughput <small id="c-req"></small></h2>
<canvas id="g-requests" height="140"></canvas>
</section>
<section class="card wide">
<h2>Token <small id="c-tok"></small></h2>
<h2>Tokens <small id="c-tok"></small></h2>
<canvas id="g-tokens" height="140"></canvas>
</section>
<section class="card">
<h2>Latenz</h2>
<h2>Latency</h2>
<canvas id="g-latency" height="120"></canvas>
</section>
<section class="card">
<h2>Anfragedaten</h2>
<h2>Request data</h2>
<canvas id="g-traffic" height="120"></canvas>
</section>
<section class="card wide" id="eps">
<h2>Endpunkte</h2>
<h2>Endpoints</h2>
<table id="t-eps">
<thead><tr>
<th>Name</th><th>Zustand</th><th class="num">ok</th><th class="num">Fehler</th>
<th class="num">laufend</th><th class="num">letzte ms</th><th></th>
<th>Name</th><th>State</th><th class="num">ok</th><th class="num">Errors</th>
<th class="num">inflight</th><th class="num">last ms</th><th></th>
</tr></thead>
<tbody></tbody>
</table>
</section>
<section class="card wide">
<h2>MCP-Server <small id="c-mcp"></small></h2>
<h2>MCP Servers <small id="c-mcp"></small></h2>
<table id="t-mcp">
<thead><tr>
<th>Name</th><th>Adresse</th><th class="num">Werkzeuge</th>
<th class="num">Abrufe</th><th class="num">Fehler</th><th>zuletzt</th>
<th>Name</th><th>Address</th><th class="num">Tools</th>
<th class="num">Fetches</th><th class="num">Errors</th><th>Last</th>
</tr></thead>
<tbody></tbody>
</table>
<p class="hint" id="mcp-hint">Ein Agent verbindet sich mit <code id="mcp-url">/mcp</code>
und sieht alle Werkzeuge unten — mit dem Servernamen als Präfix.</p>
<p class="hint" id="mcp-hint">An agent connects to <code id="mcp-url">/mcp</code>
and sees all tools below — with the server name as prefix.</p>
<div id="mcp-tools" class="tools"></div>
</section>
<section class="card wide">
<h2>Schlüssel &amp; Monat <small id="c-spend"></small></h2>
<h2>Keys &amp; Month <small id="c-spend"></small></h2>
<table id="t-vkeys">
<thead><tr>
<th>Schlüssel</th><th>Modelle</th><th class="num">rpm</th>
<th class="num">Budget</th><th class="num">verbraucht</th>
<th class="num">Anfragen</th><th class="num">abgelehnt</th>
<th>Key</th><th>Models</th><th class="num">rpm</th>
<th class="num">Budget</th><th class="num">spent</th>
<th class="num">Requests</th><th class="num">denied</th>
</tr></thead>
<tbody></tbody>
</table>
<div id="spend-detail" class="tools"></div>
<p class="hint">Kosten aus dem Spend-Log, nicht geschätzt. Ein Schlüssel ohne Grenze
steht mit 0 — das heißt „kein Limit“, nicht „unbekannt“.</p>
<p class="hint">Costs come from the spend log, not estimates. A key without a limit
shows 0 — meaning “no limit”, not “unknown”.</p>
</section>
<section class="card wide">
<h2>Letzte Anfragen <small id="req-stats"></small></h2>
<h2>Recent Requests <small id="req-stats"></small></h2>
<table id="t-req">
<thead><tr>
<th>Zeit</th><th>Modell</th><th>Ziel</th><th class="num">Status</th>
<th class="num">ms</th><th>Cache</th><th class="num">ein/aus</th><th class="num">$</th>
<th>Time</th><th>Model</th><th>Target</th><th class="num">Status</th>
<th class="num">ms</th><th>Cache</th><th class="num">in/out</th><th class="num">$</th>
</tr></thead>
<tbody></tbody>
</table>
<p class="hint">Eine Zeile je bedienter Anfrage aus dem Anfrage-Log. <b>p95</b> und
<b>Trefferquote</b> gelten für die angezeigten Zeilen, nicht für den ganzen Tag —
was nicht im Log steht, wird hier nicht behauptet.</p>
<p class="hint">One row per served request from the request log. <b>p95</b> and
<b>hit rate</b> apply to the displayed rows, not the whole day — what is not in
the log is not claimed here.</p>
</section>
<section class="card wide">
<h2>Regeln <small id="c-rules"></small></h2>
<h2>Rules <small id="c-rules"></small></h2>
<table id="t-rules">
<thead><tr>
<th class="num">#</th><th>Modell</th><th>Pfad</th><th>Ziel</th>
<th class="num">#</th><th>Model</th><th>Path</th><th>Target</th>
<th class="num">need</th><th class="num">ctx</th><th></th>
</tr></thead>
<tbody></tbody>
</table>
<form id="f-rule">
<input id="rule-text" placeholder='neue Regel, z.B. req for "deepseek-*" pass cloud'>
<button type="submit">setzen</button>
<input id="rule-text" placeholder='new rule, e.g. req for "deepseek-*" pass cloud'>
<button type="submit">set</button>
</form>
<p class="hint" id="rule-hint"></p>
</section>
<section class="card wide">
<h2>Konfiguration <small>wird beim Speichern sofort übernommen</small></h2>
<textarea id="config" spellcheck="false"></textarea>
<h2>Configuration <small>applied immediately on save</small></h2>
<div class="editor-wrap">
<pre id="config-hl" aria-hidden="true" class="config-layer"></pre>
<textarea id="config" spellcheck="false" class="config-layer"></textarea>
</div>
<div class="row">
<button id="cfg-load">laden</button>
<button id="cfg-save" class="primary">prüfen &amp; speichern</button>
<button id="cfg-load">reload</button>
<button id="cfg-save" class="primary">validate &amp; save</button>
<a class="hint" href="/static/junction.vim" download>Download junction.vim (Vim syntax)</a>
<span class="hint" id="cfg-hint"></span>
</div>
<p class="hint">Current configuration loads automatically. Syntax highlighting follows Junction syntax (see <code>syntax/junction.vim</code>).</p>
</section>
</main>
+83
View File
@@ -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 "\<https\?://\f\+"
hi def link junctionComment Comment
hi def link junctionString String
hi def link junctionBlock Structure
hi def link junctionName Identifier
hi def link junctionKeyword Keyword
hi def link junctionRule Statement
hi def link junctionCondition Conditional
hi def link junctionCheckValue Constant
hi def link junctionSpecial Special
hi def link junctionProperty Type
hi def link junctionBoolean Boolean
hi def link junctionBalance Constant
hi def link junctionKind Constant
hi def link junctionNumber Number
hi def link junctionOperator Operator
hi def link junctionPath Underlined
hi def link junctionUrl Underlined
let b:current_syntax = "junction"
+127 -145
View File
@@ -1,14 +1,14 @@
#!/usr/bin/env node
'use strict';
/*
* junction dashboard — Node, ohne Abhängigkeiten.
* junction dashboard — Node, no dependencies.
*
* Es spricht über den Steuerkanal mit junction (Unix-Socket oder TCP), hält die
* letzten Minuten als Ringpuffer und zeichnet sie im Browser. Der Server rechnet
* nichts dazu: was junction nicht meldet, fehlt im Diagramm, statt als Null
* durchzugehen.
* Talks to junction over the control channel (Unix socket or TCP), keeps the last
* minutes as a ring buffer and draws them in the browser. The server adds no
* calculations: what junction does not report is missing from the chart instead of
* being shown as zero.
*
* JUNCTION_SOCKET=/run/junction/control.sock (oder JUNCTION_TCP=127.0.0.1:8091)
* JUNCTION_SOCKET=/run/junction/control.sock (or JUNCTION_TCP=127.0.0.1:8091)
* DASH_PORT=8092 DASH_BIND=0.0.0.0 DASH_TOKEN=…
*/
const http = require('http');
@@ -22,10 +22,10 @@ const PORT = Number(process.env.DASH_PORT || 8092);
const BIND = process.env.DASH_BIND || '0.0.0.0';
const TOKEN = process.env.DASH_TOKEN || '';
const SAMPLE_MS = Number(process.env.SAMPLE_MS || 1000);
const HISTORY = Number(process.env.HISTORY || 900); // 15 Minuten bei 1 s
const HISTORY = Number(process.env.HISTORY || 900); // 15 minutes at 1 s
const HISTORY_FILE = process.env.HISTORY_FILE || '/var/lib/junction-dashboard/history.json';
/* ------------------------------------------------------------------ Kanal */
/* ------------------------------------------------------------------ Channel */
let sock = null;
let queue = [];
@@ -40,7 +40,7 @@ function connect() {
sock.setEncoding('utf8');
sock.on('connect', () => {
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); });
}