#!/usr/bin/env node 'use strict'; /* * junction dashboard — Node, no dependencies. * * 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 (or JUNCTION_TCP=127.0.0.1:8091) * DASH_PORT=8092 DASH_BIND=0.0.0.0 DASH_TOKEN=… */ const http = require('http'); const net = require('net'); const fs = require('fs'); const path = require('path'); const SOCKET = process.env.JUNCTION_SOCKET || '/run/junction/control.sock'; const TCP = process.env.JUNCTION_TCP || ''; 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 minutes at 1 s const HISTORY_FILE = process.env.HISTORY_FILE || '/var/lib/junction-dashboard/history.json'; /* ------------------------------------------------------------------ Channel */ let sock = null; let queue = []; let pending = null; let buffer = ''; function connect() { const [host, port] = TCP ? TCP.split(':') : []; sock = TCP ? net.connect(Number(port), host) : net.connect(SOCKET); sock.setEncoding('utf8'); sock.on('connect', () => { console.log(`connected to junction via ${TCP || SOCKET}`); }); sock.on('data', (chunk) => { buffer += chunk; let nl; while ((nl = buffer.indexOf('\n')) >= 0) { const line = buffer.slice(0, nl); buffer = buffer.slice(nl + 1); if (!pending) continue; const done = pending; pending = null; try { done.resolve(JSON.parse(line)); } catch (e) { done.reject(new Error('unreadable response: ' + line.slice(0, 120))); } pump(); } }); sock.on('error', (err) => { console.error('control channel:', err.message); }); sock.on('close', () => { console.error('control channel closed, retrying in 2 s'); if (pending) { pending.reject(new Error('channel closed')); pending = null; } setTimeout(connect, 2000); }); } function pump() { if (pending || !sock || sock.destroyed || queue.length === 0) return; const { payload, resolve, reject } = queue.shift(); pending = { resolve, reject }; sock.write(JSON.stringify(payload) + '\n'); } function ask(payload, timeoutMs = 8000) { return new Promise((resolve, reject) => { const entry = { payload, resolve, reject }; queue.push(entry); const timer = setTimeout(() => { queue = queue.filter((q) => q !== entry); reject(new Error('timeout')); }, timeoutMs); const wrapResolve = (v) => { clearTimeout(timer); resolve(v); }; const wrapReject = (e) => { clearTimeout(timer); reject(e); }; entry.resolve = wrapResolve; entry.reject = wrapReject; pump(); }); } /* ------------------------------------------------------------------ History */ const series = { t: [], requests: [], failed: [], tokensIn: [], tokensOut: [], latency: [], traffic: [], cost: [], }; let last = null; function loadHistory() { try { const raw = JSON.parse(fs.readFileSync(HISTORY_FILE, 'utf8')); if (raw && raw.series) { for (const key of Object.keys(series)) { if (Array.isArray(raw.series[key])) series[key] = raw.series[key].slice(-HISTORY); } } if (raw && raw.last) last = raw.last; const n = (series.t || []).length; console.log(`history loaded: ${n} samples`); } catch (e) { if (e.code !== 'ENOENT') console.error('history not readable:', e.message); } } let saveTimer = null; function saveHistory() { const payload = JSON.stringify({ saved: Date.now(), series, last }); try { fs.mkdirSync(path.dirname(HISTORY_FILE), { recursive: true }); const tmp = HISTORY_FILE + '.new'; fs.writeFileSync(tmp, payload); fs.renameSync(tmp, HISTORY_FILE); } catch (e) { console.error('history not writable:', e.message); } } function scheduleSave() { if (saveTimer) return; saveTimer = setTimeout(() => { saveTimer = null; saveHistory(); }, 5000); } function sample(status) { const now = Date.now(); const reqs = status.requests || {}; const tok = status.usage || {}; const lat = status.latency || {}; const traf = status.traffic || {}; const row = { t: now, requests: reqs.ok ?? 0, failed: reqs.fail ?? 0, tokensIn: tok.tokens_in ?? 0, tokensOut: tok.tokens_out ?? 0, latency: lat.avg_ms ?? -1, traffic: (traf.request_bytes ?? 0), cost: tok.cost_usd ?? 0, }; const d = (cur, prev) => (last === null ? 0 : Math.max(0, cur - prev)); const dt = last ? (now - last.t) / 1000 : 1; push('t', now); push('requests', d(row.requests, last && last.requests) / dt); push('failed', d(row.failed, last && last.failed) / dt); push('tokensIn', d(row.tokensIn, last && last.tokensIn) / dt); push('tokensOut', d(row.tokensOut, last && last.tokensOut) / dt); push('latency', row.latency); push('traffic', d(row.traffic, last && last.traffic) / dt); push('cost', d(row.cost, last && last.cost) / dt); last = row; scheduleSave(); } function push(key, value) { const arr = series[key]; arr.push(value); if (arr.length > HISTORY) arr.shift(); } /* ------------------------------------------------------------------ HTTP */ const MIME = { '.html': 'text/html; charset=utf-8', '.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') { res.writeHead(code, { 'Content-Type': type, 'Cache-Control': 'no-store' }); res.end(body); } function authorized(req) { if (!TOKEN) return true; const h = req.headers.authorization || ''; const q = new URL(req.url, 'http://x').searchParams.get('token') || ''; return h === `Bearer ${TOKEN}` || q === TOKEN; } function body(req) { return new Promise((resolve, reject) => { let data = ''; req.on('data', (c) => { data += c; if (data.length > 4 * 1024 * 1024) reject(new Error('too large')); }); req.on('end', () => { try { resolve(data ? JSON.parse(data) : {}); } catch (e) { reject(e); } }); req.on('error', reject); }); } const sseClients = new Set(); async function snapshot() { try { const r = await ask({ cmd: 'status' }); if (r.ok && r.status) { sample(r.status); return { ok: true, status: r.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) => { try { const url = new URL(req.url, 'http://x'); 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 === '/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' })); } }); setInterval(async () => { const snap = await snapshot(); if (sseClients.size === 0) return; const [rules, tools] = await Promise.all([ ask({ cmd: 'rules.list' }).catch(() => ({ rules: [] })), ask({ cmd: 'mcp.tools' }, 15000).catch(() => ({ tools: [] })), ]); 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); } } }, SAMPLE_MS); loadHistory(); connect(); server.listen(PORT, BIND, () => { console.log(`Dashboard listening on http://${BIND}:${PORT}`); }); for (const sig of ['SIGTERM', 'SIGINT']) { process.on(sig, () => { saveHistory(); process.exit(0); }); }