|
| 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 + inline config. |
| 6 | +
|
| 7 | +Route bindings live in the CHANNELS_WEBHOOK_ROUTES env var (JSON) for now — the |
| 8 | +seam where a real per-config store (resolving a saved agent_config_id) plugs in later: |
| 9 | +
|
| 10 | + CHANNELS_WEBHOOK_ROUTES='{"demo": {"secret": "<shared-secret>", |
| 11 | + "agent_name": "golden-agent", "system_prompt": "You are ...", |
| 12 | + "harness": "claude-code", "model": "..."}}' |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import json |
| 18 | +import os |
| 19 | + |
| 20 | +from fastapi import APIRouter, HTTPException, Request |
| 21 | + |
| 22 | +from src.domain.channels.base import ChannelBinding |
| 23 | +from src.domain.channels.router import ChannelRouter |
| 24 | +from src.domain.channels.webhook import MAX_BODY_BYTES, WebhookChannel |
| 25 | +from src.domain.use_cases.agents_acp_use_case import DAgentsACPUseCase |
| 26 | +from src.utils.logging import make_logger |
| 27 | + |
| 28 | +logger = make_logger(__name__) |
| 29 | + |
| 30 | +router = APIRouter(prefix="/channels", tags=["Channels"]) |
| 31 | + |
| 32 | +# Channel registry — add "slack": SlackChannel() here when it lands. |
| 33 | +_WEBHOOK = WebhookChannel() |
| 34 | + |
| 35 | + |
| 36 | +def _webhook_binding(route_id: str) -> ChannelBinding | None: |
| 37 | + """Resolve a webhook route's binding. Env-backed seam; replace with a config store.""" |
| 38 | + raw = os.environ.get("CHANNELS_WEBHOOK_ROUTES") |
| 39 | + if not raw: |
| 40 | + return None |
| 41 | + try: |
| 42 | + routes = json.loads(raw) |
| 43 | + except json.JSONDecodeError: |
| 44 | + logger.error("[channels] CHANNELS_WEBHOOK_ROUTES is not valid JSON") |
| 45 | + return None |
| 46 | + cfg = routes.get(route_id) |
| 47 | + if not isinstance(cfg, dict) or not cfg.get("secret") or not cfg.get("agent_name"): |
| 48 | + return None |
| 49 | + return ChannelBinding( |
| 50 | + secret=cfg["secret"], |
| 51 | + agent_name=cfg["agent_name"], |
| 52 | + system_prompt=cfg.get("system_prompt"), |
| 53 | + harness=cfg.get("harness", "claude-code"), |
| 54 | + model=cfg.get("model"), |
| 55 | + allowed_tools=cfg.get("allowed_tools", []), |
| 56 | + mcps=cfg.get("mcps", []), |
| 57 | + ) |
| 58 | + |
| 59 | + |
| 60 | +@router.post( |
| 61 | + "/webhook/{route_id}", |
| 62 | + summary="Generic webhook channel", |
| 63 | + description="Authenticated webhook ingress: verifies a per-route secret/HMAC and " |
| 64 | + "drives an agent turn. Auth is whitelisted at the middleware; the channel verifies " |
| 65 | + "the route secret instead.", |
| 66 | +) |
| 67 | +async def handle_webhook( |
| 68 | + route_id: str, |
| 69 | + request: Request, |
| 70 | + agents_acp_use_case: DAgentsACPUseCase, |
| 71 | +) -> dict: |
| 72 | + binding = _webhook_binding(route_id) |
| 73 | + if binding is None: |
| 74 | + raise HTTPException(status_code=404, detail="unknown route") |
| 75 | + |
| 76 | + raw = await request.body() |
| 77 | + if len(raw) > MAX_BODY_BYTES: |
| 78 | + raise HTTPException(status_code=413, detail="payload too large") |
| 79 | + if not _WEBHOOK.authenticate(binding, request, raw): |
| 80 | + raise HTTPException(status_code=401, detail="unauthorized") |
| 81 | + if "application/json" not in request.headers.get("content-type", ""): |
| 82 | + raise HTTPException(status_code=400, detail="expected application/json") |
| 83 | + try: |
| 84 | + body = json.loads(raw) |
| 85 | + except json.JSONDecodeError: |
| 86 | + raise HTTPException(status_code=400, detail="invalid json") |
| 87 | + if not isinstance(body, dict): |
| 88 | + raise HTTPException(status_code=400, detail="json body must be an object") |
| 89 | + |
| 90 | + inbound = _WEBHOOK.to_inbound(route_id, body) |
| 91 | + task_id = await ChannelRouter(agents_acp_use_case).dispatch(inbound, binding) |
| 92 | + return {"ok": True, "channel": "webhook", "route_id": route_id, "task_id": task_id} |
0 commit comments