diff --git a/src/agenthub/admin_ops.py b/src/agenthub/admin_ops.py new file mode 100644 index 0000000..a8dae7c --- /dev/null +++ b/src/agenthub/admin_ops.py @@ -0,0 +1,201 @@ +"""Admin write operations: config channels/agents + binding (UI-backed). + +All writes go through: + 1. config.json update (atomic tmp+rename) — persisted source of truth + 2. live mutation — agents hot-registered into mgr.agents (AgentSpec); + channels noted for restart pickup (IM long-connections cannot be + hot-swapped safely, so new/changed channels require a supervisor + restart, surfaced to the UI as a pending-restart hint) + 3. binding = mgr.prompt(channel, chat_id, text=..., agent=...) with a + tiny no-op prompt so the binding row exists without a real turn + (empty text would waste a model call, so we use prompt text "." ? + no — we bind via _ensure_session through a dedicated bind() method). + +Secrets: written values land in config.json server-side only; /api/config +redacts at render time (sanitize_config). This module never echoes them. +""" + +from __future__ import annotations + +import json +import os +import threading +from typing import Any + +from .session import AgentSpec + +VALID_CHANNELS = {"wecom", "wecom-app", "weixin"} + +CHANNEL_REQUIRED: dict[str, list[str]] = { + "wecom": ["bot_id", "secret"], + "wecom-app": ["corp_id", "secret", "agent_id"], + "weixin": ["token"], +} +CHANNEL_OPTIONAL: dict[str, list[str]] = { + "wecom": ["mock_transport"], + "wecom-app": [], + "weixin": [], +} +AGENT_REQUIRED = ["cmd"] +AGENT_OPTIONAL = ["cwd_whitelist", "default_model"] + +SECRET_KEYS = {"secret", "token", "app_secret", "key"} + + +class AdminWriteError(ValueError): + pass + + +class AdminWrites: + """Holds config path + mgr ref; executes validated mutations.""" + + def __init__(self, mgr: Any, config_path: str): + self.mgr = mgr + self.config_path = config_path + self._lock = threading.Lock() + self.pending_restart = False # channels changed -> needs supervisor restart + + # -- config io ---------------------------------------------------------- + + def _load(self) -> dict[str, Any]: + with open(self.config_path, encoding="utf-8") as f: + return json.load(f) + + def _save(self, cfg: dict[str, Any]) -> None: + tmp = self.config_path + ".tmp" + with open(tmp, "w", encoding="utf-8") as f: + json.dump(cfg, f, indent=2, ensure_ascii=False) + f.write("\n") + os.replace(tmp, self.config_path) + + # -- validation --------------------------------------------------------- + + @staticmethod + def _clean_fields(kind: str, fields: dict[str, Any], required: list[str], + optional: list[str]) -> dict[str, Any]: + out: dict[str, Any] = {} + for k in required: + v = fields.get(k) + if not v or not str(v).strip(): + raise AdminWriteError(f"{kind}: missing required field {k!r}") + out[k] = v if isinstance(v, (int, float)) else str(v).strip() + for k in optional: + if k in fields and fields[k] not in (None, ""): + out[k] = fields[k] + unknown = set(fields) - set(required) - set(optional) + if unknown: + raise AdminWriteError(f"{kind}: unknown fields {sorted(unknown)}") + return out + + # -- 1. IM channel ------------------------------------------------------ + + def upsert_channel(self, name: str, fields: dict[str, Any]) -> dict[str, Any]: + if name not in VALID_CHANNELS: + raise AdminWriteError( + f"unknown channel {name!r}; valid: {sorted(VALID_CHANNELS)}" + ) + cleaned = self._clean_fields( + f"channel {name}", fields, + CHANNEL_REQUIRED[name], CHANNEL_OPTIONAL[name], + ) + with self._lock: + cfg = self._load() + existed = name in cfg.get("channels", {}) + cfg.setdefault("channels", {})[name] = cleaned + self._save(cfg) + self.pending_restart = True + return {"channel": name, "existed": existed, "restart_required": True} + + def delete_channel(self, name: str) -> dict[str, Any]: + with self._lock: + cfg = self._load() + if name not in cfg.get("channels", {}): + raise AdminWriteError(f"channel {name!r} not configured") + del cfg["channels"][name] + self._save(cfg) + self.pending_restart = True + return {"channel": name, "deleted": True, "restart_required": True} + + # -- 2. ACP agent ------------------------------------------------------- + + def upsert_agent(self, name: str, fields: dict[str, Any]) -> dict[str, Any]: + if not name or "/" in name or " " in name: + raise AdminWriteError(f"invalid agent name {name!r}") + cleaned = self._clean_fields( + f"agent {name}", fields, AGENT_REQUIRED, AGENT_OPTIONAL + ) + if isinstance(cleaned.get("cmd"), str): + cleaned["cmd"] = cleaned["cmd"].split() + if cleaned.get("cwd_whitelist") is not None and not isinstance( + cleaned["cwd_whitelist"], list + ): + cleaned["cwd_whitelist"] = [ + p.strip() for p in str(cleaned["cwd_whitelist"]).split(",") if p.strip() + ] + with self._lock: + cfg = self._load() + existed = name in cfg.get("agents", {}) + cfg.setdefault("agents", {})[name] = cleaned + self._save(cfg) + # live hot-register (new agents spawn lazily on first use) + self.mgr.agents[name] = AgentSpec( + name=name, + cmd=cleaned["cmd"], + cwd_whitelist=cleaned.get("cwd_whitelist", []), + default_model=cleaned.get("default_model"), + ) + return {"agent": name, "existed": existed, "hot_registered": True} + + def delete_agent(self, name: str) -> dict[str, Any]: + with self._lock: + cfg = self._load() + if name not in cfg.get("agents", {}): + raise AdminWriteError(f"agent {name!r} not configured") + if len(cfg["agents"]) == 1: + raise AdminWriteError("cannot delete the last agent") + del cfg["agents"][name] + self._save(cfg) + self.mgr.agents.pop(name, None) + return {"agent": name, "deleted": True} + + # -- 3. bind IM chat <-> agent ------------------------------------------ + + def bind(self, channel: str, chat_id: str, agent: str, + continue_history: bool = True) -> dict[str, Any]: + """Create/replace binding (channel, chat_id) -> agent. + + Uses mgr.handle_command-free direct path: reuse prompt() with a + marker-free approach — actually we call the internal session setup + via prompt() with a real text, because the hub requires an ACP + session before a binding exists. The chat gets a bind confirmation + appended to its conversation log. + """ + if not channel or not chat_id: + raise AdminWriteError("channel and chat_id are required") + if agent not in self.mgr.agents: + raise AdminWriteError( + f"agent {agent!r} not configured; known: {sorted(self.mgr.agents)}" + ) + res = self.mgr.switch(channel, chat_id, agent, cont=continue_history) + return { + "binding": f"{channel}:{chat_id}", + "agent": agent, + "acp_session_id": res.get("acp_session_id"), + "migrated_turns": res.get("migrated", 0), + } + + def unbind(self, channel: str, chat_id: str) -> dict[str, Any]: + if self.mgr.get_binding(channel, chat_id) is None: + raise AdminWriteError(f"no binding for {channel}:{chat_id}") + self.mgr.unbind(channel, chat_id) + return {"binding": f"{channel}:{chat_id}", "deleted": True} + + # -- status ------------------------------------------------------------- + + def state(self) -> dict[str, Any]: + cfg = self._load() + return { + "channels": sorted(cfg.get("channels", {})), + "agents": sorted(cfg.get("agents", {})), + "pending_restart": self.pending_restart, + } diff --git a/src/agenthub/admin_ui.py b/src/agenthub/admin_ui.py index 92b01e4..4857b3d 100644 --- a/src/agenthub/admin_ui.py +++ b/src/agenthub/admin_ui.py @@ -53,6 +53,12 @@ pre.config{font-size:14px;color:var(--muted);white-space:pre-wrap;word-break:bre .age{color:var(--muted);font-size:13px;font-weight:400;text-transform:none;letter-spacing:0} .stale{color:var(--amber)} @media(max-width:760px){body{padding:16px}.grid{grid-template-columns:1fr}.kv{font-size:22px}} +input,select{background:#0d1117;border:1px solid var(--border);border-radius:6px;color:var(--fg);font-family:var(--mono);font-size:15px;padding:8px 10px} +input:focus,select:focus{outline:none;border-color:var(--blue)} +.btn{background:#21262d;color:var(--fg);border:1px solid var(--border);border-radius:6px;font-family:var(--mono);font-size:15px;padding:8px 18px;cursor:pointer} +.btn:hover{border-color:var(--blue);color:var(--blue)} +.btn.danger{color:var(--red)} +.btn.danger:hover{border-color:var(--red)} """ HTML = """ @@ -73,7 +79,7 @@ const fmtUp=s=>{if(s<60)return Math.round(s)+'s';if(s<3600)return Math.floor(s/6 const ago=t=>Math.max(0,Math.round(Date.now()/1000-t)); let DATA={}; -const TABS=['Overview','Sessions','Conversations','Approvals','Config']; +const TABS=['Overview','Sessions','Conversations','Approvals','Config','Ops']; let cur='Overview'; function renderTabs(){ const pend=(DATA.approvals?.approvals||[]).filter(a=>!a.answered).length; @@ -136,9 +142,107 @@ function renderPanes(){ } else if(cur==='Config'){ P.innerHTML=`

