File size: 11,054 Bytes
042f4ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""A2A gateway service -- JSON-RPC 2.0 communication with external agents."""

import logging
import time
import uuid
from typing import AsyncGenerator

import httpx
from sqlalchemy.ext.asyncio import AsyncSession

logger = logging.getLogger(__name__)


class A2AGatewayService:
    """Sends JSON-RPC 2.0 requests to remote A2A-compliant agent endpoints."""

    JSON_RPC_VERSION = "2.0"
    DEFAULT_TIMEOUT = 120.0

    def __init__(self, db: AsyncSession):
        self.db = db

    # ------------------------------------------------------------------
    # Helpers
    # ------------------------------------------------------------------

    def _build_request(self, method: str, params: dict) -> dict:
        """Build a JSON-RPC 2.0 request payload."""
        return {
            "jsonrpc": self.JSON_RPC_VERSION,
            "id": str(uuid.uuid4()),
            "method": method,
            "params": params,
        }

    async def _post(
        self, endpoint: str, method: str, params: dict, timeout: float | None = None
    ) -> dict:
        """Send a JSON-RPC POST and return the parsed response."""
        payload = self._build_request(method, params)
        start = time.monotonic()
        status_code = None
        response_body = None
        error_msg = None
        success = True

        try:
            async with httpx.AsyncClient(timeout=timeout or self.DEFAULT_TIMEOUT) as client:
                response = await client.post(
                    endpoint,
                    json=payload,
                    headers={"Content-Type": "application/json"},
                )
                status_code = response.status_code
                response_body = response.json()
                response.raise_for_status()
                return response_body
        except Exception as exc:
            success = False
            error_msg = str(exc)[:500]
            raise
        finally:
            latency_ms = int((time.monotonic() - start) * 1000)
            # Extract agent_id and task_id from params for logging
            task_id_str = params.get("id")
            await self._log_webhook(
                agent_id=None,  # resolved by caller if needed
                task_id_str=task_id_str,
                direction="outbound",
                method=method,
                request_body=payload,
                response_body=response_body,
                status_code=status_code,
                success=success,
                error_message=error_msg,
                latency_ms=latency_ms,
            )

    async def _log_webhook(
        self,
        *,
        agent_id: uuid.UUID | None,
        task_id_str: str | None,
        direction: str,
        method: str,
        request_body: dict | None,
        response_body: dict | None,
        status_code: int | None,
        success: bool,
        error_message: str | None,
        latency_ms: int | None,
    ) -> None:
        """Persist a webhook log entry. Best-effort — never fails the caller."""
        try:
            from src.models.webhook_log import WebhookLog

            task_id = uuid.UUID(task_id_str) if task_id_str else None
            # If agent_id not provided, try to resolve from task
            if agent_id is None and task_id:
                from src.models.task import Task
                from sqlalchemy import select
                result = await self.db.execute(
                    select(Task.provider_agent_id).where(Task.id == task_id)
                )
                row = result.first()
                if row:
                    agent_id = row[0]

            if agent_id is None:
                return  # Can't log without agent_id

            log = WebhookLog(
                agent_id=agent_id,
                task_id=task_id,
                direction=direction,
                method=method,
                request_body=request_body,
                response_body=response_body,
                status_code=status_code,
                success=success,
                error_message=error_message,
                latency_ms=latency_ms,
            )
            self.db.add(log)
            await self.db.flush()
        except Exception:
            logger.debug("Failed to persist webhook log", exc_info=True)

    # ------------------------------------------------------------------
    # Send task
    # ------------------------------------------------------------------

    async def send_task(self, agent_endpoint: str, task_data: dict) -> dict:
        """Send a task to a remote agent via JSON-RPC ``tasks/send``.

        Args:
            agent_endpoint: The base URL of the remote agent.
            task_data: The task payload conforming to the A2A spec.

        Returns:
            The JSON-RPC response body.
        """
        return await self._post(agent_endpoint, "tasks/send", task_data)

    # ------------------------------------------------------------------
    # Get task status
    # ------------------------------------------------------------------

    async def get_task_status(self, agent_endpoint: str, task_id: str) -> dict:
        """Query the status of a task via JSON-RPC ``tasks/get``.

        Args:
            agent_endpoint: The base URL of the remote agent.
            task_id: The identifier of the task.

        Returns:
            The JSON-RPC response body.
        """
        return await self._post(agent_endpoint, "tasks/get", {"id": task_id})

    # ------------------------------------------------------------------
    # Cancel task
    # ------------------------------------------------------------------

    async def cancel_task(self, agent_endpoint: str, task_id: str) -> dict:
        """Cancel a task via JSON-RPC ``tasks/cancel``.

        Args:
            agent_endpoint: The base URL of the remote agent.
            task_id: The identifier of the task.

        Returns:
            The JSON-RPC response body.
        """
        return await self._post(agent_endpoint, "tasks/cancel", {"id": task_id})

    # ------------------------------------------------------------------
    # AP2: Payment settlement notification
    # ------------------------------------------------------------------

    async def send_payment_notification(
        self,
        agent_endpoint: str,
        agent_id: uuid.UUID,
        params: dict,
        max_retries: int = 3,
    ) -> bool:
        """Send a payment/settled notification to an agent with retries.

        Uses exponential backoff (1s, 5s, 25s). Fire-and-forget —
        failures are logged but never raised to the caller.

        Returns True if delivery succeeded, False otherwise.
        """
        import asyncio
        import hashlib
        import hmac as hmac_mod
        import json

        payload = self._build_request("payment/settled", params)
        backoff = 1

        for attempt in range(1, max_retries + 1):
            status_code = None
            response_body = None
            error_msg = None
            success = True
            start = time.monotonic()

            try:
                body_bytes = json.dumps(payload, sort_keys=True).encode()
                from src.config import settings
                signature = hmac_mod.new(
                    settings.webhook_secret.encode(), body_bytes, hashlib.sha256
                ).hexdigest()

                async with httpx.AsyncClient(timeout=30.0) as client:
                    response = await client.post(
                        agent_endpoint,
                        json=payload,
                        headers={
                            "Content-Type": "application/json",
                            "X-Webhook-Signature": signature,
                        },
                    )
                    status_code = response.status_code
                    response_body = response.json() if response.content else None
                    response.raise_for_status()

                logger.info(
                    "Payment notification delivered to %s (attempt %d)",
                    agent_endpoint, attempt,
                )
                return True

            except Exception as exc:
                success = False
                error_msg = f"Attempt {attempt}/{max_retries}: {exc}"
                logger.warning(
                    "Payment notification failed for %s: %s",
                    agent_endpoint, error_msg,
                )
                if attempt < max_retries:
                    await asyncio.sleep(backoff)
                    backoff *= 5

            finally:
                latency_ms = int((time.monotonic() - start) * 1000)
                await self._log_webhook(
                    agent_id=agent_id,
                    task_id_str=params.get("task_id"),
                    direction="outbound",
                    method="payment/settled",
                    request_body=payload,
                    response_body=response_body,
                    status_code=status_code,
                    success=success,
                    error_message=error_msg,
                    latency_ms=latency_ms,
                )

        return False

    # ------------------------------------------------------------------
    # Stream task (SSE)
    # ------------------------------------------------------------------

    async def stream_task(
        self, agent_endpoint: str, task_id: str
    ) -> AsyncGenerator[dict, None]:
        """Stream task updates via SSE from the remote agent.

        Connects to the agent endpoint and yields parsed events as they arrive.

        Args:
            agent_endpoint: The base URL of the remote agent.
            task_id: The identifier of the task.

        Yields:
            Parsed event dicts from the SSE stream.
        """
        payload = self._build_request("tasks/sendSubscribe", {"id": task_id})

        async with httpx.AsyncClient(timeout=None) as client:
            async with client.stream(
                "POST",
                agent_endpoint,
                json=payload,
                headers={
                    "Content-Type": "application/json",
                    "Accept": "text/event-stream",
                },
            ) as response:
                response.raise_for_status()
                event_data = ""
                async for line in response.aiter_lines():
                    if line.startswith("data: "):
                        event_data = line[6:]
                        try:
                            import json
                            yield json.loads(event_data)
                        except (ValueError, TypeError):
                            yield {"raw": event_data}
                        event_data = ""
                    elif line == "" and event_data:
                        # Empty line marks end of an event block
                        event_data = ""