// Admin: KI-Leitstand – Status des Sprachmodells (Sicherung, Warteschlange, Zwecke), Verbindungstest,
// Tageszusammenfassung und Entwürfe für Ankündigungen (opsdesk.js auf dem Server).
// Alles funktioniert auch ohne Modell: Zusammenfassung und Entwürfe kommen dann aus Vorlagen.
import { api } from './net.js';
import { toast, ask } from './ui.js';
import { esc, $, int, num, when, ago, countdown, patch } from './util.js';
import { icon } from './icons.js';
import { art } from './art.js';
let ops = null; // Antwort von GET /api/admin/ops
let testRes = null; // letzter Verbindungstest
let testing = false;
const probes = new Map(); // Zweck → letztes Ergebnis des Probelaufs (neueste zuerst angezeigt)
let probing = null; // Zweck, der gerade geprüft wird
let probeQueue = []; // „Alle nacheinander“
let styleDirty = false; // Formular „Ton und Länge“ bearbeitet, noch nicht gespeichert
let kind = 'wartung';
let pollT = 0, pollN = 0, tickT = 0;
let active = () => false;
const TONE = { alert: 'Alarm', warn: 'Achtung', info: 'Info', ok: 'in Ordnung' };
const KIND_ICON = { wartung: 'wrench', saison: 'season', markt: 'market', neuerung: 'sparkles', frei: 'megaphone' };
const byBadge = (by, pending) => (pending
? 'Sprachmodell formuliert …'
: by === 'ki' ? 'KI' : 'Vorlage');
/** Aufruf aus admin.js: isActive() sagt, ob der Bereich gerade sichtbar ist */
export function initOps(isActive) { active = isActive; }
export function opsHtml() {
styleDirty = false; // Bereich wird neu aufgebaut: Formular „Ton und Länge“ zeigt wieder die gespeicherten Werte
return `
${icon('chip')} KI-Status
${ops ? statusBody() : '
Lade …
'}
${icon('today')} Tageszusammenfassung
${ops ? summaryBody() : ''}
${icon('megaphone')} Ankündigung entwerfen
${draftForm()}
${icon('target')} Probelauf
${ops ? probeBody() : ''}
${icon('wrench')} Ton und Länge
`;
}
export async function loadOps() {
try { ops = await api('/api/admin/ops'); } catch (e) { toast(e.message, 'err'); return; }
draw();
}
function draw() {
if (!ops || !$('#opsStatus')) return;
patch($('#opsStatus'), statusBody());
patch($('#opsSummary'), summaryBody());
drawDrafts();
patch($('#opsProbe'), probeBody());
drawStyle();
schedule();
}
/** Nachfragen, solange ein Modelltext aussteht (höchstens ~90 s); sonst Status alle 10 s auffrischen */
function schedule() {
clearTimeout(pollT);
if (!active()) return;
if (ops.pending && pollN < 60) { pollN++; pollT = setTimeout(loadOps, 1500); return; }
pollN = 0;
pollT = setTimeout(() => { if (active()) loadOps(); }, 10_000);
clearInterval(tickT);
if (ops.status?.breaker?.open) tickT = setInterval(() => { const el = $('#opsBreakerLeft'); if (!el || !active()) { clearInterval(tickT); return; } el.textContent = countdown(ops.status.breaker.until - Date.now()); }, 1000);
}
// ---------------------------------------------------------------- Status
function hero(st) {
if (!st.configured) return { cls: 'off', pic: 'plug', title: 'Kein Sprachmodell eingerichtet', text: 'Alle KI-Funktionen laufen mit Vorlagen aus den Spieldaten. Einrichten unter .' };
if (st.breaker.open) return { cls: 'bad', pic: 'plug', title: 'Sicherung ausgelöst – Vorlagen aktiv', text: `Nach ${int(st.breaker.fails)} Fehlschlägen in Folge ist das Modell gesperrt. Nächste Probeanfrage in ${countdown(st.breaker.until - Date.now())}.${st.breaker.lastError ? ` Letzter Fehler: ${esc(st.breaker.lastError)}.` : ''}` };
if (st.breaker.fails) return { cls: 'warn', pic: 'robot', title: `Modell ${ops.model ? `„${esc(ops.model)}“ ` : ''}antwortet unzuverlässig`, text: `${int(st.breaker.fails)} Fehlschlag${st.breaker.fails === 1 ? '' : 'e'} in Folge${st.breaker.lastError ? ` (${esc(st.breaker.lastError)})` : ''}. Die Sicherung löst bei weiteren Fehlern aus.` };
return { cls: 'ok', pic: 'robot', title: `Modell ${ops.model ? `„${esc(ops.model)}“ ` : ''}bereit`, text: 'Texte werden vom Sprachmodell formuliert; bei Ausfall springen die Vorlagen ein.' };
}
function statusBody() {
const st = ops.status;
const h = hero(st);
const t = st.totals;
const kpi = (label, v, sub = '') => `
`;
}
/** getrennte Fälle der Statistik: Prüfung abgelehnt, Antwort unbrauchbar, Ausfall */
const REJ_KIND = { abgelehnt: 'abgelehnt', unbrauchbar: 'unbrauchbar', ausfall: 'Ausfall' };
// ---------------------------------------------------------------- Probelauf
const SOURCE = { beispiel: 'Beispiel aus den aktuellen Spieldaten', letzte: 'letzte echte Anfrage dieses Zwecks' };
function probeBody() {
const ps = ops.status.purposes;
const can = ps.filter((p) => p.probe);
const head = `
Je Zweck geht eine Beispielanfrage direkt an das Modell – am Stundenbudget vorbei, ohne etwas im Spiel zu ändern. Nebeneinander stehen Vorlage, Rohantwort und das Ergebnis der Prüfung.
${probes.size ? '' : ''}
`;
if (!probes.size && !probing) return `${head}
${icon('info')} Noch kein Probelauf. Einzelne Zwecke startest du oben in der Liste unter KI-Status.
`;
const run = probing && !probes.has(probing) ? `
`}
${prompt}`;
}
async function runProbe(purpose) {
probing = purpose;
probes.delete(purpose);
draw();
let r;
try { r = await api('/api/admin/llm/probe', { method: 'POST', body: { purpose } }); if (r.status) ops.status = r.status; }
catch (e) { r = { purpose, ok: false, configured: true, error: e.message }; }
probing = null;
if (!r.busy) {
// neuestes Ergebnis zuerst
const rest = [...probes].filter(([k]) => k !== purpose);
probes.clear();
probes.set(purpose, r);
for (const [k, v] of rest) probes.set(k, v);
}
if (probeQueue.length) { runProbe(probeQueue.shift()); return; }
draw();
}
// ---------------------------------------------------------------- Ton und Länge
function drawStyle(force = false) {
const el = $('#opsStyle');
if (!el || !ops.style || (styleDirty && !force)) return;
if (!force && el.dataset.sig === JSON.stringify(ops.style)) return;
el.dataset.sig = JSON.stringify(ops.style);
el.innerHTML = styleBody();
}
function styleBody() {
const s = ops.style;
const opt = (map, v) => Object.entries(map).map(([k, l]) => ``).join('');
const rows = s.funcs.map((f) => `
${esc(f.label)}
`).join('');
return ``;
}
async function saveStyle(form) {
const game = {};
for (const el of form.querySelectorAll('select[name], input[name]')) game[el.name] = el.type === 'number' ? Number(el.value) : el.value;
try {
await api('/api/admin/settings', { method: 'PUT', body: { game } });
styleDirty = false;
toast('Ton und Länge gespeichert – gilt ab der nächsten Anfrage.', 'ok');
await loadOps();
drawStyle(true);
} catch (e) { toast(e.message, 'err'); }
}
function testHtml() {
if (!testRes) return '';
const r = testRes;
if (r.ok) return `
${icon('check')}Verbindung steht – Antwort in ${num(r.ms / 1000, 1)} s${r.model ? ` von „${esc(r.model)}“` : ''}: „${esc(r.reply)}“${r.json ? '' : ' (kein JSON – die Texte werden trotzdem geprüft)'}${r.status?.breaker?.open ? ' · Die Sicherung ist noch ausgelöst – jetzt zurücksetzen?' : ''}${r.saved ? '' : ' · Hinweis: Das Modell ist in den Einstellungen abgeschaltet.'}
`;
if (!r.configured) return `
${icon('info')}Kein Sprachmodell eingerichtet – Endpunkt und Modell unter eintragen.
`;
return `
${icon('warn')}Keine Verbindung${r.ms != null ? ` nach ${num(r.ms / 1000, 1)} s` : ''}: ${esc(r.error)}. Das Spiel läuft mit Vorlagen weiter.
`;
}
// ---------------------------------------------------------------- Tageszusammenfassung
function summaryBody() {
const s = ops.summary;
const pts = [...s.points].sort((a, b) => ['alert', 'warn', 'info', 'ok'].indexOf(a.tone) - ['alert', 'warn', 'info', 'ok'].indexOf(b.tone));
const stamp = s.preview ? 'Vorschau aus den aktuellen Kennzahlen' : `${s.auto ? 'Automatisch nach Handelsschluss' : 'Erstellt'} ${when(s.at)}`;
return `
`;
}
/** Entwürfe einzeln abgleichen, damit Bearbeitungen in fertigen Entwürfen beim Nachfragen erhalten bleiben */
function drawDrafts() {
const box = $('#opsDrafts');
if (!box) return;
const ids = new Set(ops.drafts.map((d) => String(d.id)));
for (const el of [...box.children]) if (!ids.has(el.dataset.draft)) el.remove();
let prev = null;
for (const d of ops.drafts) {
let el = box.querySelector(`[data-draft="${d.id}"]`);
if (!el) {
el = document.createElement('article');
el.className = 'ops-draft';
el.dataset.draft = String(d.id);
if (prev) prev.after(el); else box.prepend(el);
}
const sig = draftSig(d);
if (el.dataset.sig !== sig) { el.dataset.sig = sig; el.classList.toggle('is-ki', d.by === 'ki'); el.innerHTML = draftHtml(d); }
prev = el;
}
if (!ops.drafts.length) box.innerHTML = `
${icon('inbox')} Noch keine Entwürfe.
`;
else box.querySelector('.ops-empty')?.remove();
}
// ---------------------------------------------------------------- Bedienung
async function runTest() {
testing = true; draw();
try { testRes = await api('/api/admin/llm/test', { method: 'POST', body: {} }); if (testRes.status) ops.status = testRes.status; }
catch (e) { testRes = { ok: false, configured: true, error: e.message }; }
testing = false; draw();
}
/** Klicks auf data-a="ops…" aus admin.js weitergereicht */
export async function opsClick(act, a) {
if (act === 'opsReload') { testRes = null; await loadOps(); }
else if (act === 'opsTest') runTest();
else if (act === 'opsProbe') {
if (probing) return;
await runProbe(a.dataset.purpose);
const el = document.getElementById(`opsPr-${a.dataset.purpose}`);
el?.scrollIntoView({ block: 'nearest', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
} else if (act === 'opsProbeAll') {
if (probing) return;
probeQueue = ops.status.purposes.filter((p) => p.probe).map((p) => p.name);
if (probeQueue.length) runProbe(probeQueue.shift());
} else if (act === 'opsProbeClear') { probes.clear(); draw(); }
else if (act === 'opsStyleReset') { styleDirty = false; drawStyle(true); }
else if (act === 'opsReset') {
try { ops.status = await api('/api/admin/llm/reset', { method: 'POST', body: {} }); toast('Sicherung zurückgesetzt – die nächste Anfrage geht wieder ans Modell.', 'ok'); draw(); } catch (e) { toast(e.message, 'err'); }
} else if (act === 'opsSummary') {
try { ops = await api('/api/admin/ops/summary', { method: 'POST', body: {} }); pollN = 0; draw(); } catch (e) { toast(e.message, 'err'); }
} else if (act === 'opsDel') {
try { ops = await api(`/api/admin/ops/draft/${encodeURIComponent(a.dataset.id)}`, { method: 'DELETE' }); draw(); } catch (e) { toast(e.message, 'err'); }
} else if (act === 'opsCopy') {
const t = $(`#opsT${a.dataset.id}`)?.value ?? '';
try { await navigator.clipboard.writeText(t); toast('Text kopiert.', 'ok'); } catch { $(`#opsT${a.dataset.id}`)?.select(); toast('Kopieren nicht erlaubt – Text ist markiert.', 'info'); }
} else if (act === 'opsSend') {
const text = ($(`#opsT${a.dataset.id}`)?.value ?? '').trim();
if (text.length < 3) { toast('Der Text ist zu kurz.', 'err'); return; }
if (!(await ask({ title: 'Durchsage an alle Spieler senden?', text: `„${text}“`, ok: 'Senden' }))) return;
try { await api('/api/admin/action', { method: 'POST', body: { action: 'broadcast', value: text } }); toast('Durchsage gesendet.', 'ok'); } catch (e) { toast(e.message, 'err'); }
}
}
/** Formular „Entwurf erstellen“; synchron true/false, damit admin.js weiß, ob das Absenden erledigt ist */
export function opsSubmit(e) {
if (e.target.id === 'opsStyleForm') { e.preventDefault(); saveStyle(e.target); return true; }
if (e.target.id !== 'opsDraftForm') return false;
e.preventDefault();
kind = e.target.querySelector('input[name="opsKind"]:checked')?.value ?? 'frei';
const note = $('#opsNote').value.trim();
api('/api/admin/ops/draft', { method: 'POST', body: { kind, note } })
.then((r) => { ops = r; $('#opsNote').value = ''; pollN = 0; draw(); })
.catch((err) => toast(err.message, 'err'));
return true;
}
export function opsInput(e) {
if (e.target.closest?.('#opsStyleForm')) {
if (!styleDirty) { styleDirty = true; const b = document.querySelector('[data-a="opsStyleReset"]'); if (b) b.disabled = false; }
const hc = e.target.name && document.querySelector(`[data-hcount="${CSS.escape(e.target.name)}"]`);
if (hc) hc.textContent = `${int(e.target.value.length)} / ${int(ops?.style?.hintMax ?? 300)}`;
return true;
}
const m = /^opsT(\d+)$/.exec(e.target.id ?? '');
if (!m) return false;
const c = document.querySelector(`[data-count="${m[1]}"]`);
if (c) c.textContent = `${int(e.target.value.length)} / 300`;
return true;
}