feat(approval): route ACP permission approvals to the wecom approval chat
- single dispatch-all event sink (per-channel sinks previously overwrote each other) - channels.wecom.approval_chat config: interaction events are additionally delivered to that wecom chat with routed_from stamp; SessionManager.set_route stamps the pending permission route_key so the approval chat can answer with numbered/name/re r replies (pending_interaction + permission_reply accept either the originating key or the route key) - origin == approval chat is not duplicated; no config = previous behavior - tests: tests/test_approval_route.py (7 cases)
This commit is contained in:
1 parent
5f2f724827
commit
10420f9d72
3 files changed
+173
-6
No files matched your search
+46
-3
@@ -68,9 +68,6 @@ def build_channels(cfg: dict[str, Any], mgr: SessionManager) -> list:
|
|||||||
ch.on_message(
|
ch.on_message(
|
||||||
lambda m: _safe_inbound(mgr, ch, m)
|
lambda m: _safe_inbound(mgr, ch, m)
|
||||||
)
|
)
|
||||||
mgr.set_event_sink(
|
|
||||||
lambda key, kind, payload: _safe_event(ch, key, kind, payload)
|
|
||||||
)
|
|
||||||
channels.append(ch)
|
channels.append(ch)
|
||||||
|
|
||||||
if "wecom" in ccfg:
|
if "wecom" in ccfg:
|
||||||
@@ -84,9 +81,55 @@ def build_channels(cfg: dict[str, Any], mgr: SessionManager) -> list:
|
|||||||
sink_and_inbound(WecomAppChannel(ccfg["wecom-app"]))
|
sink_and_inbound(WecomAppChannel(ccfg["wecom-app"]))
|
||||||
if "weixin" in ccfg:
|
if "weixin" in ccfg:
|
||||||
sink_and_inbound(WeixinChannel(ccfg["weixin"]))
|
sink_and_inbound(WeixinChannel(ccfg["weixin"]))
|
||||||
|
|
||||||
|
# ONE dispatch-all event sink (per-channel sinks would overwrite each
|
||||||
|
# other; _safe_event filters per channel name anyway). Approvals
|
||||||
|
# (interaction events) are additionally routed to the wecom approval
|
||||||
|
# chat when configured: channels.wecom.approval_chat.
|
||||||
|
def dispatch_all(key: str, kind: str, payload: dict[str, Any]) -> None:
|
||||||
|
for ch in channels:
|
||||||
|
_safe_event(ch, key, kind, payload)
|
||||||
|
if kind == "interaction":
|
||||||
|
_route_approval(channels, ccfg, mgr, key, payload)
|
||||||
|
|
||||||
|
mgr.set_event_sink(dispatch_all)
|
||||||
return channels
|
return channels
|
||||||
|
|
||||||
|
|
||||||
|
def _route_approval(channels: list, ccfg: dict[str, Any], mgr: SessionManager,
|
||||||
|
key: str, payload: dict[str, Any]) -> None:
|
||||||
|
"""Deliver an approval/question to the wecom approval chat.
|
||||||
|
|
||||||
|
Config: channels.wecom.approval_chat = "<chat_id>" (e.g. a user id).
|
||||||
|
The originating channel still gets its own copy; this ADDS a wecom
|
||||||
|
delivery so approvals are answerable from wecom even when the turn
|
||||||
|
started on another channel. The pending permission's route_key is
|
||||||
|
stamped (mgr.set_route) so a reply from the approval chat matches.
|
||||||
|
"""
|
||||||
|
wcfg = ccfg.get("wecom") or {}
|
||||||
|
approval_chat = wcfg.get("approval_chat")
|
||||||
|
if not approval_chat:
|
||||||
|
return
|
||||||
|
wecom = next((c for c in channels if c.name == "wecom"), None)
|
||||||
|
if wecom is None:
|
||||||
|
return
|
||||||
|
origin = f"wecom:{approval_chat}"
|
||||||
|
if key == origin:
|
||||||
|
return # already delivered to the approval chat directly
|
||||||
|
req_id = payload.get("request_id")
|
||||||
|
if req_id:
|
||||||
|
try:
|
||||||
|
mgr.set_route(str(req_id), origin)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
log.warning(f"[wecom] approval route stamp failed: {e}")
|
||||||
|
routed = dict(payload)
|
||||||
|
routed["routed_from"] = key
|
||||||
|
try:
|
||||||
|
wecom.push_event(approval_chat, "interaction", routed)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
log.warning(f"[wecom] approval route to {approval_chat} failed: {e}")
|
||||||
|
|
||||||
|
|
||||||
def _safe_inbound(mgr: SessionManager, ch, m) -> None:
|
def _safe_inbound(mgr: SessionManager, ch, m) -> None:
|
||||||
"""One inbound IM message: ack -> command dispatch OR agent prompt.
|
"""One inbound IM message: ack -> command dispatch OR agent prompt.
|
||||||
|
|
||||||
|
|||||||
+18
-3
@@ -86,6 +86,7 @@ class PermissionRequest:
|
|||||||
answered: threading.Event = field(default_factory=threading.Event)
|
answered: threading.Event = field(default_factory=threading.Event)
|
||||||
choice: str | None = None # optionId chosen, None = timeout/deny
|
choice: str | None = None # optionId chosen, None = timeout/deny
|
||||||
presented: bool = False # interaction event emitted to the front-end
|
presented: bool = False # interaction event emitted to the front-end
|
||||||
|
route_key: str | None = None # approval chat "channel:chat_id" if routed elsewhere (e.g. wecom approval)
|
||||||
|
|
||||||
|
|
||||||
def _is_transient_model_error(msg: str) -> bool:
|
def _is_transient_model_error(msg: str) -> bool:
|
||||||
@@ -414,10 +415,16 @@ class SessionManager:
|
|||||||
|
|
||||||
# -- permission ---------------------------------------------------------------
|
# -- permission ---------------------------------------------------------------
|
||||||
def pending_interaction(self, channel: str, chat_id: str) -> dict[str, Any] | None:
|
def pending_interaction(self, channel: str, chat_id: str) -> dict[str, Any] | None:
|
||||||
"""The most recent pending interaction for this chat, if any."""
|
"""The most recent pending interaction for this chat, if any.
|
||||||
|
|
||||||
|
Matches either the originating chat key or the approval route_key
|
||||||
|
(so an approval routed to the wecom approval chat can be answered
|
||||||
|
from that chat even though the agent turn started elsewhere).
|
||||||
|
"""
|
||||||
key = f"{channel}:{chat_id}"
|
key = f"{channel}:{chat_id}"
|
||||||
with self._lock:
|
with self._lock:
|
||||||
pendings = [p for p in self._pending_permissions.values() if p.key == key]
|
pendings = [p for p in self._pending_permissions.values()
|
||||||
|
if p.key == key or p.route_key == key]
|
||||||
if not pendings:
|
if not pendings:
|
||||||
return None
|
return None
|
||||||
pr = pendings[-1] # newest
|
pr = pendings[-1] # newest
|
||||||
@@ -465,6 +472,14 @@ class SessionManager:
|
|||||||
self.permission_reply(channel, chat_id, inter["request_id"], choice)
|
self.permission_reply(channel, chat_id, inter["request_id"], choice)
|
||||||
return "consumed"
|
return "consumed"
|
||||||
|
|
||||||
|
def set_route(self, request_id: str, route_key: str) -> None:
|
||||||
|
"""Stamp an approval route so replies from the routed chat (e.g. the
|
||||||
|
wecom approval chat) are accepted by pending_interaction/reply."""
|
||||||
|
with self._lock:
|
||||||
|
pr = self._pending_permissions.get(request_id)
|
||||||
|
if pr is not None:
|
||||||
|
pr.route_key = route_key
|
||||||
|
|
||||||
def permission_reply(self, channel: str, chat_id: str, request_id: str, choice: str) -> None:
|
def permission_reply(self, channel: str, chat_id: str, request_id: str, choice: str) -> None:
|
||||||
"""Answer a pending permission/interaction.
|
"""Answer a pending permission/interaction.
|
||||||
|
|
||||||
@@ -476,7 +491,7 @@ class SessionManager:
|
|||||||
pr = self._pending_permissions.get(request_id)
|
pr = self._pending_permissions.get(request_id)
|
||||||
if pr is None:
|
if pr is None:
|
||||||
raise SessionError(f"no pending permission {request_id}")
|
raise SessionError(f"no pending permission {request_id}")
|
||||||
if pr.key != f"{channel}:{chat_id}":
|
if pr.key != f"{channel}:{chat_id}" and pr.route_key != f"{channel}:{chat_id}":
|
||||||
raise SessionError("permission request belongs to a different chat")
|
raise SessionError("permission request belongs to a different chat")
|
||||||
if not pr.presented:
|
if not pr.presented:
|
||||||
# never turn a decision on an approval the user has not seen into
|
# never turn a decision on an approval the user has not seen into
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
"""Tests: approval routing to the wecom approval chat.
|
||||||
|
|
||||||
|
covers SessionManager.set_route / route_key matching in
|
||||||
|
pending_interaction + permission_reply, and runtime._route_approval
|
||||||
|
multi-channel dispatch (dispatch-all sink + approval multicast).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from agenthub.session import SessionManager, PermissionRequest
|
||||||
|
from agenthub.runtime import _route_approval
|
||||||
|
|
||||||
|
|
||||||
|
def _mgr() -> SessionManager:
|
||||||
|
return SessionManager(agents={}, client_factory=lambda spec: None)
|
||||||
|
|
||||||
|
|
||||||
|
def _pending(mgr: SessionManager, req_id="req1", key="nats:chat-a") -> None:
|
||||||
|
mgr._pending_permissions[req_id] = PermissionRequest(
|
||||||
|
request_id=req_id, agent="opencode", acp_request_id=None,
|
||||||
|
session_id="sid", key=key, tool_title="run cmd",
|
||||||
|
tool_kind="execute", raw_request_id=None,
|
||||||
|
options=[
|
||||||
|
{"option_id": "allow_once", "name": "Allow once", "kind": "allow_once"},
|
||||||
|
{"option_id": "reject_once", "name": "Reject", "kind": "reject_once"},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
mgr._pending_permissions[req_id].presented = True
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_key_matches_pending_interaction():
|
||||||
|
mgr = _mgr()
|
||||||
|
_pending(mgr)
|
||||||
|
mgr.set_route("req1", "wecom:vex1023")
|
||||||
|
inter = mgr.pending_interaction("wecom", "vex1023")
|
||||||
|
assert inter is not None and inter["request_id"] == "req1"
|
||||||
|
# originating chat still matches too
|
||||||
|
assert mgr.pending_interaction("nats", "chat-a")["request_id"] == "req1"
|
||||||
|
# unrelated chat does not
|
||||||
|
assert mgr.pending_interaction("wecom", "other") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_permission_reply_from_routed_chat():
|
||||||
|
mgr = _mgr()
|
||||||
|
_pending(mgr)
|
||||||
|
mgr.set_route("req1", "wecom:vex1023")
|
||||||
|
# reply from the approval route chat: accepted
|
||||||
|
mgr.permission_reply("wecom", "vex1023", "req1", "allow_once")
|
||||||
|
assert mgr._pending_permissions["req1"].choice == "allow_once"
|
||||||
|
|
||||||
|
|
||||||
|
def test_permission_reply_wrong_chat_rejected():
|
||||||
|
import pytest
|
||||||
|
from agenthub.session import SessionError
|
||||||
|
mgr = _mgr()
|
||||||
|
_pending(mgr)
|
||||||
|
mgr.set_route("req1", "wecom:vex1023")
|
||||||
|
with pytest.raises(SessionError):
|
||||||
|
mgr.permission_reply("wecom", "someone-else", "req1", "allow_once")
|
||||||
|
|
||||||
|
|
||||||
|
def test_take_interaction_answer_from_routed_chat():
|
||||||
|
mgr = _mgr()
|
||||||
|
_pending(mgr)
|
||||||
|
mgr.set_route("req1", "wecom:vex1023")
|
||||||
|
assert mgr.take_interaction_answer("wecom", "vex1023", "1") == "consumed"
|
||||||
|
assert mgr._pending_permissions["req1"].choice == "allow_once"
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeWecom:
|
||||||
|
name = "wecom"
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.events = []
|
||||||
|
|
||||||
|
def push_event(self, chat_id, kind, payload):
|
||||||
|
self.events.append((chat_id, kind, payload))
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_approval_multicast():
|
||||||
|
wecom = _FakeWecom()
|
||||||
|
mgr = _mgr()
|
||||||
|
_pending(mgr)
|
||||||
|
ccfg = {"wecom": {"approval_chat": "vex1023"}}
|
||||||
|
payload = {"request_id": "req1", "interaction_type": "permission",
|
||||||
|
"tool": "run cmd", "options": []}
|
||||||
|
_route_approval([wecom], ccfg, mgr, "nats:chat-a", payload)
|
||||||
|
assert wecom.events and wecom.events[0][0] == "vex1023"
|
||||||
|
assert wecom.events[0][1] == "interaction"
|
||||||
|
assert wecom.events[0][2]["routed_from"] == "nats:chat-a"
|
||||||
|
assert mgr._pending_permissions["req1"].route_key == "wecom:vex1023"
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_approval_no_config_noop():
|
||||||
|
wecom = _FakeWecom()
|
||||||
|
mgr = _mgr()
|
||||||
|
_pending(mgr)
|
||||||
|
_route_approval([wecom], {}, mgr, "nats:chat-a",
|
||||||
|
{"request_id": "req1", "options": []})
|
||||||
|
assert wecom.events == []
|
||||||
|
assert mgr._pending_permissions["req1"].route_key is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_approval_origin_is_approval_chat_noop():
|
||||||
|
wecom = _FakeWecom()
|
||||||
|
mgr = _mgr()
|
||||||
|
_pending(mgr, key="wecom:vex1023")
|
||||||
|
ccfg = {"wecom": {"approval_chat": "vex1023"}}
|
||||||
|
_route_approval([wecom], ccfg, mgr, "wecom:vex1023",
|
||||||
|
{"request_id": "req1", "options": []})
|
||||||
|
assert wecom.events == [] # not duplicated
|
||||||
Reference in new issue
Block a user