feat(admin): write ops — channel/agent config editing + IM<->agent binding
- admin_ops.AdminWrites: atomic config.json writes (tmp+rename), field validation (required/optional/unknown), secrets stay server-side - channels: upsert/delete for wecom|wecom-app|weixin; sets pending_restart hint (long-lived IM connections need supervisor restart) - agents: upsert hot-registers AgentSpec into live SessionManager (lazy spawn); delete guards last-agent; cmd string->list normalization - binding: reuse mgr.switch() (cross-agent history migration honored) + unbind; /api/* POST endpoints auth-gated (fail-closed) - UI: Ops tab — 3 forms (channel w/ per-type fields, agent, bind) with toasts, secret inputs masked, pending-restart banner
This commit is contained in:
1 parent
56259346d8
commit
f876f2723d
5 files changed
+489
-1
No files matched your search
@@ -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,
|
||||
}
|
||||
+105
-1
@@ -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 = """<!DOCTYPE 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=`<div class="card"><h2>Effective config (secrets redacted)</h2>
|
||||
<pre class="config">${esc(JSON.stringify(DATA.config?.config||{},null,2))}</pre></div>`;
|
||||
} 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?`<div class="card" style="border-color:var(--amber)"><h2 style="color:var(--amber)">⚠ Channel config changed</h2>
|
||||
<div class="row"><span class="k">IM channels are long-lived connections — a service restart is needed to pick up changes.</span></div></div>`:''}
|
||||
<div class="grid">
|
||||
<div class="card"><h2>1 · IM 渠道</h2>
|
||||
<div class="row"><span class="k">已配置</span><span>${esc((st.channels||[]).join(', ')||'—')}</span></div>
|
||||
<div class="row"><span class="k">类型</span><select id="ch-name">
|
||||
<option value="wecom">wecom(企微智能机器人)</option>
|
||||
<option value="wecom-app">wecom-app(企微应用)</option>
|
||||
<option value="weixin">weixin</option></select></div>
|
||||
<div id="ch-fields"></div>
|
||||
<div class="row"><button class="btn" onclick="saveChannel()">保存渠道</button>
|
||||
<button class="btn danger" onclick="delChannel()">删除</button></div>
|
||||
</div>
|
||||
<div class="card"><h2>2 · ACP Agent</h2>
|
||||
<div class="row"><span class="k">已配置</span><span>${esc((st.agents||[]).join(', ')||'—')}</span></div>
|
||||
<div class="row"><span class="k">名称</span><input id="ag-name" placeholder="opencode"></div>
|
||||
<div class="row"><span class="k">启动命令</span><input id="ag-cmd" placeholder="opencode acp" style="width:60%"></div>
|
||||
<div class="row"><span class="k">默认模型</span><input id="ag-model" placeholder="留空 = agent 默认" style="width:60%"></div>
|
||||
<div class="row"><span class="k">cwd 白名单</span><input id="ag-cwd" placeholder="逗号分隔,可空" style="width:60%"></div>
|
||||
<div class="row"><button class="btn" onclick="saveAgent()">保存 Agent</button>
|
||||
<button class="btn danger" onclick="delAgent()">删除</button></div>
|
||||
</div>
|
||||
<div class="card"><h2>3 · 绑定 IM ⇄ Agent</h2>
|
||||
<div class="row"><span class="k">channel</span><input id="bd-ch" placeholder="wecom" style="width:50%"></div>
|
||||
<div class="row"><span class="k">chat_id</span><input id="bd-chat" placeholder="会话 ID" style="width:50%"></div>
|
||||
<div class="row"><span class="k">agent</span><select id="bd-ag">${(st.agents||[]).map(a=>`<option>${esc(a)}</option>`).join('')}</select></div>
|
||||
<div class="row"><label class="k"><input type="checkbox" id="bd-cont" checked> 保留历史(跨 agent 迁移文本)</label></div>
|
||||
<div class="row"><button class="btn" onclick="doBind()">绑定</button>
|
||||
<button class="btn danger" onclick="doUnbind()">解绑</button></div>
|
||||
<div class="meta">绑定即建立新 ACP 会话并写库;会话里用户可随时 /switch。</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="ops-toast" style="min-height:26px;font-size:15px;margin-top:8px"></div>`;
|
||||
$('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])=>`<div class="row"><span class="k">${esc(k)}</span>
|
||||
<input id="chf-${esc(k)}" placeholder="${esc(ph)}" style="width:55%" type="${k==='secret'||k==='token'?'password':'text'}"></div>`).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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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]
|
||||
Reference in new issue
Block a user