feat(admin): sqlite-backed config CRUD + full management UI
- config doc moves to agenthub.db table 'config' (single JSON doc, id=1); config.json is first-run seed only; same db as bindings/records - AdminStore: sqlite doc store (thread-locked, persists across restarts) - full CRUD per entity: list/get/upsert/delete for channels + agents, bind/unbind for bindings; upsert merges blank secret fields (edit form can leave them empty); last-agent delete guard; unknown-field 400s - secrets masked at list/get time (yb…[REDACTED]); plaintext never crosses the API - Ops tab rebuilt: list tables w/ per-row edit+delete buttons, +新增 forms, delete confirm() dialogs, live binding table w/ unbind
This commit is contained in:
1 parent
f876f2723d
commit
355446c80a
5 files changed
+339
-173
No files matched your search
+148
-82
@@ -1,24 +1,22 @@
|
|||||||
"""Admin write operations: config channels/agents + binding (UI-backed).
|
"""Admin write operations — sqlite-backed config CRUD.
|
||||||
|
|
||||||
All writes go through:
|
Config lives in agenthub.db table `config` (single JSON doc, id=1).
|
||||||
1. config.json update (atomic tmp+rename) — persisted source of truth
|
The JSON boot file is only used to seed the doc on first run.
|
||||||
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
|
CRUD semantics:
|
||||||
redacts at render time (sanitize_config). This module never echoes them.
|
- list/get: secrets masked (UI tables/forms never see plaintext)
|
||||||
|
- upsert: blank/omitted secret fields merge with existing values
|
||||||
|
(so the edit form can leave them empty)
|
||||||
|
- delete: guarded (last agent protected; unknown name -> 400)
|
||||||
|
- channels need supervisor restart to take effect (long-lived IM
|
||||||
|
connections); agents hot-register into the live SessionManager
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import sqlite3
|
||||||
import threading
|
import threading
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -38,37 +36,76 @@ CHANNEL_OPTIONAL: dict[str, list[str]] = {
|
|||||||
}
|
}
|
||||||
AGENT_REQUIRED = ["cmd"]
|
AGENT_REQUIRED = ["cmd"]
|
||||||
AGENT_OPTIONAL = ["cwd_whitelist", "default_model"]
|
AGENT_OPTIONAL = ["cwd_whitelist", "default_model"]
|
||||||
|
SECRET_KEYS = {"secret", "token"}
|
||||||
SECRET_KEYS = {"secret", "token", "app_secret", "key"}
|
|
||||||
|
|
||||||
|
|
||||||
class AdminWriteError(ValueError):
|
class AdminWriteError(ValueError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class AdminWrites:
|
class AdminStore:
|
||||||
"""Holds config path + mgr ref; executes validated mutations."""
|
"""sqlite-backed config document store (agenthub.db table `config`)."""
|
||||||
|
|
||||||
def __init__(self, mgr: Any, config_path: str):
|
def __init__(self, db_path: str):
|
||||||
self.mgr = mgr
|
self.db_path = db_path
|
||||||
self.config_path = config_path
|
|
||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
self.pending_restart = False # channels changed -> needs supervisor restart
|
os.makedirs(os.path.dirname(db_path) or ".", exist_ok=True)
|
||||||
|
self._db = sqlite3.connect(db_path, check_same_thread=False)
|
||||||
|
self._db.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS config ("
|
||||||
|
"id INTEGER PRIMARY KEY CHECK(id=1), doc TEXT NOT NULL)"
|
||||||
|
)
|
||||||
|
self._db.commit()
|
||||||
|
|
||||||
# -- config io ----------------------------------------------------------
|
def load(self) -> dict[str, Any]:
|
||||||
|
row = self._db.execute("SELECT doc FROM config WHERE id=1").fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise AdminWriteError("config not seeded")
|
||||||
|
return json.loads(row[0])
|
||||||
|
|
||||||
|
def save(self, cfg: dict[str, Any]) -> None:
|
||||||
|
doc = json.dumps(cfg, ensure_ascii=False, indent=2)
|
||||||
|
with self._lock:
|
||||||
|
self._db.execute(
|
||||||
|
"INSERT INTO config(id,doc) VALUES(1,?) "
|
||||||
|
"ON CONFLICT(id) DO UPDATE SET doc=excluded.doc",
|
||||||
|
(doc,),
|
||||||
|
)
|
||||||
|
self._db.commit()
|
||||||
|
|
||||||
|
def seeded(self) -> bool:
|
||||||
|
return self._db.execute("SELECT 1 FROM config WHERE id=1").fetchone() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def seed_from_json(store: AdminStore, json_path: str) -> bool:
|
||||||
|
"""First-run bootstrap: copy config.json into sqlite. True if seeded now."""
|
||||||
|
if store.seeded():
|
||||||
|
return False
|
||||||
|
with open(json_path, encoding="utf-8") as f:
|
||||||
|
store.save(json.load(f))
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
class AdminWrites:
|
||||||
|
"""CRUD over the sqlite config doc + live session manager."""
|
||||||
|
|
||||||
|
def __init__(self, mgr: Any, store: AdminStore):
|
||||||
|
self.mgr = mgr
|
||||||
|
self.store = store
|
||||||
|
self.pending_restart = False
|
||||||
|
|
||||||
|
# -- helpers ------------------------------------------------------------
|
||||||
|
|
||||||
def _load(self) -> dict[str, Any]:
|
def _load(self) -> dict[str, Any]:
|
||||||
with open(self.config_path, encoding="utf-8") as f:
|
return self.store.load()
|
||||||
return json.load(f)
|
|
||||||
|
|
||||||
def _save(self, cfg: dict[str, Any]) -> None:
|
def _save(self, cfg: dict[str, Any]) -> None:
|
||||||
tmp = self.config_path + ".tmp"
|
self.store.save(cfg)
|
||||||
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 _mask(v: Any) -> str:
|
||||||
|
s = str(v)
|
||||||
|
return (s[:2] + "…[REDACTED]") if len(s) > 6 else "[REDACTED]"
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _clean_fields(kind: str, fields: dict[str, Any], required: list[str],
|
def _clean_fields(kind: str, fields: dict[str, Any], required: list[str],
|
||||||
@@ -76,30 +113,55 @@ class AdminWrites:
|
|||||||
out: dict[str, Any] = {}
|
out: dict[str, Any] = {}
|
||||||
for k in required:
|
for k in required:
|
||||||
v = fields.get(k)
|
v = fields.get(k)
|
||||||
if not v or not str(v).strip():
|
if v is None or (isinstance(v, str) and not v.strip()):
|
||||||
raise AdminWriteError(f"{kind}: missing required field {k!r}")
|
raise AdminWriteError(f"{kind}: missing required field {k!r}")
|
||||||
out[k] = v if isinstance(v, (int, float)) else str(v).strip()
|
if isinstance(v, (int, float, list)):
|
||||||
|
out[k] = v
|
||||||
|
else:
|
||||||
|
out[k] = str(v).strip()
|
||||||
for k in optional:
|
for k in optional:
|
||||||
if k in fields and fields[k] not in (None, ""):
|
if fields.get(k) not in (None, ""):
|
||||||
out[k] = fields[k]
|
out[k] = fields[k]
|
||||||
unknown = set(fields) - set(required) - set(optional)
|
unknown = set(fields) - set(required) - set(optional)
|
||||||
if unknown:
|
if unknown:
|
||||||
raise AdminWriteError(f"{kind}: unknown fields {sorted(unknown)}")
|
raise AdminWriteError(f"{kind}: unknown fields {sorted(unknown)}")
|
||||||
return out
|
return out
|
||||||
|
|
||||||
# -- 1. IM channel ------------------------------------------------------
|
# -- CHANNEL CRUD -------------------------------------------------------
|
||||||
|
|
||||||
|
def list_channels(self) -> list[dict[str, Any]]:
|
||||||
|
ccfg = self._load().get("channels", {})
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"name": name,
|
||||||
|
"fields": {
|
||||||
|
k: (self._mask(v) if k in SECRET_KEYS else v)
|
||||||
|
for k, v in fields.items()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for name, fields in sorted(ccfg.items())
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_channel(self, name: str) -> dict[str, Any]:
|
||||||
|
fields = self._load().get("channels", {}).get(name)
|
||||||
|
if fields is None:
|
||||||
|
raise AdminWriteError(f"channel {name!r} not configured")
|
||||||
|
return {
|
||||||
|
"name": name,
|
||||||
|
"fields": {k: (self._mask(v) if k in SECRET_KEYS else v) for k, v in fields.items()},
|
||||||
|
}
|
||||||
|
|
||||||
def upsert_channel(self, name: str, fields: dict[str, Any]) -> dict[str, Any]:
|
def upsert_channel(self, name: str, fields: dict[str, Any]) -> dict[str, Any]:
|
||||||
if name not in VALID_CHANNELS:
|
if name not in VALID_CHANNELS:
|
||||||
raise AdminWriteError(
|
raise AdminWriteError(f"unknown channel {name!r}; valid: {sorted(VALID_CHANNELS)}")
|
||||||
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()
|
cfg = self._load()
|
||||||
|
merged = dict(cfg.get("channels", {}).get(name, {}))
|
||||||
|
for k, v in fields.items():
|
||||||
|
if v is None or (isinstance(v, str) and not v.strip()):
|
||||||
|
continue # blank = keep existing (edit form leaves secrets empty)
|
||||||
|
merged[k] = v
|
||||||
|
cleaned = self._clean_fields(f"channel {name}", merged,
|
||||||
|
CHANNEL_REQUIRED[name], CHANNEL_OPTIONAL[name])
|
||||||
existed = name in cfg.get("channels", {})
|
existed = name in cfg.get("channels", {})
|
||||||
cfg.setdefault("channels", {})[name] = cleaned
|
cfg.setdefault("channels", {})[name] = cleaned
|
||||||
self._save(cfg)
|
self._save(cfg)
|
||||||
@@ -107,7 +169,6 @@ class AdminWrites:
|
|||||||
return {"channel": name, "existed": existed, "restart_required": True}
|
return {"channel": name, "existed": existed, "restart_required": True}
|
||||||
|
|
||||||
def delete_channel(self, name: str) -> dict[str, Any]:
|
def delete_channel(self, name: str) -> dict[str, Any]:
|
||||||
with self._lock:
|
|
||||||
cfg = self._load()
|
cfg = self._load()
|
||||||
if name not in cfg.get("channels", {}):
|
if name not in cfg.get("channels", {}):
|
||||||
raise AdminWriteError(f"channel {name!r} not configured")
|
raise AdminWriteError(f"channel {name!r} not configured")
|
||||||
@@ -116,38 +177,57 @@ class AdminWrites:
|
|||||||
self.pending_restart = True
|
self.pending_restart = True
|
||||||
return {"channel": name, "deleted": True, "restart_required": True}
|
return {"channel": name, "deleted": True, "restart_required": True}
|
||||||
|
|
||||||
# -- 2. ACP agent -------------------------------------------------------
|
# -- AGENT CRUD ---------------------------------------------------------
|
||||||
|
|
||||||
|
def list_agents(self) -> list[dict[str, Any]]:
|
||||||
|
acfg = self._load().get("agents", {})
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"name": name,
|
||||||
|
"cmd": " ".join(s["cmd"]) if isinstance(s.get("cmd"), list) else s.get("cmd", ""),
|
||||||
|
"default_model": s.get("default_model") or "",
|
||||||
|
"cwd_whitelist": ", ".join(s.get("cwd_whitelist") or []),
|
||||||
|
}
|
||||||
|
for name, s in sorted(acfg.items())
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_agent(self, name: str) -> dict[str, Any]:
|
||||||
|
s = self._load().get("agents", {}).get(name)
|
||||||
|
if s is None:
|
||||||
|
raise AdminWriteError(f"agent {name!r} not configured")
|
||||||
|
return {
|
||||||
|
"name": name,
|
||||||
|
"cmd": " ".join(s["cmd"]) if isinstance(s.get("cmd"), list) else s.get("cmd", ""),
|
||||||
|
"default_model": s.get("default_model") or "",
|
||||||
|
"cwd_whitelist": ", ".join(s.get("cwd_whitelist") or []),
|
||||||
|
}
|
||||||
|
|
||||||
def upsert_agent(self, name: str, fields: dict[str, Any]) -> dict[str, Any]:
|
def upsert_agent(self, name: str, fields: dict[str, Any]) -> dict[str, Any]:
|
||||||
if not name or "/" in name or " " in name:
|
if not name or "/" in name or " " in name:
|
||||||
raise AdminWriteError(f"invalid agent name {name!r}")
|
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()
|
cfg = self._load()
|
||||||
|
merged = dict(cfg.get("agents", {}).get(name, {}))
|
||||||
|
for k, v in fields.items():
|
||||||
|
if v is None or (isinstance(v, str) and not v.strip()):
|
||||||
|
continue
|
||||||
|
merged[k] = v
|
||||||
|
if isinstance(merged.get("cmd"), str):
|
||||||
|
merged["cmd"] = merged["cmd"].split()
|
||||||
|
wl = merged.get("cwd_whitelist")
|
||||||
|
if wl is not None and not isinstance(wl, list):
|
||||||
|
merged["cwd_whitelist"] = [p.strip() for p in str(wl).split(",") if p.strip()]
|
||||||
|
cleaned = self._clean_fields(f"agent {name}", merged, AGENT_REQUIRED, AGENT_OPTIONAL)
|
||||||
existed = name in cfg.get("agents", {})
|
existed = name in cfg.get("agents", {})
|
||||||
cfg.setdefault("agents", {})[name] = cleaned
|
cfg.setdefault("agents", {})[name] = cleaned
|
||||||
self._save(cfg)
|
self._save(cfg)
|
||||||
# live hot-register (new agents spawn lazily on first use)
|
|
||||||
self.mgr.agents[name] = AgentSpec(
|
self.mgr.agents[name] = AgentSpec(
|
||||||
name=name,
|
name=name, cmd=cleaned["cmd"],
|
||||||
cmd=cleaned["cmd"],
|
|
||||||
cwd_whitelist=cleaned.get("cwd_whitelist", []),
|
cwd_whitelist=cleaned.get("cwd_whitelist", []),
|
||||||
default_model=cleaned.get("default_model"),
|
default_model=cleaned.get("default_model"),
|
||||||
)
|
)
|
||||||
return {"agent": name, "existed": existed, "hot_registered": True}
|
return {"agent": name, "existed": existed, "hot_registered": True}
|
||||||
|
|
||||||
def delete_agent(self, name: str) -> dict[str, Any]:
|
def delete_agent(self, name: str) -> dict[str, Any]:
|
||||||
with self._lock:
|
|
||||||
cfg = self._load()
|
cfg = self._load()
|
||||||
if name not in cfg.get("agents", {}):
|
if name not in cfg.get("agents", {}):
|
||||||
raise AdminWriteError(f"agent {name!r} not configured")
|
raise AdminWriteError(f"agent {name!r} not configured")
|
||||||
@@ -158,31 +238,17 @@ class AdminWrites:
|
|||||||
self.mgr.agents.pop(name, None)
|
self.mgr.agents.pop(name, None)
|
||||||
return {"agent": name, "deleted": True}
|
return {"agent": name, "deleted": True}
|
||||||
|
|
||||||
# -- 3. bind IM chat <-> agent ------------------------------------------
|
# -- BINDING CRUD -------------------------------------------------------
|
||||||
|
|
||||||
def bind(self, channel: str, chat_id: str, agent: str,
|
def bind(self, channel: str, chat_id: str, agent: str,
|
||||||
continue_history: bool = True) -> dict[str, Any]:
|
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:
|
if not channel or not chat_id:
|
||||||
raise AdminWriteError("channel and chat_id are required")
|
raise AdminWriteError("channel and chat_id are required")
|
||||||
if agent not in self.mgr.agents:
|
if agent not in self.mgr.agents:
|
||||||
raise AdminWriteError(
|
raise AdminWriteError(f"agent {agent!r} not configured; known: {sorted(self.mgr.agents)}")
|
||||||
f"agent {agent!r} not configured; known: {sorted(self.mgr.agents)}"
|
|
||||||
)
|
|
||||||
res = self.mgr.switch(channel, chat_id, agent, cont=continue_history)
|
res = self.mgr.switch(channel, chat_id, agent, cont=continue_history)
|
||||||
return {
|
return {"binding": f"{channel}:{chat_id}", "agent": agent,
|
||||||
"binding": f"{channel}:{chat_id}",
|
"acp_session_id": res.get("acp_session_id"), "migrated_turns": res.get("migrated", 0)}
|
||||||
"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]:
|
def unbind(self, channel: str, chat_id: str) -> dict[str, Any]:
|
||||||
if self.mgr.get_binding(channel, chat_id) is None:
|
if self.mgr.get_binding(channel, chat_id) is None:
|
||||||
@@ -190,12 +256,12 @@ class AdminWrites:
|
|||||||
self.mgr.unbind(channel, chat_id)
|
self.mgr.unbind(channel, chat_id)
|
||||||
return {"binding": f"{channel}:{chat_id}", "deleted": True}
|
return {"binding": f"{channel}:{chat_id}", "deleted": True}
|
||||||
|
|
||||||
# -- status -------------------------------------------------------------
|
# -- overview -----------------------------------------------------------
|
||||||
|
|
||||||
def state(self) -> dict[str, Any]:
|
def state(self) -> dict[str, Any]:
|
||||||
cfg = self._load()
|
|
||||||
return {
|
return {
|
||||||
"channels": sorted(cfg.get("channels", {})),
|
"channels": self.list_channels(),
|
||||||
"agents": sorted(cfg.get("agents", {})),
|
"agents": self.list_agents(),
|
||||||
"pending_restart": self.pending_restart,
|
"pending_restart": self.pending_restart,
|
||||||
|
"storage": "sqlite",
|
||||||
}
|
}
|
||||||
+81
-40
@@ -59,6 +59,7 @@ input:focus,select:focus{outline:none;border-color:var(--blue)}
|
|||||||
.btn:hover{border-color:var(--blue);color:var(--blue)}
|
.btn:hover{border-color:var(--blue);color:var(--blue)}
|
||||||
.btn.danger{color:var(--red)}
|
.btn.danger{color:var(--red)}
|
||||||
.btn.danger:hover{border-color:var(--red)}
|
.btn.danger:hover{border-color:var(--red)}
|
||||||
|
.btn.sm{padding:4px 12px;font-size:13px}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
HTML = """<!DOCTYPE html>
|
HTML = """<!DOCTYPE html>
|
||||||
@@ -164,82 +165,122 @@ async function renderOps(){
|
|||||||
const P=$('panes');
|
const P=$('panes');
|
||||||
let st={channels:[],agents:[]};
|
let st={channels:[],agents:[]};
|
||||||
try{ st=await post('api/ops-state',{})||st; }catch(e){}
|
try{ st=await post('api/ops-state',{})||st; }catch(e){}
|
||||||
|
DATA.ops=st;
|
||||||
const pend=st.pending_restart;
|
const pend=st.pending_restart;
|
||||||
|
const chRows=(st.channels||[]).map(c=>`<tr><td>${esc(c.name)}</td>`+
|
||||||
|
Object.entries(c.fields).map(([k,v])=>`<td>${esc(String(v))}${String(v).includes('REDACTED')?' <span class="age">(输入留空=保留)</span>':''}</td>`).join('')+
|
||||||
|
`<td><button class="btn sm" onclick="editChannel('${esc(c.name)}')">编辑</button>
|
||||||
|
<button class="btn sm danger" onclick="delItem('channel','${esc(c.name)}')">删除</button></td></tr>`).join('');
|
||||||
|
const agRows=(st.agents||[]).map(a=>`<tr><td>${esc(a.name)}</td><td><code>${esc(a.cmd)}</code></td>
|
||||||
|
<td>${esc(a.default_model||'—')}</td><td>${esc(a.cwd_whitelist||'—')}</td>
|
||||||
|
<td><button class="btn sm" onclick="editAgent('${esc(a.name)}')">编辑</button>
|
||||||
|
<button class="btn sm danger" onclick="delItem('agent','${esc(a.name)}')">删除</button></td></tr>`).join('');
|
||||||
P.innerHTML=`
|
P.innerHTML=`
|
||||||
${pend?`<div class="card" style="border-color:var(--amber)"><h2 style="color:var(--amber)">⚠ Channel config changed</h2>
|
${pend?`<div class="card" style="border-color:var(--amber)"><h2 style="color:var(--amber)">⚠ 渠道配置已变更</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="row"><span class="k">IM 渠道是长连接,需重启服务后生效(保存 agent 不需要)。</span></div></div>`:''}
|
||||||
<div class="grid">
|
<div class="grid">
|
||||||
<div class="card"><h2>1 · IM 渠道</h2>
|
<div class="card" style="grid-column:1/-1"><h2>IM 渠道 <button class="btn sm" onclick="newChannel()">+ 新增</button></h2>
|
||||||
<div class="row"><span class="k">已配置</span><span>${esc((st.channels||[]).join(', ')||'—')}</span></div>
|
<table><tr><th>类型</th><th>字段</th><th></th></tr>${chRows||'<tr><td colspan="9"><div class="empty">无</div></td></tr>'}</table>
|
||||||
<div class="row"><span class="k">类型</span><select id="ch-name">
|
<div id="ch-form"></div>
|
||||||
<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>
|
||||||
<div class="card"><h2>2 · ACP Agent</h2>
|
<div class="card" style="grid-column:1/-1"><h2>ACP Agent <button class="btn sm" onclick="newAgent()">+ 新增</button></h2>
|
||||||
<div class="row"><span class="k">已配置</span><span>${esc((st.agents||[]).join(', ')||'—')}</span></div>
|
<table><tr><th>名称</th><th>命令</th><th>默认模型</th><th>cwd 白名单</th><th></th></tr>${agRows||'<tr><td colspan="5"><div class="empty">无</div></td></tr>'}</table>
|
||||||
<div class="row"><span class="k">名称</span><input id="ag-name" placeholder="opencode"></div>
|
<div id="ag-form"></div>
|
||||||
<div class="row"><span class="k">启动命令</span><input id="ag-cmd" placeholder="opencode acp" style="width:60%"></div>
|
<div class="meta">保存即时生效(进程懒启动);删除有末位保护。</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>
|
||||||
<div class="card"><h2>3 · 绑定 IM ⇄ Agent</h2>
|
<div class="card"><h2>绑定 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">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">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"><span class="k">agent</span><select id="bd-ag">${(st.agents||[]).map(a=>`<option>${esc(a.name)}</option>`).join('')}</select></div>
|
||||||
<div class="row"><label class="k"><input type="checkbox" id="bd-cont" checked> 保留历史(跨 agent 迁移文本)</label></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>
|
<div class="row"><button class="btn" onclick="doBind()">绑定</button></div>
|
||||||
<button class="btn danger" onclick="doUnbind()">解绑</button></div>
|
|
||||||
<div class="meta">绑定即建立新 ACP 会话并写库;会话里用户可随时 /switch。</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div class="card"><h2>当前绑定</h2>${bindTable()}</div>
|
||||||
</div>
|
</div>
|
||||||
<div id="ops-toast" style="min-height:26px;font-size:15px;margin-top:8px"></div>`;
|
<div id="ops-toast" style="min-height:26px;font-size:15px;margin-top:8px"></div>`;
|
||||||
|
}
|
||||||
|
function bindTable(){
|
||||||
|
const bs=(DATA.sessions0?.bindings||[]);
|
||||||
|
return bs.length?`<table><tr><th>channel</th><th>chat</th><th>agent</th><th></th></tr>`+
|
||||||
|
bs.map(b=>`<tr><td>${esc(b.channel)}</td><td>${esc(b.chat_id)}</td><td>${esc(b.agent)}</td>
|
||||||
|
<td><button class="btn sm danger" onclick="doUnbind('${esc(b.channel)}','${esc(b.chat_id)}')">解绑</button></td></tr>`).join('')+'</table>'
|
||||||
|
:'<div class="empty">无绑定</div>';
|
||||||
|
}
|
||||||
|
const CH_LABEL={wecom:'wecom(企微智能机器人)','wecom-app':'wecom-app(企微应用)',weixin:'weixin'};
|
||||||
|
function newChannel(){
|
||||||
|
$('ag-form').innerHTML='';
|
||||||
|
$('ch-form').innerHTML=`
|
||||||
|
<div class="row"><span class="k">类型</span><select id="ch-name">${Object.entries(CH_LABEL).map(([k,v])=>`<option value="${k}">${v}</option>`).join('')}</select></div>
|
||||||
|
<div id="ch-fields"></div>
|
||||||
|
<div class="row"><button class="btn" onclick="saveChannel()">保存</button>
|
||||||
|
<button class="btn" onclick="$('ch-form').innerHTML=''">取消</button></div>`;
|
||||||
$('ch-name').onchange=renderChFields;renderChFields();
|
$('ch-name').onchange=renderChFields;renderChFields();
|
||||||
|
$('ch-form').scrollIntoView({behavior:'smooth'});
|
||||||
|
}
|
||||||
|
async function editChannel(name){
|
||||||
|
try{ const c=await post('api/channel/get',{name});
|
||||||
|
newChannel();
|
||||||
|
$('ch-name').value=name;$('ch-name').disabled=true;renderChFields();
|
||||||
|
Object.entries(c.fields).forEach(([k,v])=>{const i=$('chf-'+k);if(i)i.value=v;});
|
||||||
|
$('ch-form').scrollIntoView({behavior:'smooth'});
|
||||||
|
}catch(e){toast(false,e.message)}
|
||||||
}
|
}
|
||||||
function renderChFields(){
|
function renderChFields(){
|
||||||
const req={wecom:[['bot_id','bot_id'],['secret','secret(写入 config.json,不回显)']],
|
const req={wecom:[['bot_id','bot_id'],['secret','留空 = 保留原值']],
|
||||||
'wecom-app':[['corp_id','corp_id'],['secret','secret'],['agent_id','agent_id']],
|
'wecom-app':[['corp_id','corp_id'],['secret','留空 = 保留原值'],['agent_id','agent_id']],
|
||||||
weixin:[['token','token']]}[$('ch-name').value]||[];
|
weixin:[['token','留空 = 保留原值']]}[$('ch-name').value]||[];
|
||||||
$('ch-fields').innerHTML=req.map(([k,ph])=>`<div class="row"><span class="k">${esc(k)}</span>
|
$('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('');
|
<input id="chf-${esc(k)}" placeholder="${esc(ph)}" style="width:55%" type="${k==='secret'||k==='token'?'password':'text'}"></div>`).join('');
|
||||||
}
|
}
|
||||||
async function saveChannel(){
|
async function saveChannel(){
|
||||||
try{ const name=$('ch-name').value;
|
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 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});
|
await post('api/channel',{name,fields});
|
||||||
toast(true,`渠道 ${name} 已保存`+(r.existed?'(覆盖)':'')+' · 需重启生效');
|
toast(true,`渠道 ${name} 已保存 · 需重启生效`);renderOps();
|
||||||
}catch(e){toast(false,e.message)}
|
}catch(e){toast(false,e.message)}
|
||||||
}
|
}
|
||||||
async function delChannel(){
|
function newAgent(){
|
||||||
try{ await post('api/channel/delete',{name:$('ch-name').value});
|
$('ch-form').innerHTML='';
|
||||||
toast(true,'渠道已删除 · 需重启生效'); }catch(e){toast(false,e.message)}
|
$('ag-form').innerHTML=`
|
||||||
|
<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()">保存</button>
|
||||||
|
<button class="btn" onclick="$('ag-form').innerHTML=''">取消</button></div>`;
|
||||||
|
}
|
||||||
|
async function editAgent(name){
|
||||||
|
try{ const a=await post('api/agent/get',{name});
|
||||||
|
newAgent();
|
||||||
|
$('ag-name').value=a.name;$('ag-name').disabled=true;
|
||||||
|
$('ag-cmd').value=a.cmd;$('ag-model').value=a.default_model;$('ag-cwd').value=a.cwd_whitelist;
|
||||||
|
$('ag-form').scrollIntoView({behavior:'smooth'});
|
||||||
|
}catch(e){toast(false,e.message)}
|
||||||
}
|
}
|
||||||
async function saveAgent(){
|
async function saveAgent(){
|
||||||
try{ const name=$('ag-name').value.trim();
|
try{ const name=$('ag-name').value.trim();
|
||||||
const fields={cmd:$('ag-cmd').value};
|
const fields={cmd:$('ag-cmd').value};
|
||||||
if($('ag-model').value)fields.default_model=$('ag-model').value.trim();
|
if($('ag-model').value)fields.default_model=$('ag-model').value.trim();
|
||||||
if($('ag-cwd').value)fields.cwd_whitelist=$('ag-cwd').value;
|
if($('ag-cwd').value)fields.cwd_whitelist=$('ag-cwd').value;
|
||||||
const r=await post('api/agent',{name,fields});
|
await post('api/agent',{name,fields});
|
||||||
toast(true,`agent ${name} 已保存`+(r.existed?'(覆盖)':'')+',即时生效');
|
toast(true,`agent ${name} 已保存,即时生效`);renderOps();
|
||||||
}catch(e){toast(false,e.message)}
|
}catch(e){toast(false,e.message)}
|
||||||
}
|
}
|
||||||
async function delAgent(){
|
async function delItem(kind,name){
|
||||||
try{ await post('api/agent/delete',{name:$('ag-name').value.trim()});
|
if(!confirm(`确认删除 ${kind} "${name}"?`))return;
|
||||||
toast(true,'agent 已删除'); }catch(e){toast(false,e.message)}
|
try{ await post(`api/${kind}/delete`,{name});
|
||||||
|
toast(true,`${kind} ${name} 已删除`);renderOps();
|
||||||
|
}catch(e){toast(false,e.message)}
|
||||||
}
|
}
|
||||||
async function doBind(){
|
async function doBind(){
|
||||||
try{ const r=await post('api/bind',{channel:$('bd-ch').value.trim(),chat_id:$('bd-chat').value.trim(),
|
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});
|
agent:$('bd-ag').value,continue_history:$('bd-cont').checked});
|
||||||
toast(true,`已绑定 ${r.binding} → ${r.agent}(会话 ${String(r.acp_session_id).slice(0,12)}…)`);load();
|
toast(true,`已绑定 ${r.binding} → ${r.agent}`);load();
|
||||||
}catch(e){toast(false,e.message)}
|
}catch(e){toast(false,e.message)}
|
||||||
}
|
}
|
||||||
async function doUnbind(){
|
async function doUnbind(ch,chat){
|
||||||
try{ await post('api/unbind',{channel:$('bd-ch').value.trim(),chat_id:$('bd-chat').value.trim()});
|
if(!confirm(`确认解绑 ${ch}:${chat}?`))return;
|
||||||
|
try{ await post('api/unbind',{channel:ch,chat_id:chat});
|
||||||
toast(true,'已解绑');load(); }catch(e){toast(false,e.message)}
|
toast(true,'已解绑');load(); }catch(e){toast(false,e.message)}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -171,10 +171,14 @@ class StatusHTTP:
|
|||||||
self._json(200, ops.upsert_channel(req["name"], req.get("fields", {})))
|
self._json(200, ops.upsert_channel(req["name"], req.get("fields", {})))
|
||||||
elif path == "/api/channel/delete":
|
elif path == "/api/channel/delete":
|
||||||
self._json(200, ops.delete_channel(req["name"]))
|
self._json(200, ops.delete_channel(req["name"]))
|
||||||
|
elif path == "/api/channel/get":
|
||||||
|
self._json(200, ops.get_channel(req["name"]))
|
||||||
elif path == "/api/agent":
|
elif path == "/api/agent":
|
||||||
self._json(200, ops.upsert_agent(req["name"], req.get("fields", {})))
|
self._json(200, ops.upsert_agent(req["name"], req.get("fields", {})))
|
||||||
elif path == "/api/agent/delete":
|
elif path == "/api/agent/delete":
|
||||||
self._json(200, ops.delete_agent(req["name"]))
|
self._json(200, ops.delete_agent(req["name"]))
|
||||||
|
elif path == "/api/agent/get":
|
||||||
|
self._json(200, ops.get_agent(req["name"]))
|
||||||
elif path == "/api/bind":
|
elif path == "/api/bind":
|
||||||
self._json(200, ops.bind(
|
self._json(200, ops.bind(
|
||||||
req["channel"], str(req["chat_id"]), req["agent"],
|
req["channel"], str(req["chat_id"]), req["agent"],
|
||||||
|
|||||||
+11
-2
@@ -203,9 +203,18 @@ def main(argv: list[str] | None = None) -> None:
|
|||||||
http.channels = chans # /status reports per-channel connection state
|
http.channels = chans # /status reports per-channel connection state
|
||||||
http.effective_cfg = cfg # /api/config (sanitized at render time)
|
http.effective_cfg = cfg # /api/config (sanitized at render time)
|
||||||
try:
|
try:
|
||||||
from .admin_ops import AdminWrites
|
from .admin_ops import AdminStore, AdminWrites, seed_from_json
|
||||||
|
|
||||||
http.ops = AdminWrites(mgr, os.path.abspath(args.config))
|
# config doc lives in sqlite (same db as bindings/records);
|
||||||
|
# config.json is only the first-run seed
|
||||||
|
sess = cfg.get("session", {})
|
||||||
|
db_path = sess.get("db_path") or os.path.join(
|
||||||
|
os.path.dirname(os.path.abspath(args.config)), "agenthub.db"
|
||||||
|
)
|
||||||
|
store = AdminStore(db_path)
|
||||||
|
if seed_from_json(store, os.path.abspath(args.config)):
|
||||||
|
log.info(f"config seeded into sqlite from {args.config}")
|
||||||
|
http.ops = AdminWrites(mgr, store)
|
||||||
except Exception as e: # noqa: BLE001
|
except Exception as e: # noqa: BLE001
|
||||||
log.warning(f"admin writes disabled: {e}")
|
log.warning(f"admin writes disabled: {e}")
|
||||||
http.start()
|
http.start()
|
||||||
|
|||||||
+95
-49
@@ -1,44 +1,85 @@
|
|||||||
"""Tests for admin write ops (channel/agent config + binding)."""
|
"""Tests for admin write ops (sqlite-backed CRUD: channel/agent/binding)."""
|
||||||
|
|
||||||
|
import base64
|
||||||
import json
|
import json
|
||||||
import threading
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from agenthub.admin_ops import AdminWriteError, AdminWrites
|
from agenthub.admin_ops import AdminStore, AdminWriteError, AdminWrites, seed_from_json
|
||||||
from agenthub.http_admin import StatusHTTP
|
from agenthub.http_admin import StatusHTTP
|
||||||
from agenthub.session import AgentSpec
|
from agenthub.session import AgentSpec
|
||||||
|
|
||||||
|
BOOT = {
|
||||||
@pytest.fixture
|
|
||||||
def ops(tmp_path):
|
|
||||||
cfg = tmp_path / "config.json"
|
|
||||||
cfg.write_text(json.dumps({
|
|
||||||
"channels": {"wecom": {"bot_id": "b1", "secret": "s1"}},
|
"channels": {"wecom": {"bot_id": "b1", "secret": "s1"}},
|
||||||
"agents": {"opencode": {"cmd": ["opencode", "acp"]}},
|
"agents": {"opencode": {"cmd": ["opencode", "acp"]}},
|
||||||
}))
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def make_mgr():
|
||||||
mgr = MagicMock()
|
mgr = MagicMock()
|
||||||
mgr.agents = {"opencode": AgentSpec(name="opencode", cmd=["opencode", "acp"])}
|
mgr.agents = {"opencode": AgentSpec(name="opencode", cmd=["opencode", "acp"])}
|
||||||
mgr.switch.return_value = {"acp_session_id": "sess-1", "migrated": 3}
|
mgr.switch.return_value = {"acp_session_id": "sess-1", "migrated": 3}
|
||||||
mgr.get_binding.return_value = True
|
mgr.get_binding.return_value = True
|
||||||
return AdminWrites(mgr, str(cfg))
|
return mgr
|
||||||
|
|
||||||
|
|
||||||
# -- channel --
|
@pytest.fixture
|
||||||
|
def ops(tmp_path):
|
||||||
|
boot = tmp_path / "config.json"
|
||||||
|
boot.write_text(json.dumps(BOOT))
|
||||||
|
store = AdminStore(str(tmp_path / "agenthub.db"))
|
||||||
|
seed_from_json(store, str(boot))
|
||||||
|
return AdminWrites(make_mgr(), store)
|
||||||
|
|
||||||
def test_channel_upsert_new_and_update(ops):
|
|
||||||
r = ops.upsert_channel("weixin", {"token": "tok123"})
|
# -- store / seeding --
|
||||||
assert r["existed"] is False and r["restart_required"]
|
|
||||||
r2 = ops.upsert_channel("weixin", {"token": "tok456"})
|
def test_store_seed_once(tmp_path):
|
||||||
assert r2["existed"] is True
|
boot = tmp_path / "config.json"
|
||||||
cfg = json.load(open(ops.config_path))
|
boot.write_text(json.dumps(BOOT))
|
||||||
assert cfg["channels"]["weixin"]["token"] == "tok456"
|
store = AdminStore(str(tmp_path / "db.sqlite"))
|
||||||
|
assert seed_from_json(store, str(boot)) is True
|
||||||
|
assert seed_from_json(store, str(boot)) is False # second call no-op
|
||||||
|
assert store.load()["channels"]["wecom"]["bot_id"] == "b1"
|
||||||
|
store2 = AdminStore(str(tmp_path / "db2.sqlite"))
|
||||||
|
with pytest.raises(AdminWriteError, match="not seeded"):
|
||||||
|
store2.load()
|
||||||
|
|
||||||
|
|
||||||
|
def test_store_persists_across_reopen(tmp_path):
|
||||||
|
boot = tmp_path / "config.json"
|
||||||
|
boot.write_text(json.dumps(BOOT))
|
||||||
|
store = AdminStore(str(tmp_path / "db.sqlite"))
|
||||||
|
seed_from_json(store, str(boot))
|
||||||
|
cfg = store.load()
|
||||||
|
cfg["agents"]["x"] = {"cmd": ["x"]}
|
||||||
|
store.save(cfg)
|
||||||
|
assert "x" in AdminStore(str(tmp_path / "db.sqlite")).load()["agents"]
|
||||||
|
|
||||||
|
|
||||||
|
# -- channel CRUD --
|
||||||
|
|
||||||
|
def test_channel_list_masks_secret(ops):
|
||||||
|
chans = ops.list_channels()
|
||||||
|
assert chans[0]["name"] == "wecom"
|
||||||
|
assert "REDACTED" in chans[0]["fields"]["secret"]
|
||||||
|
assert chans[0]["fields"]["bot_id"] == "b1"
|
||||||
|
assert "s1" not in json.dumps(chans) # plaintext never leaks
|
||||||
|
|
||||||
|
|
||||||
|
def test_channel_update_blank_secret_keeps_old(ops):
|
||||||
|
ops.upsert_channel("wecom", {"bot_id": "b2", "secret": ""})
|
||||||
|
doc = ops.store.load()
|
||||||
|
assert doc["channels"]["wecom"]["bot_id"] == "b2"
|
||||||
|
assert doc["channels"]["wecom"]["secret"] == "s1" # blank -> preserved
|
||||||
|
|
||||||
|
|
||||||
def test_channel_missing_required_rejected(ops):
|
def test_channel_missing_required_rejected(ops):
|
||||||
with pytest.raises(AdminWriteError, match="secret"):
|
with pytest.raises(AdminWriteError, match="token"):
|
||||||
ops.upsert_channel("wecom", {"bot_id": "x"})
|
ops.upsert_channel("weixin", {})
|
||||||
|
|
||||||
|
|
||||||
def test_channel_unknown_type_rejected(ops):
|
def test_channel_unknown_type_rejected(ops):
|
||||||
@@ -51,38 +92,45 @@ def test_channel_unknown_field_rejected(ops):
|
|||||||
ops.upsert_channel("wecom", {"bot_id": "b", "secret": "s", "foo": 1})
|
ops.upsert_channel("wecom", {"bot_id": "b", "secret": "s", "foo": 1})
|
||||||
|
|
||||||
|
|
||||||
def test_channel_delete(ops):
|
def test_channel_delete_and_get_missing(ops):
|
||||||
ops.delete_channel("wecom")
|
ops.delete_channel("wecom")
|
||||||
assert "wecom" not in json.load(open(ops.config_path))["channels"]
|
assert ops.list_channels() == []
|
||||||
|
with pytest.raises(AdminWriteError, match="not configured"):
|
||||||
|
ops.get_channel("wecom")
|
||||||
|
|
||||||
|
|
||||||
# -- agent --
|
# -- agent CRUD --
|
||||||
|
|
||||||
def test_agent_upsert_hot_registers(ops):
|
def test_agent_crud_full_cycle(ops):
|
||||||
r = ops.upsert_agent("coder", {"cmd": "coder acp", "default_model": "m1"})
|
r = ops.upsert_agent("coder", {"cmd": "coder acp", "default_model": "m1"})
|
||||||
assert r["hot_registered"]
|
assert r["existed"] is False and r["hot_registered"]
|
||||||
assert "coder" in ops.mgr.agents
|
|
||||||
assert ops.mgr.agents["coder"].default_model == "m1"
|
assert ops.mgr.agents["coder"].default_model == "m1"
|
||||||
cfg = json.load(open(ops.config_path))
|
assert ops.get_agent("coder")["cmd"] == "coder acp"
|
||||||
assert cfg["agents"]["coder"]["cmd"] == ["coder", "acp"]
|
# update keeps untouched fields (merge semantics)
|
||||||
|
ops.upsert_agent("coder", {"cmd": "coder acp --new"})
|
||||||
|
a = ops.get_agent("coder")
|
||||||
|
assert a["cmd"] == "coder acp --new" and a["default_model"] == "m1"
|
||||||
|
ops.delete_agent("coder")
|
||||||
|
assert "coder" not in ops.mgr.agents
|
||||||
|
with pytest.raises(AdminWriteError, match="not configured"):
|
||||||
|
ops.get_agent("coder")
|
||||||
|
|
||||||
|
|
||||||
def test_agent_delete_last_rejected(ops):
|
def test_agent_delete_last_rejected(ops):
|
||||||
ops2_cfg = json.load(open(ops.config_path))
|
doc = ops.store.load()
|
||||||
ops2_cfg["agents"] = {"solo": {"cmd": ["x"]}}
|
doc["agents"] = {"solo": {"cmd": ["x"]}}
|
||||||
json.dump(ops2_cfg, open(ops.config_path, "w"))
|
ops.store.save(doc)
|
||||||
ops.mgr.agents.clear()
|
ops.mgr.agents.clear()
|
||||||
ops.mgr.agents["solo"] = AgentSpec(name="solo", cmd=["x"])
|
ops.mgr.agents["solo"] = AgentSpec(name="solo", cmd=["x"])
|
||||||
with pytest.raises(AdminWriteError, match="last agent"):
|
with pytest.raises(AdminWriteError, match="last agent"):
|
||||||
ops.delete_agent("solo")
|
ops.delete_agent("solo")
|
||||||
|
|
||||||
|
|
||||||
# -- bind --
|
# -- binding --
|
||||||
|
|
||||||
def test_bind_calls_switch(ops):
|
def test_bind_calls_switch(ops):
|
||||||
r = ops.bind("wecom", "chat9", "opencode")
|
r = ops.bind("wecom", "chat9", "opencode")
|
||||||
assert r["binding"] == "wecom:chat9"
|
assert r["binding"] == "wecom:chat9" and r["migrated_turns"] == 3
|
||||||
assert r["migrated_turns"] == 3
|
|
||||||
ops.mgr.switch.assert_called_once_with("wecom", "chat9", "opencode", cont=True)
|
ops.mgr.switch.assert_called_once_with("wecom", "chat9", "opencode", cont=True)
|
||||||
|
|
||||||
|
|
||||||
@@ -100,25 +148,22 @@ def test_unbind_missing_binding_rejected(ops):
|
|||||||
# -- HTTP layer --
|
# -- HTTP layer --
|
||||||
|
|
||||||
def test_http_ops_endpoints_auth_gated(tmp_path):
|
def test_http_ops_endpoints_auth_gated(tmp_path):
|
||||||
cfg = tmp_path / "config.json"
|
boot = tmp_path / "config.json"
|
||||||
cfg.write_text(json.dumps({"agents": {"a": {"cmd": ["x"]}}, "channels": {}}))
|
boot.write_text(json.dumps({"agents": {"a": {"cmd": ["x"]}}, "channels": {}}))
|
||||||
mgr = MagicMock()
|
store = AdminStore(str(tmp_path / "db.sqlite"))
|
||||||
|
seed_from_json(store, str(boot))
|
||||||
|
mgr = make_mgr()
|
||||||
mgr.agents = {"a": AgentSpec(name="a", cmd=["x"])}
|
mgr.agents = {"a": AgentSpec(name="a", cmd=["x"])}
|
||||||
mgr.switch.return_value = {"acp_session_id": "s", "migrated": 0}
|
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,
|
||||||
http = StatusHTTP(mgr, host="127.0.0.1", port=0, admin_cfg={"username": "u", "password": "p"})
|
admin_cfg={"username": "u", "password": "p"})
|
||||||
from agenthub.admin_ops import AdminWrites
|
http.ops = AdminWrites(mgr, store)
|
||||||
http.ops = AdminWrites(mgr, str(cfg))
|
|
||||||
http.start()
|
http.start()
|
||||||
port = http._server.server_address[1] # type: ignore[union-attr]
|
port = http._server.server_address[1] # type: ignore[union-attr]
|
||||||
import base64
|
|
||||||
import urllib.error
|
|
||||||
import urllib.request
|
|
||||||
|
|
||||||
def post(path, body, auth=True):
|
def post(path, body, auth=True):
|
||||||
req = urllib.request.Request(
|
req = urllib.request.Request(
|
||||||
f"http://127.0.0.1:{port}{path}", data=json.dumps(body).encode(), method="POST"
|
f"http://127.0.0.1:{port}{path}", data=json.dumps(body).encode(), method="POST")
|
||||||
)
|
|
||||||
if auth:
|
if auth:
|
||||||
req.add_header("Authorization", "Basic " + base64.b64encode(b"u:p").decode())
|
req.add_header("Authorization", "Basic " + base64.b64encode(b"u:p").decode())
|
||||||
try:
|
try:
|
||||||
@@ -127,13 +172,14 @@ def test_http_ops_endpoints_auth_gated(tmp_path):
|
|||||||
except urllib.error.HTTPError as e:
|
except urllib.error.HTTPError as e:
|
||||||
return e.code, json.loads(e.read() or b"{}")
|
return e.code, json.loads(e.read() or b"{}")
|
||||||
|
|
||||||
# no auth -> 401
|
|
||||||
code, _ = post("/api/agent", {"name": "b", "fields": {"cmd": "y"}}, auth=False)
|
code, _ = post("/api/agent", {"name": "b", "fields": {"cmd": "y"}}, auth=False)
|
||||||
assert code == 401
|
assert code == 401
|
||||||
# with auth -> creates agent
|
|
||||||
code, j = post("/api/agent", {"name": "b", "fields": {"cmd": "y"}})
|
code, j = post("/api/agent", {"name": "b", "fields": {"cmd": "y"}})
|
||||||
assert code == 200 and j["hot_registered"]
|
assert code == 200 and j["hot_registered"]
|
||||||
# validation error -> 400
|
code, j = post("/api/agent/get", {"name": "b"})
|
||||||
|
assert code == 200 and j["cmd"] == "y"
|
||||||
code, j = post("/api/channel", {"name": "wecom", "fields": {"bot_id": "b"}})
|
code, j = post("/api/channel", {"name": "wecom", "fields": {"bot_id": "b"}})
|
||||||
assert code == 400 and "secret" in j["error"]
|
assert code == 400 and "secret" in j["error"]
|
||||||
|
code, j = post("/api/ops-state", {})
|
||||||
|
assert code == 200 and j["storage"] == "sqlite"
|
||||||
http.stop() # type: ignore[union-attr]
|
http.stop() # type: ignore[union-attr]
|
||||||
Reference in new issue
Block a user