feat(admin): auth + four data panels (sessions/conversations/approvals/config)
- HTTP Basic auth from config http.admin (constant-time compare; absent config -> UI/api fail-closed 503, legacy JSON endpoints stay open) - GET /api/sessions: bindings + pinned model + idle - GET /api/conversations: hub-side text logs (tail 50/binding) - GET /api/approvals: pending permission requests incl. options/presented - GET /api/config: effective config with secret-looking values redacted - UI: tabbed layout (Overview/Sessions/Conversations/Approvals/Config), approvals tab shows pending count badge
This commit is contained in:
1 parent
e1afdce073
commit
c396ce2d5e
5 files changed
+423
-97
No files matched your search
@@ -0,0 +1,131 @@
|
||||
"""Admin UI data endpoints + auth for agenthub (added to StatusHTTP).
|
||||
|
||||
Auth: HTTP Basic. Credentials live in config["http"]["admin"] = {"username",
|
||||
"password"} (config.json / agenthub-etc/config.json, 0600 — secrets never in
|
||||
code or docs). If admin block is absent, UI+data endpoints serve 503 with a
|
||||
hint (fail-closed); /healthz and /status stay open (nginx already gates them).
|
||||
|
||||
New read-only endpoints (all auth-gated):
|
||||
GET /api/conversations -> hub-side conversation text per binding
|
||||
GET /api/approvals -> pending permission requests
|
||||
GET /api/sessions -> bindings + pinned model config
|
||||
GET /api/config -> sanitized effective config
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
|
||||
def check_auth(header_value: str | None, admin_cfg: dict[str, Any] | None) -> bool:
|
||||
"""Constant-time Basic auth check. Fail-closed when admin_cfg is None/empty."""
|
||||
if not admin_cfg or not admin_cfg.get("username") or not admin_cfg.get("password"):
|
||||
return False
|
||||
if not header_value or not header_value.startswith("Basic "):
|
||||
return False
|
||||
try:
|
||||
raw = base64.b64decode(header_value[6:]).decode("utf-8", "replace")
|
||||
user, _, pw = raw.partition(":")
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
ok_u = hmac.compare_digest(user, str(admin_cfg["username"]))
|
||||
ok_p = hmac.compare_digest(pw, str(admin_cfg["password"]))
|
||||
return ok_u and ok_p
|
||||
|
||||
|
||||
def sanitize_config(cfg: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Config view for the UI: structure only, secret-looking values redacted."""
|
||||
SECRET_KEYS = {"secret", "password", "token", "key", "app_secret", "api_key"}
|
||||
|
||||
def redact(obj: Any, parent_key: str = "") -> Any:
|
||||
if isinstance(obj, dict):
|
||||
out = {}
|
||||
for k, v in obj.items():
|
||||
if any(s in k.lower() for s in SECRET_KEYS) and isinstance(v, str) and v:
|
||||
out[k] = v[:4] + "…[REDACTED]"
|
||||
else:
|
||||
out[k] = redact(v, k)
|
||||
return out
|
||||
if isinstance(obj, list):
|
||||
return [redact(x) for x in obj]
|
||||
return obj
|
||||
|
||||
return redact(cfg)
|
||||
|
||||
|
||||
def conversations_payload(mgr: Any) -> dict[str, Any]:
|
||||
"""Hub-side text logs (SessionRecord.text_log), newest first, tail-limited."""
|
||||
items = []
|
||||
with mgr._lock:
|
||||
for key, rec in getattr(mgr, "_records", {}).items():
|
||||
log = rec.text_log[-50:]
|
||||
items.append(
|
||||
{
|
||||
"binding_key": key,
|
||||
"agent": rec.agent,
|
||||
"acp_session_id": rec.acp_session_id,
|
||||
"updated_at": rec.updated_at,
|
||||
"turns": len(rec.text_log),
|
||||
"log": log,
|
||||
}
|
||||
)
|
||||
items.sort(key=lambda x: x["updated_at"], reverse=True)
|
||||
return {"conversations": items}
|
||||
|
||||
|
||||
def approvals_payload(mgr: Any) -> dict[str, Any]:
|
||||
"""Pending permission requests (live memory state)."""
|
||||
now = time.time()
|
||||
items = []
|
||||
with mgr._lock:
|
||||
for rid, p in getattr(mgr, "_pending_permissions", {}).items():
|
||||
items.append(
|
||||
{
|
||||
"request_id": rid,
|
||||
"agent": p.agent,
|
||||
"session_id": p.session_id,
|
||||
"key": p.key,
|
||||
"tool_title": p.tool_title,
|
||||
"tool_kind": p.tool_kind,
|
||||
"options": p.options,
|
||||
"presented": p.presented,
|
||||
"age_s": round(now - p.created_at, 1),
|
||||
"answered": p.answered.is_set(),
|
||||
"choice": p.choice,
|
||||
}
|
||||
)
|
||||
items.sort(key=lambda x: x["age_s"], reverse=True)
|
||||
return {"approvals": items}
|
||||
|
||||
|
||||
def sessions_payload(mgr: Any) -> dict[str, Any]:
|
||||
"""Bindings enriched with the pinned per-session model (if known)."""
|
||||
out = []
|
||||
with mgr._lock:
|
||||
bindings = list(mgr._bindings.items())
|
||||
for (channel, chat_id), b in bindings:
|
||||
cfg_model = None
|
||||
try:
|
||||
sc = mgr._session_config(b) # {"model": {"current": ..., "options": [...]}}
|
||||
cfg_model = sc.get("model", {}).get("current")
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
out.append(
|
||||
{
|
||||
"channel": channel,
|
||||
"chat_id": chat_id,
|
||||
"agent": b.agent,
|
||||
"acp_session_id": b.acp_session_id,
|
||||
"model": cfg_model,
|
||||
"created_at": b.created_at,
|
||||
"last_active": b.last_active,
|
||||
"idle_s": round(time.time() - b.last_active, 1),
|
||||
}
|
||||
)
|
||||
out.sort(key=lambda x: x["last_active"], reverse=True)
|
||||
return {"sessions": out}
|
||||
+108
-49
@@ -1,40 +1,57 @@
|
||||
"""Admin UI for agenthub — single-file dashboard served by StatusHTTP.
|
||||
|
||||
Design: dark terminal-inspired theme, pure stdlib (no build step), auto-refresh.
|
||||
Panels: service health, channels (connection state), agents (running procs),
|
||||
live session bindings. All data comes from the existing /status + /sessions
|
||||
endpoints — the UI is a static HTML string that fetches JSON client-side.
|
||||
Tabs: Overview (health/channels/agents/bindings), Sessions (pinned models,
|
||||
idle), Conversations (hub-side text logs), Approvals (pending permission
|
||||
requests), Config (sanitized effective config). Data from /status, /sessions
|
||||
and auth-gated /api/* endpoints; browser caches Basic credentials per session.
|
||||
"""
|
||||
|
||||
DARK_CSS = """
|
||||
:root{--bg:#0d1117;--panel:#161b22;--border:#30363d;--fg:#e6edf3;--muted:#8b949e;
|
||||
--green:#3fb950;--red:#f85149;--amber:#d29922;--blue:#58a6ff;--mono:ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace}
|
||||
--green:#3fb950;--red:#f85149;--amber:#d29922;--blue:#58a6ff;
|
||||
--mono:ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace}
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{background:var(--bg);color:var(--fg);font-family:var(--mono);font-size:14px;padding:24px;max-width:1200px;margin:0 auto}
|
||||
body{background:var(--bg);color:var(--fg);font-family:var(--mono);font-size:14px;padding:24px;max-width:1280px;margin:0 auto}
|
||||
h1{font-size:18px;font-weight:600;display:flex;align-items:center;gap:10px;margin-bottom:4px}
|
||||
h1 .sub{font-size:12px;color:var(--muted);font-weight:400}
|
||||
.tabs{display:flex;gap:4px;margin-top:16px;border-bottom:1px solid var(--border)}
|
||||
.tab{padding:8px 16px;cursor:pointer;color:var(--muted);border:1px solid transparent;border-bottom:none;border-radius:6px 6px 0 0;font-size:13px}
|
||||
.tab:hover{color:var(--fg)}
|
||||
.tab.on{color:var(--fg);background:var(--panel);border-color:var(--border);position:relative;top:1px}
|
||||
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(340px,1fr));gap:16px;margin-top:18px}
|
||||
.card{background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:16px}
|
||||
.card{background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:16px;margin-bottom:16px}
|
||||
.card h2{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:12px;display:flex;justify-content:space-between;align-items:center}
|
||||
.pill{font-size:11px;padding:2px 8px;border-radius:10px;font-weight:600}
|
||||
.pill.ok{background:#12351d;color:var(--green)}
|
||||
.pill.bad{background:#3d1418;color:var(--red)}
|
||||
.pill.warn{background:#33290c;color:var(--amber)}
|
||||
.row{display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid var(--border)}
|
||||
.row{display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid var(--border);gap:8px}
|
||||
.row:last-child{border-bottom:none}
|
||||
.row .k{color:var(--muted)}
|
||||
.dot{width:8px;height:8px;border-radius:50%;display:inline-block;margin-right:8px}
|
||||
.dot{width:8px;height:8px;border-radius:50%;display:inline-block;margin-right:8px;flex-shrink:0}
|
||||
.dot.ok{background:var(--green)}.dot.bad{background:var(--red)}.dot.warn{background:var(--amber)}.dot.idle{background:var(--muted)}
|
||||
.kv{font-size:22px;font-weight:600}
|
||||
.meta{color:var(--muted);font-size:12px;margin-top:6px}
|
||||
table{width:100%;border-collapse:collapse;font-size:13px}
|
||||
th{color:var(--muted);text-align:left;font-weight:500;padding:6px 8px;border-bottom:1px solid var(--border);font-size:11px;text-transform:uppercase;letter-spacing:.06em}
|
||||
td{padding:8px;border-bottom:1px solid var(--border)}
|
||||
td{padding:8px;border-bottom:1px solid var(--border);vertical-align:top}
|
||||
tr:last-child td{border-bottom:none}
|
||||
code{background:#21262d;padding:1px 6px;border-radius:4px;font-size:12px;color:var(--blue)}
|
||||
#refresh{color:var(--muted);font-size:11px;cursor:pointer;user-select:none}
|
||||
#refresh:hover{color:var(--blue)}
|
||||
.empty{color:var(--muted);font-style:italic;padding:12px 0;font-size:13px}
|
||||
.msg{padding:6px 10px;border-left:3px solid var(--border);margin:6px 0;border-radius:0 6px 6px 0;font-size:13px;white-space:pre-wrap;word-break:break-word}
|
||||
.msg.user{border-color:var(--blue);background:rgba(88,166,255,.06)}
|
||||
.msg.assistant{border-color:var(--green);background:rgba(63,185,80,.05)}
|
||||
.msg .who{font-size:10px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);display:block;margin-bottom:2px}
|
||||
.opts{margin-top:6px;font-size:12px;color:var(--muted)}
|
||||
.badge{display:inline-block;padding:1px 7px;border-radius:8px;font-size:11px;background:#21262d;color:var(--muted);margin-right:4px}
|
||||
.badge.kind-deny{background:#3d1418;color:var(--red)}
|
||||
.badge.kind-allow{background:#12351d;color:var(--green)}
|
||||
pre.config{font-size:12px;color:var(--muted);white-space:pre-wrap;word-break:break-all;max-height:520px;overflow:auto}
|
||||
.age{color:var(--muted);font-size:12px;font-weight:400;text-transform:none;letter-spacing:0}
|
||||
.stale{color:var(--amber)}
|
||||
"""
|
||||
|
||||
HTML = """<!DOCTYPE html>
|
||||
@@ -44,53 +61,95 @@ HTML = """<!DOCTYPE html>
|
||||
<h1>⚡ agenthub <span class="sub">ACP bridge · IM ⇄ NATS ⇄ agents</span></h1>
|
||||
<div class="meta">refreshed <span id="ts">—</span> · <span id="refresh">↻ refresh</span> · auto 10s</div>
|
||||
|
||||
<div class="grid">
|
||||
<div class="card"><h2>Service <span id="svc-pill" class="pill">…</span></h2>
|
||||
<div style="display:flex;gap:32px;margin-top:4px">
|
||||
<div><div class="kv" id="k-agents">—</div><div class="meta">agents</div></div>
|
||||
<div><div class="kv" id="k-sessions">—</div><div class="meta">sessions</div></div>
|
||||
<div><div class="kv" id="k-uptime">—</div><div class="meta">uptime</div></div>
|
||||
</div></div>
|
||||
<div class="tabs" id="tabs"></div>
|
||||
<div id="panes"></div>
|
||||
|
||||
<div class="card"><h2>Channels</h2><div id="channels"></div></div>
|
||||
|
||||
<div class="card"><h2>Agents</h2><div id="agents"></div></div>
|
||||
|
||||
<div class="card"><h2>Live Bindings</h2><div id="bindings"></div></div>
|
||||
</div>
|
||||
<script>
|
||||
const $=id=>document.getElementById(id);
|
||||
const esc=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));
|
||||
const dot=s=>({connected:'ok',running:'ok',subscribed:'ok',ok:'ok',failed:'bad',error:'bad',degraded:'warn'}[s]||'idle');
|
||||
function fmtUp(s){if(s<60)return Math.round(s)+'s';if(s<3600)return Math.floor(s/60)+'m '+Math.round(s%60)+'s';return Math.floor(s/3600)+'h '+Math.floor(s%3600/60)+'m'}
|
||||
const fmtUp=s=>{if(s<60)return Math.round(s)+'s';if(s<3600)return Math.floor(s/60)+'m';return Math.floor(s/3600)+'h '+Math.floor(s%3600/60)+'m'};
|
||||
const ago=t=>Math.max(0,Math.round(Date.now()/1000-t));
|
||||
|
||||
let DATA={};
|
||||
const TABS=['Overview','Sessions','Conversations','Approvals','Config'];
|
||||
let cur='Overview';
|
||||
function renderTabs(){
|
||||
const pend=(DATA.approvals?.approvals||[]).filter(a=>!a.answered).length;
|
||||
$('tabs').innerHTML=TABS.map(t=>{
|
||||
let n=t==='Approvals'&&pend?` <span class="badge" style="background:var(--red);color:#fff">${pend}</span>`:'';
|
||||
return `<div class="tab ${t===cur?'on':''}" onclick="cur='${t}';renderTabs();renderPanes()">${t}${n}</div>`;
|
||||
}).join('');
|
||||
}
|
||||
const ch=cs=>cs.length?cs.map(c=>{const d=dot(c.state);
|
||||
return `<div class="row"><span><span class="dot ${d}"></span>${esc(c.name)}</span>
|
||||
<span style="color:var(--${d==='ok'?'green':d==='bad'?'red':'amber'})">${esc(c.state)}${c.error?` <span title="${esc(c.error)}" style="color:var(--muted)">⚠</span>`:''}</span></div>`}).join('')
|
||||
:'<div class="empty">no channels</div>';
|
||||
const ag=as=>as.map(a=>{const d=a.running?'ok':'idle';
|
||||
return `<div class="row"><span><span class="dot ${d}"></span>${esc(a.name)}</span><code>${esc(Array.isArray(a.cmd)?a.cmd.join(' '):a.cmd)}</code></div>`}).join('')||'<div class="empty">no agents</div>';
|
||||
const bind=bs=>bs.length?`<table><tr><th>channel</th><th>chat</th><th>agent</th><th>active</th></tr>`+
|
||||
bs.map(b=>`<tr><td>${esc(b.channel)}</td><td>${esc(b.chat_id)}</td><td>${esc(b.agent)}</td>
|
||||
<td class="age">${ago(b.last_active)}s</td></tr>`).join('')+'</table>':'<div class="empty">no live sessions</div>';
|
||||
|
||||
function renderPanes(){
|
||||
const P=$('panes');
|
||||
if(cur==='Overview'){
|
||||
const st=DATA.status||{}, se=DATA.sessions0||{bindings:[]};
|
||||
P.innerHTML=`<div class="grid">
|
||||
<div class="card"><h2>Service <span class="pill ${st.status==='degraded'?'bad':'ok'}">${esc(st.status||'—')}</span></h2>
|
||||
<div style="display:flex;gap:32px;margin-top:4px">
|
||||
<div><div class="kv">${st.agents?.length??'—'}</div><div class="meta">agents</div></div>
|
||||
<div><div class="kv">${(se.bindings||[]).length}</div><div class="meta">sessions</div></div>
|
||||
<div><div class="kv">${fmtUp(st.uptime_s||0)}</div><div class="meta">uptime</div></div></div></div>
|
||||
<div class="card"><h2>Channels</h2>${ch(st.channels)}</div>
|
||||
<div class="card"><h2>Agents</h2>${ag(st.agents)}</div>
|
||||
<div class="card"><h2>Live Bindings</h2>${bind(se.bindings)}</div>
|
||||
</div>`;
|
||||
} else if(cur==='Sessions'){
|
||||
const ss=DATA.sessions?.sessions||[];
|
||||
P.innerHTML=`<div class="card"><h2>Sessions (${ss.length})</h2>
|
||||
${ss.length?`<table><tr><th>channel</th><th>chat</th><th>agent</th><th>model (pinned)</th><th>idle</th></tr>`+
|
||||
ss.map(s=>`<tr><td>${esc(s.channel)}</td><td>${esc(s.chat_id)}</td><td>${esc(s.agent)}</td>
|
||||
<td><code>${esc(s.model||'—')}</code></td>
|
||||
<td class="age ${s.idle_s>600?'stale':''}">${Math.round(s.idle_s)}s</td></tr>`).join('')+'</table>'
|
||||
:'<div class="empty">no sessions</div>'}</div>`;
|
||||
} else if(cur==='Conversations'){
|
||||
const cs=DATA.convs?.conversations||[];
|
||||
P.innerHTML=cs.length?cs.map(c=>`<div class="card">
|
||||
<h2>${esc(c.binding_key)} <span class="age">${c.turns} turns · ${ago(c.updated_at)}s ago</span></h2>
|
||||
${c.log.slice(-20).map(m=>`<div class="msg ${esc(m.role)}"><span class="who">${esc(m.role)}</span>${esc(m.text||'')}</div>`).join('')}
|
||||
</div>`).join('')
|
||||
:`<div class="card"><div class="empty">no conversations recorded</div></div>`;
|
||||
} else if(cur==='Approvals'){
|
||||
const ap=DATA.approvals?.approvals||[];
|
||||
P.innerHTML=ap.length?ap.map(a=>{
|
||||
const opts=(a.options||[]).map(o=>`<span class="badge kind-${(o.kind||'').includes('reject')?'deny':'allow'}">${esc(o.name||o.option_id)}</span>`).join('');
|
||||
return `<div class="card"><h2>${esc(a.tool_title||a.tool_kind||'request')}
|
||||
<span class="age">${Math.round(a.age_s)}s ago · ${a.answered?'answered: '+esc(a.choice||'—'):(a.presented?'awaiting user':'not presented')}</span></h2>
|
||||
<div class="row"><span class="k">agent</span><span>${esc(a.agent)}</span></div>
|
||||
<div class="row"><span class="k">session</span><span>${esc(a.session_id)}</span></div>
|
||||
<div class="row"><span class="k">chat</span><span>${esc(a.key)}</span></div>
|
||||
<div class="opts">${opts}</div></div>`;
|
||||
}).join('')
|
||||
:`<div class="card"><div class="empty">no pending approvals — nothing waiting</div></div>`;
|
||||
} else if(cur==='Config'){
|
||||
P.innerHTML=`<div class="card"><h2>Effective config (secrets redacted)</h2>
|
||||
<pre class="config">${esc(JSON.stringify(DATA.config?.config||{},null,2))}</pre></div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function load(){
|
||||
try{
|
||||
const st=await fetch('status').then(r=>r.json());
|
||||
const se=await fetch('sessions').then(r=>r.json()).catch(()=>({bindings:[]}));
|
||||
const g=u=>fetch(u).then(r=>r.ok?r.json():null);
|
||||
DATA.status=await g('status')||{};
|
||||
DATA.sessions0=await g('sessions')||{bindings:[]};
|
||||
DATA.sessions=await g('api/sessions');
|
||||
DATA.convs=await g('api/conversations');
|
||||
DATA.approvals=await g('api/approvals');
|
||||
DATA.config=await g('api/config');
|
||||
$('ts').textContent=new Date().toLocaleTimeString();
|
||||
const ok=st.status!=='degraded';
|
||||
$('svc-pill').textContent=st.status;
|
||||
$('svc-pill').className='pill '+(ok?'ok':'bad');
|
||||
$('k-agents').textContent=st.agents.length;
|
||||
$('k-sessions').textContent=(se.bindings||[]).length;
|
||||
$('k-uptime').textContent=fmtUp(st.uptime_s||0);
|
||||
// channels
|
||||
$('channels').innerHTML=st.channels.length?st.channels.map(c=>{
|
||||
const d=dot(c.state);
|
||||
return `<div class="row"><span><span class="dot ${d}"></span>${c.name}</span>
|
||||
<span style="color:var(--${d==='ok'?'green':d==='bad'?'red':'amber'})">${c.state}${c.error?` <span title="${c.error}" style="color:var(--muted)">⚠</span>`:''}</span></div>`;
|
||||
}).join(''):'<div class="empty">no channels</div>';
|
||||
// agents
|
||||
$('agents').innerHTML=st.agents.map(a=>{
|
||||
const d=a.running?'ok':'idle';
|
||||
return `<div class="row"><span><span class="dot ${d}"></span>${a.name}</span><code>${a.cmd}</code></div>`;
|
||||
}).join('')||'<div class="empty">no agents configured</div>';
|
||||
// bindings
|
||||
const bs=se.bindings||[];
|
||||
$('bindings').innerHTML=bs.length?`<table><tr><th>channel</th><th>chat</th><th>agent</th><th>last active</th></tr>`+
|
||||
bs.map(b=>`<tr><td>${b.channel}</td><td>${b.chat_id}</td><td>${b.agent}</td>
|
||||
<td style="color:var(--muted)">${Math.max(0,Math.round(Date.now()/1000-b.last_active))}s ago</td></tr>`).join('')+
|
||||
'</table>':'<div class="empty">no live sessions</div>';
|
||||
}catch(e){$('svc-pill').textContent='unreachable';$('svc-pill').className='pill bad';}
|
||||
}catch(e){DATA.status={status:'unreachable'}}
|
||||
renderTabs();renderPanes();
|
||||
}
|
||||
$('refresh').onclick=load;setInterval(load,10000);load();
|
||||
</script></body></html>"""
|
||||
|
||||
+83
-17
@@ -1,11 +1,18 @@
|
||||
"""Minimal HTTP surface for nginx reverse proxy (/agents).
|
||||
"""HTTP surface for nginx reverse proxy (/agents).
|
||||
|
||||
Endpoints (read-only):
|
||||
GET /agents/ -> service overview {status, agents, uptime}
|
||||
GET /agents/status -> same as above
|
||||
GET /agents/sessions -> live bindings
|
||||
GET /agents/healthz -> liveness (200)
|
||||
POST /agents/prompt -> {channel, chat_id, text, agent?, cwd?} (ops tool; loopback-guarded)
|
||||
Endpoints (JSON, programmatic — open, nginx-level gating applies):
|
||||
GET /agents/status -> {status, agents, channels, uptime}
|
||||
GET /agents/sessions -> live bindings (legacy; superseded by /api/sessions)
|
||||
GET /agents/healthz -> liveness (200)
|
||||
POST /agents/prompt -> {channel, chat_id, text, agent?, cwd?} (ops tool)
|
||||
|
||||
Admin UI (auth-gated via HTTP Basic from config http.admin; fail-closed 503
|
||||
when http.admin is absent):
|
||||
GET /agents/ , /ui -> dashboard HTML
|
||||
GET /agents/api/conversations -> hub-side conversation logs
|
||||
GET /agents/api/approvals -> pending permission requests
|
||||
GET /agents/api/sessions -> bindings + pinned model
|
||||
GET /agents/api/config -> sanitized effective config
|
||||
|
||||
Runs a ThreadingHTTPServer in-thread; bound to loopback by default —
|
||||
nginx on the same host proxies https://api.vxquant.com/agents/ to it.
|
||||
@@ -20,14 +27,29 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from agenthub.admin_data import (
|
||||
approvals_payload,
|
||||
check_auth,
|
||||
conversations_payload,
|
||||
sanitize_config,
|
||||
sessions_payload,
|
||||
)
|
||||
from agenthub.admin_ui import render_index
|
||||
|
||||
|
||||
class StatusHTTP:
|
||||
def __init__(self, mgr: Any, host: str = "127.0.0.1", port: int = 30990):
|
||||
def __init__(
|
||||
self,
|
||||
mgr: Any,
|
||||
host: str = "127.0.0.1",
|
||||
port: int = 30990,
|
||||
admin_cfg: dict[str, Any] | None = None,
|
||||
):
|
||||
self.mgr = mgr
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.admin_cfg = admin_cfg # {"username","password"} or None (fail-closed)
|
||||
self.effective_cfg: dict[str, Any] = {} # injected by runtime.main()
|
||||
self.started = time.time()
|
||||
self.channels: list = [] # injected by runtime.main() after build_channels
|
||||
self._server: ThreadingHTTPServer | None = None
|
||||
@@ -46,6 +68,28 @@ class StatusHTTP:
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def _html(self, data: bytes) -> None:
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def _require_auth(self) -> bool:
|
||||
if check_auth(self.headers.get("Authorization"), outer.admin_cfg):
|
||||
return True
|
||||
if outer.admin_cfg:
|
||||
self.send_response(401)
|
||||
self.send_header("WWW-Authenticate", 'Basic realm="agenthub"')
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
else:
|
||||
self._json(
|
||||
503,
|
||||
{"error": "admin auth not configured; set http.admin in config.json"},
|
||||
)
|
||||
return False
|
||||
|
||||
def _route_get(self, path: str, qs: dict) -> None:
|
||||
m = outer.mgr
|
||||
if path in ("/", "/status"):
|
||||
@@ -87,6 +131,26 @@ class StatusHTTP:
|
||||
}
|
||||
)
|
||||
self._json(200, {"bindings": bindings})
|
||||
elif path in ("/ui", "/index.html"):
|
||||
if not self._require_auth():
|
||||
return
|
||||
self._html(render_index().encode())
|
||||
elif path == "/api/conversations":
|
||||
if not self._require_auth():
|
||||
return
|
||||
self._json(200, conversations_payload(m))
|
||||
elif path == "/api/approvals":
|
||||
if not self._require_auth():
|
||||
return
|
||||
self._json(200, approvals_payload(m))
|
||||
elif path == "/api/sessions":
|
||||
if not self._require_auth():
|
||||
return
|
||||
self._json(200, sessions_payload(m))
|
||||
elif path == "/api/config":
|
||||
if not self._require_auth():
|
||||
return
|
||||
self._json(200, {"config": sanitize_config(outer.effective_cfg)})
|
||||
else:
|
||||
self._json(404, {"error": "not found"})
|
||||
|
||||
@@ -110,17 +174,19 @@ class StatusHTTP:
|
||||
def do_GET(self):
|
||||
parsed = urlparse(self.path)
|
||||
path = parsed.path.rstrip("/") or "/"
|
||||
if path in ("/", "/ui", "/index.html"):
|
||||
# Admin UI (browser-facing): the same nginx /agents/ prefix
|
||||
# serves it; JSON endpoints remain for programmatic access.
|
||||
data = render_index().encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
if path == "/":
|
||||
# With auth configured, / serves the dashboard (browser entry).
|
||||
# Without auth config, keep the legacy open JSON status so
|
||||
# existing scripts don't break.
|
||||
if outer.admin_cfg is not None:
|
||||
if not self._require_auth():
|
||||
return
|
||||
self._html(render_index().encode())
|
||||
return
|
||||
self._route_get(path, parse_qs(parsed.query))
|
||||
return
|
||||
self._route_get(path, parse_qs(parsed.query))
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length", 0))
|
||||
self._route_post(urlparse(self.path).path.rstrip("/"), self.rfile.read(length))
|
||||
|
||||
@@ -194,8 +194,14 @@ def main(argv: list[str] | None = None) -> None:
|
||||
from .http_admin import StatusHTTP
|
||||
|
||||
http_cfg = cfg.get("http", {})
|
||||
http = StatusHTTP(mgr, host=http_cfg.get("listen_host", "127.0.0.1"), port=int(http_cfg.get("port", 30990)))
|
||||
http = StatusHTTP(
|
||||
mgr,
|
||||
host=http_cfg.get("listen_host", "127.0.0.1"),
|
||||
port=int(http_cfg.get("port", 30990)),
|
||||
admin_cfg=http_cfg.get("admin"), # None -> UI/api fail-closed 503
|
||||
)
|
||||
http.channels = chans # /status reports per-channel connection state
|
||||
http.effective_cfg = cfg # /api/config (sanitized at render time)
|
||||
http.start()
|
||||
log.info(f"status http on {http.host}:{http.port}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
|
||||
+94
-30
@@ -1,15 +1,20 @@
|
||||
"""Tests for the admin UI endpoint (served on / and /ui)."""
|
||||
"""Tests for admin UI + auth + data endpoints (served on /, /ui, /api/*)."""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from agenthub.admin_data import check_auth, sanitize_config
|
||||
from agenthub.http_admin import StatusHTTP
|
||||
|
||||
ADMIN = {"username": "ops", "password": "s3cret"}
|
||||
|
||||
|
||||
class FakeBinding:
|
||||
def __init__(self, channel, chat_id, agent, acp_session_id):
|
||||
@@ -17,58 +22,117 @@ class FakeBinding:
|
||||
self.chat_id = chat_id
|
||||
self.agent = agent
|
||||
self.acp_session_id = acp_session_id
|
||||
self.created_at = time.time()
|
||||
self.last_active = time.time()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server():
|
||||
class FakeRecord:
|
||||
def __init__(self, key, agent, sid, log):
|
||||
self.binding_key = key
|
||||
self.agent = agent
|
||||
self.acp_session_id = sid
|
||||
self.text_log = log
|
||||
self.updated_at = time.time()
|
||||
|
||||
|
||||
def make_mgr():
|
||||
mgr = MagicMock()
|
||||
mgr.list_agents.return_value = [
|
||||
{"name": "opencode", "cmd": "opencode acp", "running": True},
|
||||
{"name": "codex", "cmd": "codex acp", "running": False},
|
||||
]
|
||||
mgr._bindings = {
|
||||
("wecom", "c1"): FakeBinding("wecom", "c1", "opencode", "s1"),
|
||||
b = FakeBinding("wecom", "c1", "opencode", "s1")
|
||||
mgr._bindings = {("wecom", "c1"): b}
|
||||
mgr._records = {
|
||||
"wecom:c1": FakeRecord(
|
||||
"wecom:c1", "opencode", "s1",
|
||||
[{"role": "user", "text": "hi"}, {"role": "assistant", "text": "hello"}],
|
||||
)
|
||||
}
|
||||
mgr._pending_permissions = {}
|
||||
mgr._lock = threading.Lock()
|
||||
http = StatusHTTP(mgr, host="127.0.0.1", port=0) # port 0 = ephemeral
|
||||
mgr._session_config.return_value = {"model": {"current": "opencode/mimo-v2.6-flash-free"}}
|
||||
return mgr
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_server():
|
||||
http = StatusHTTP(make_mgr(), host="127.0.0.1", port=0, admin_cfg=ADMIN)
|
||||
http.start()
|
||||
port = http._server.server_address[1]
|
||||
yield f"http://127.0.0.1:{port}"
|
||||
http.stop()
|
||||
|
||||
|
||||
def _get(url):
|
||||
with urllib.request.urlopen(url, timeout=5) as r:
|
||||
return r.status, r.read()
|
||||
@pytest.fixture
|
||||
def open_server():
|
||||
http = StatusHTTP(make_mgr(), host="127.0.0.1", port=0, admin_cfg=None)
|
||||
http.start()
|
||||
port = http._server.server_address[1]
|
||||
yield f"http://127.0.0.1:{port}"
|
||||
http.stop()
|
||||
|
||||
|
||||
def test_root_serves_html(server):
|
||||
code, body = _get(server + "/")
|
||||
assert code == 200
|
||||
assert b"text/html" not in body # header not in body; content check below
|
||||
assert b"agenthub" in body
|
||||
assert b"<!DOCTYPE html>" in body
|
||||
def _get(url, auth=None):
|
||||
req = urllib.request.Request(url)
|
||||
if auth:
|
||||
req.add_header("Authorization", "Basic " + base64.b64encode(auth.encode()).decode())
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=5) as r:
|
||||
return r.status, r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read()
|
||||
|
||||
|
||||
def test_ui_alias(server):
|
||||
code, body = _get(server + "/ui")
|
||||
# --- auth unit ---
|
||||
|
||||
def test_check_auth_ok_and_bad():
|
||||
assert check_auth("Basic " + base64.b64encode(b"ops:s3cret").decode(), ADMIN)
|
||||
assert not check_auth("Basic " + base64.b64encode(b"ops:wrong").decode(), ADMIN)
|
||||
assert not check_auth(None, ADMIN)
|
||||
assert not check_auth("Basic abc", ADMIN) # malformed b64 -> False
|
||||
assert not check_auth("Basic " + base64.b64encode(b"ops:s3cret").decode(), None) # fail-closed
|
||||
|
||||
|
||||
def test_sanitize_config_redacts_secrets():
|
||||
cfg = {"channels": [{"name": "wecom", "secret": "abcdef123456"}], "http": {"port": 30990}}
|
||||
out = sanitize_config(cfg)
|
||||
assert out["channels"][0]["secret"].endswith("[REDACTED]")
|
||||
assert "abcdef123456" not in json.dumps(out)
|
||||
assert out["http"]["port"] == 30990
|
||||
|
||||
|
||||
# --- auth-gated server ---
|
||||
|
||||
def test_root_requires_auth(auth_server):
|
||||
code, _ = _get(auth_server + "/")
|
||||
assert code == 401
|
||||
|
||||
|
||||
def test_ui_ok_with_auth(auth_server):
|
||||
code, body = _get(auth_server + "/ui", auth="ops:s3cret")
|
||||
assert code == 200 and b"<!DOCTYPE html>" in body
|
||||
|
||||
|
||||
def test_json_endpoints_still_work(server):
|
||||
code, body = _get(server + "/status")
|
||||
def test_api_endpoints(auth_server):
|
||||
code, body = _get(auth_server + "/api/sessions", auth="ops:s3cret")
|
||||
d = json.loads(body)
|
||||
assert d["service"] == "agenthub"
|
||||
assert len(d["agents"]) == 2
|
||||
code, body = _get(server + "/sessions")
|
||||
assert d["sessions"][0]["model"] == "opencode/mimo-v2.6-flash-free"
|
||||
code, body = _get(auth_server + "/api/conversations", auth="ops:s3cret")
|
||||
d = json.loads(body)
|
||||
assert d["bindings"][0]["agent"] == "opencode"
|
||||
assert d["conversations"][0]["turns"] == 2
|
||||
assert d["conversations"][0]["log"][0]["text"] == "hi"
|
||||
code, body = _get(auth_server + "/api/approvals", auth="ops:s3cret")
|
||||
assert json.loads(body)["approvals"] == []
|
||||
|
||||
|
||||
def test_html_references_fetch_targets(server):
|
||||
_, body = _get(server + "/")
|
||||
# UI fetches status/sessions relatively — must not hardcode hosts
|
||||
assert b"fetch('status')" in body
|
||||
assert b"fetch('sessions')" in body
|
||||
assert b"botflow_truncated" not in body # sanity: unrelated content absent
|
||||
def test_open_server_ui_fail_closed(open_server):
|
||||
code, body = _get(open_server + "/ui")
|
||||
assert code == 503
|
||||
assert b"not configured" in body
|
||||
|
||||
|
||||
def test_open_server_legacy_json_survives(open_server):
|
||||
code, body = _get(open_server + "/status")
|
||||
assert code == 200
|
||||
code, body = _get(open_server + "/sessions")
|
||||
assert code == 200 and b"bindings" in body
|
||||
Reference in new issue
Block a user