Effective config (secrets redacted)

${esc(JSON.stringify(DATA.config?.config||{},null,2))}
`; + } else if(cur==='Ops'){ + renderOps(); } } +// ---- Ops tab: channel / agent / binding management (write ops) ---- +async function post(u,body){ + const r=await fetch(u,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}); + const j=await r.json().catch(()=>({})); + if(!r.ok) throw new Error(j.error||r.status); + return j; +} +function toast(ok,msg){ + const t=$('ops-toast'); + t.textContent=(ok?'✓ ':'✗ ')+msg; + t.style.color=ok?'var(--green)':'var(--red)'; + setTimeout(()=>{t.textContent=''},6000); +} +async function renderOps(){ + const P=$('panes'); + let st={channels:[],agents:[]}; + try{ st=await post('api/ops-state',{})||st; }catch(e){} + const pend=st.pending_restart; + P.innerHTML=` + ${pend?`

⚠ Channel config changed

+
IM channels are long-lived connections — a service restart is needed to pick up changes.
`:''} +
+

1 · IM 渠道

+
已配置${esc((st.channels||[]).join(', ')||'—')}
+
类型
+
+
+
+
+

2 · ACP Agent

+
已配置${esc((st.agents||[]).join(', ')||'—')}
+
名称
+
启动命令
+
默认模型
+
cwd 白名单
+
+
+
+

