|
| 1 | +"""Channels API: external surfaces (webhook now, Slack later) that drive agent turns. |
| 2 | +
|
| 3 | +The webhook endpoint is auth-whitelisted in `middleware_utils.WHITELISTED_ROUTES` |
| 4 | +(it bypasses the agentex API-key auth) and instead verifies a per-route shared |
| 5 | +secret / HMAC inside the channel. Each route binds to one agent and an opaque |
| 6 | +`params` dict forwarded verbatim to task/create (agentex does not interpret it — |
| 7 | +the bound agent does). |
| 8 | +
|
| 9 | +Route bindings live in the CHANNELS_WEBHOOK_ROUTES env var (JSON) for now — the |
| 10 | +seam where a real per-config store (resolving a saved agent_config_id) plugs in later: |
| 11 | +
|
| 12 | + CHANNELS_WEBHOOK_ROUTES='{"demo": {"secret": "<shared-secret>", |
| 13 | + "agent_name": "golden-agent", |
| 14 | + "params": {"system_prompt": "You are ...", "mcps": []}}}' |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import json |
| 20 | +import os |
| 21 | + |
| 22 | +from fastapi import APIRouter, HTTPException, Query, Request |
| 23 | + |
| 24 | +from src.domain.channels.base import ChannelBinding |
| 25 | +from src.domain.channels.router import ChannelRouter |
| 26 | +from src.domain.channels.webhook import MAX_BODY_BYTES, WebhookChannel |
| 27 | +from src.domain.services.task_message_service import DTaskMessageService |
| 28 | +from src.domain.use_cases.agents_acp_use_case import DAgentsACPUseCase |
| 29 | +from src.domain.use_cases.agents_use_case import DAgentsUseCase |
| 30 | +from src.utils.logging import make_logger |
| 31 | + |
| 32 | +logger = make_logger(__name__) |
| 33 | + |
| 34 | +router = APIRouter(prefix="/channels", tags=["Channels"]) |
| 35 | + |
| 36 | +# Channel registry — add "slack": SlackChannel() here when it lands. |
| 37 | +_WEBHOOK = WebhookChannel() |
| 38 | + |
| 39 | + |
| 40 | +def _webhook_binding(route_id: str) -> ChannelBinding | None: |
| 41 | + """Resolve a webhook route's binding. Env-backed seam; replace with a config store.""" |
| 42 | + raw = os.environ.get("CHANNELS_WEBHOOK_ROUTES") |
| 43 | + if not raw: |
| 44 | + return None |
| 45 | + try: |
| 46 | + routes = json.loads(raw) |
| 47 | + except json.JSONDecodeError: |
| 48 | + logger.error("[channels] CHANNELS_WEBHOOK_ROUTES is not valid JSON") |
| 49 | + return None |
| 50 | + cfg = routes.get(route_id) |
| 51 | + if not isinstance(cfg, dict) or not cfg.get("secret") or not cfg.get("agent_name"): |
| 52 | + return None |
| 53 | + # `params` is opaque — forwarded verbatim to task/create; agentex does not |
| 54 | + # interpret it (an agent like golden-agent reads system_prompt/mcps/etc. there). |
| 55 | + params = cfg.get("params") |
| 56 | + return ChannelBinding( |
| 57 | + secret=cfg["secret"], |
| 58 | + agent_name=cfg["agent_name"], |
| 59 | + params=params if isinstance(params, dict) else {}, |
| 60 | + ) |
| 61 | + |
| 62 | + |
| 63 | +@router.post( |
| 64 | + "/webhook/{route_id}", |
| 65 | + summary="Generic webhook channel", |
| 66 | + description="Authenticated webhook ingress: verifies a per-route secret/HMAC and " |
| 67 | + "drives an agent turn. Auth is whitelisted at the middleware; the channel verifies " |
| 68 | + "the route secret instead.", |
| 69 | +) |
| 70 | +async def handle_webhook( |
| 71 | + route_id: str, |
| 72 | + request: Request, |
| 73 | + agents_acp_use_case: DAgentsACPUseCase, |
| 74 | + agents_use_case: DAgentsUseCase, |
| 75 | + task_message_service: DTaskMessageService, |
| 76 | + wait: bool = Query( |
| 77 | + False, |
| 78 | + description="If true, wait for the agent's reply and return it (for synchronous " |
| 79 | + "callers). Default false: return immediately with the task_id.", |
| 80 | + ), |
| 81 | +) -> dict: |
| 82 | + binding = _webhook_binding(route_id) |
| 83 | + if binding is None: |
| 84 | + raise HTTPException(status_code=404, detail="unknown route") |
| 85 | + |
| 86 | + raw = await request.body() |
| 87 | + if len(raw) > MAX_BODY_BYTES: |
| 88 | + raise HTTPException(status_code=413, detail="payload too large") |
| 89 | + if not _WEBHOOK.authenticate(binding, request, raw): |
| 90 | + raise HTTPException(status_code=401, detail="unauthorized") |
| 91 | + if "application/json" not in request.headers.get("content-type", ""): |
| 92 | + raise HTTPException(status_code=400, detail="expected application/json") |
| 93 | + try: |
| 94 | + body = json.loads(raw) |
| 95 | + except json.JSONDecodeError: |
| 96 | + raise HTTPException(status_code=400, detail="invalid json") |
| 97 | + if not isinstance(body, dict): |
| 98 | + raise HTTPException(status_code=400, detail="json body must be an object") |
| 99 | + |
| 100 | + # Resolve the agent's ACP type so the router picks the right turn method |
| 101 | + # (sync -> message/send returns the reply inline; async -> event/send). |
| 102 | + agent = await agents_use_case.get(name=binding.agent_name) |
| 103 | + |
| 104 | + inbound = _WEBHOOK.to_inbound(route_id, body) |
| 105 | + router_ = ChannelRouter(agents_acp_use_case, task_message_service) |
| 106 | + result = await router_.dispatch(inbound, binding, agent.acp_type) |
| 107 | + |
| 108 | + # A plain webhook has no outbound push (supports_outbound is False) — its reply is |
| 109 | + # the HTTP response. Sync agents reply inline; for async, `wait` streams it back. |
| 110 | + # A push channel (Slack) would instead: reply = result.reply or await_reply(...); |
| 111 | + # await deliver_reply(channel, peer_id, reply). |
| 112 | + reply = result.reply |
| 113 | + if reply is None and wait: |
| 114 | + reply = await router_.await_reply(result.task_id, result.after_id) |
| 115 | + |
| 116 | + response = { |
| 117 | + "ok": True, |
| 118 | + "channel": "webhook", |
| 119 | + "route_id": route_id, |
| 120 | + "task_id": result.task_id, |
| 121 | + } |
| 122 | + if reply is not None: |
| 123 | + response["reply"] = reply |
| 124 | + return response |
0 commit comments