3 · 绑定 IM ⇄ Agent

+
channel
+
chat_id
+
agent
+
+
+
+
绑定即建立新 ACP 会话并写库;会话里用户可随时 /switch。
+
+
+
`; + $('ch-name').onchange=renderChFields;renderChFields(); +} +function renderChFields(){ + const req={wecom:[['bot_id','bot_id'],['secret','secret(写入 config.json,不回显)']], + 'wecom-app':[['corp_id','corp_id'],['secret','secret'],['agent_id','agent_id']], + weixin:[['token','token']]}[$('ch-name').value]||[]; + $('ch-fields').innerHTML=req.map(([k,ph])=>`
${esc(k)} +
`).join(''); +} +async function saveChannel(){ + try{ const name=$('ch-name').value; + const fields={}; document.querySelectorAll('[id^=chf-]').forEach(i=>{if(i.value)fields[i.id.slice(4)]=i.value}); + const r=await post('api/channel',{name,fields}); + toast(true,`渠道 ${name} 已保存`+(r.existed?'(覆盖)':'')+' · 需重启生效'); + }catch(e){toast(false,e.message)} +} +async function delChannel(){ + try{ await post('api/channel/delete',{name:$('ch-name').value}); + toast(true,'渠道已删除 · 需重启生效'); }catch(e){toast(false,e.message)} +} +async function saveAgent(){ + try{ const name=$('ag-name').value.trim(); + const fields={cmd:$('ag-cmd').value}; + if($('ag-model').value)fields.default_model=$('ag-model').value.trim(); + if($('ag-cwd').value)fields.cwd_whitelist=$('ag-cwd').value; + const r=await post('api/agent',{name,fields}); + toast(true,`agent ${name} 已保存`+(r.existed?'(覆盖)':'')+',即时生效'); + }catch(e){toast(false,e.message)} +} +async function delAgent(){ + try{ await post('api/agent/delete',{name:$('ag-name').value.trim()}); + toast(true,'agent 已删除'); }catch(e){toast(false,e.message)} +} +async function doBind(){ + try{ const r=await post('api/bind',{channel:$('bd-ch').value.trim(),chat_id:$('bd-chat').value.trim(), + agent:$('bd-ag').value,continue_history:$('bd-cont').checked}); + toast(true,`已绑定 ${r.binding} → ${r.agent}(会话 ${String(r.acp_session_id).slice(0,12)}…)`);load(); + }catch(e){toast(false,e.message)} +} +async function doUnbind(){ + try{ await post('api/unbind',{channel:$('bd-ch').value.trim(),chat_id:$('bd-chat').value.trim()}); + toast(true,'已解绑');load(); }catch(e){toast(false,e.message)} +} + async function load(){ try{ const g=u=>fetch(u).then(r=>r.ok?r.json():null); diff --git a/src/agenthub/http_admin.py b/src/agenthub/http_admin.py index 34a3f56..0e51024 100644 --- a/src/agenthub/http_admin.py +++ b/src/agenthub/http_admin.py @@ -34,6 +34,7 @@ from agenthub.admin_data import ( sanitize_config, sessions_payload, ) +from agenthub.admin_ops import AdminWriteError from agenthub.admin_ui import render_index @@ -50,6 +51,7 @@ class StatusHTTP: 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.ops: Any = None # AdminWrites, injected by runtime.main() self.started = time.time() self.channels: list = [] # injected by runtime.main() after build_channels self._server: ThreadingHTTPServer | None = None @@ -155,6 +157,42 @@ class StatusHTTP: self._json(404, {"error": "not found"}) def _route_post(self, path: str, body: bytes) -> None: + # admin write ops: auth required; /prompt stays open (nginx-gated) + if path.startswith("/api/") and path != "/api/prompt": + if not self._require_auth(): + return + ops = outer.ops + if ops is None: + self._json(503, {"error": "admin writes not configured (no config path)"}) + return + try: + req = json.loads(body or b"{}") + if path == "/api/channel": + self._json(200, ops.upsert_channel(req["name"], req.get("fields", {}))) + elif path == "/api/channel/delete": + self._json(200, ops.delete_channel(req["name"])) + elif path == "/api/agent": + self._json(200, ops.upsert_agent(req["name"], req.get("fields", {}))) + elif path == "/api/agent/delete": + self._json(200, ops.delete_agent(req["name"])) + elif path == "/api/bind": + self._json(200, ops.bind( + req["channel"], str(req["chat_id"]), req["agent"], + continue_history=bool(req.get("continue_history", True)), + )) + elif path == "/api/unbind": + self._json(200, ops.unbind(req["channel"], str(req["chat_id"]))) + elif path == "/api/ops-state": + self._json(200, ops.state()) + else: + self._json(404, {"error": "not found"}) + except AdminWriteError as e: + self._json(400, {"error": str(e)}) + except KeyError as e: + self._json(400, {"error": f"missing field {e}"}) + except Exception as e: # noqa: BLE001 + self._json(500, {"error": str(e)}) + return if path != "/prompt": self._json(404, {"error": "not found"}) return diff --git a/src/agenthub/runtime.py b/src/agenthub/runtime.py index aa46bc7..0ef86db 100644 --- a/src/agenthub/runtime.py +++ b/src/agenthub/runtime.py @@ -202,6 +202,12 @@ def main(argv: list[str] | None = None) -> None: ) http.channels = chans # /status reports per-channel connection state http.effective_cfg = cfg # /api/config (sanitized at render time) + try: + from .admin_ops import AdminWrites + + http.ops = AdminWrites(mgr, os.path.abspath(args.config)) + except Exception as e: # noqa: BLE001 + log.warning(f"admin writes disabled: {e}") http.start() log.info(f"status http on {http.host}:{http.port}") except Exception as e: # noqa: BLE001 diff --git a/tests/test_admin_ops.py b/tests/test_admin_ops.py new file mode 100644 index 0000000..382802b --- /dev/null +++ b/tests/test_admin_ops.py @@ -0,0 +1,139 @@ +"""Tests for admin write ops (channel/agent config + binding).""" + +import json +import threading +from unittest.mock import MagicMock + +import pytest + +from agenthub.admin_ops import AdminWriteError, AdminWrites +from agenthub.http_admin import StatusHTTP +from agenthub.session import AgentSpec + + +@pytest.fixture +def ops(tmp_path): + cfg = tmp_path / "config.json" + cfg.write_text(json.dumps({ + "channels": {"wecom": {"bot_id": "b1", "secret": "s1"}}, + "agents": {"opencode": {"cmd": ["opencode", "acp"]}}, + })) + mgr = MagicMock() + mgr.agents = {"opencode": AgentSpec(name="opencode", cmd=["opencode", "acp"])} + mgr.switch.return_value = {"acp_session_id": "sess-1", "migrated": 3} + mgr.get_binding.return_value = True + return AdminWrites(mgr, str(cfg)) + + +# -- channel -- + +def test_channel_upsert_new_and_update(ops): + r = ops.upsert_channel("weixin", {"token": "tok123"}) + assert r["existed"] is False and r["restart_required"] + r2 = ops.upsert_channel("weixin", {"token": "tok456"}) + assert r2["existed"] is True + cfg = json.load(open(ops.config_path)) + assert cfg["channels"]["weixin"]["token"] == "tok456" + + +def test_channel_missing_required_rejected(ops): + with pytest.raises(AdminWriteError, match="secret"): + ops.upsert_channel("wecom", {"bot_id": "x"}) + + +def test_channel_unknown_type_rejected(ops): + with pytest.raises(AdminWriteError, match="unknown channel"): + ops.upsert_channel("slack", {"token": "t"}) + + +def test_channel_unknown_field_rejected(ops): + with pytest.raises(AdminWriteError, match="unknown fields"): + ops.upsert_channel("wecom", {"bot_id": "b", "secret": "s", "foo": 1}) + + +def test_channel_delete(ops): + ops.delete_channel("wecom") + assert "wecom" not in json.load(open(ops.config_path))["channels"] + + +# -- agent -- + +def test_agent_upsert_hot_registers(ops): + r = ops.upsert_agent("coder", {"cmd": "coder acp", "default_model": "m1"}) + assert r["hot_registered"] + assert "coder" in ops.mgr.agents + assert ops.mgr.agents["coder"].default_model == "m1" + cfg = json.load(open(ops.config_path)) + assert cfg["agents"]["coder"]["cmd"] == ["coder", "acp"] + + +def test_agent_delete_last_rejected(ops): + ops2_cfg = json.load(open(ops.config_path)) + ops2_cfg["agents"] = {"solo": {"cmd": ["x"]}} + json.dump(ops2_cfg, open(ops.config_path, "w")) + ops.mgr.agents.clear() + ops.mgr.agents["solo"] = AgentSpec(name="solo", cmd=["x"]) + with pytest.raises(AdminWriteError, match="last agent"): + ops.delete_agent("solo") + + +# -- bind -- + +def test_bind_calls_switch(ops): + r = ops.bind("wecom", "chat9", "opencode") + assert r["binding"] == "wecom:chat9" + assert r["migrated_turns"] == 3 + ops.mgr.switch.assert_called_once_with("wecom", "chat9", "opencode", cont=True) + + +def test_bind_unknown_agent_rejected(ops): + with pytest.raises(AdminWriteError, match="not configured"): + ops.bind("wecom", "c", "ghost") + + +def test_unbind_missing_binding_rejected(ops): + ops.mgr.get_binding.return_value = None + with pytest.raises(AdminWriteError, match="no binding"): + ops.unbind("wecom", "c") + + +# -- HTTP layer -- + +def test_http_ops_endpoints_auth_gated(tmp_path): + cfg = tmp_path / "config.json" + cfg.write_text(json.dumps({"agents": {"a": {"cmd": ["x"]}}, "channels": {}})) + mgr = MagicMock() + mgr.agents = {"a": AgentSpec(name="a", cmd=["x"])} + mgr.switch.return_value = {"acp_session_id": "s", "migrated": 0} + mgr.get_binding.return_value = None + http = StatusHTTP(mgr, host="127.0.0.1", port=0, admin_cfg={"username": "u", "password": "p"}) + from agenthub.admin_ops import AdminWrites + http.ops = AdminWrites(mgr, str(cfg)) + http.start() + port = http._server.server_address[1] # type: ignore[union-attr] + import base64 + import urllib.error + import urllib.request + + def post(path, body, auth=True): + req = urllib.request.Request( + f"http://127.0.0.1:{port}{path}", data=json.dumps(body).encode(), method="POST" + ) + if auth: + req.add_header("Authorization", "Basic " + base64.b64encode(b"u:p").decode()) + try: + with urllib.request.urlopen(req, timeout=5) as r: + return r.status, json.loads(r.read() or b"{}") + except urllib.error.HTTPError as e: + return e.code, json.loads(e.read() or b"{}") + + # no auth -> 401 + code, _ = post("/api/agent", {"name": "b", "fields": {"cmd": "y"}}, auth=False) + assert code == 401 + # with auth -> creates agent + code, j = post("/api/agent", {"name": "b", "fields": {"cmd": "y"}}) + assert code == 200 and j["hot_registered"] + # validation error -> 400 + code, j = post("/api/channel", {"name": "wecom", "fields": {"bot_id": "b"}}) + assert code == 400 and "secret" in j["error"] + http.stop() # type: ignore[union-attr]