File size: 15,690 Bytes
04bb755 | 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 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | # Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""A2A server-side protocol β JSON-RPC dispatch and SSE streaming.
This router exposes CrewHub as an A2A-compliant server that external agents
can call to create tasks, query status, cancel, and subscribe to real-time
updates via Server-Sent Events.
"""
import asyncio
import json
import logging
from uuid import UUID
from fastapi import APIRouter, Depends, Header, Request
from fastapi.responses import StreamingResponse
from fastapi.security import HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from src.core.auth import get_current_user
from src.core.anp_auth import verify_anp_signature
from src.core.rate_limiter import get_rate_limiter
from src.core.exceptions import RateLimitError, UnauthorizedError
from src.database import get_db
from src.models.task import TaskStatus
from src.schemas.a2a import (
JSONRPC_INTERNAL_ERROR,
JSONRPC_INVALID_PARAMS,
JSONRPC_METHOD_NOT_FOUND,
JSONRPC_TASK_NOT_CANCELABLE,
JSONRPC_TASK_NOT_FOUND,
JsonRpcRequest,
JsonRpcResponse,
TaskArtifactUpdateEvent,
TaskStatusUpdateEvent,
)
from src.services.task_broker import TaskBrokerService
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/a2a", tags=["a2a"])
# ---------------------------------------------------------------------------
# A2A auth: accept Bearer token, API key, or ANP DID signature
# ---------------------------------------------------------------------------
_bearer_optional = HTTPBearer(auto_error=False)
async def _get_current_user_optional(
request: Request,
credentials=Depends(_bearer_optional),
x_api_key: str | None = Header(None, alias="X-API-Key"),
) -> dict | None:
"""Like get_current_user but returns None instead of raising when no creds."""
if credentials is None and x_api_key is None:
return None
return await get_current_user(request=request, credentials=credentials, x_api_key=x_api_key)
async def get_a2a_caller(
current_user: dict | None = Depends(_get_current_user_optional),
anp_identity: dict | None = Depends(verify_anp_signature),
) -> dict:
"""Resolve the authenticated caller for A2A requests.
Accepts standard auth (Bearer / API key) or ANP DID signature.
Returns a dict with at least 'id' key.
"""
if current_user is not None:
return current_user
if anp_identity is not None:
return {"id": anp_identity["did"], "auth_method": "anp"}
raise UnauthorizedError(detail="A2A authentication required (Bearer, API key, or ANP signature)")
async def a2a_rate_limit(
request: Request,
caller: dict = Depends(get_a2a_caller),
) -> None:
"""Rate-limit A2A requests by caller identity."""
limiter = get_rate_limiter()
key = f"a2a:{caller['id']}"
if not limiter.check(key):
info = limiter.get_limit_info(key)
raise RateLimitError(
detail=f"A2A rate limit exceeded. Try again in {info['reset_in_seconds']} seconds"
)
TERMINAL_STATUSES = {
TaskStatus.COMPLETED,
TaskStatus.FAILED,
TaskStatus.CANCELED,
TaskStatus.REJECTED,
}
SSE_POLL_INTERVAL = 2 # seconds
SSE_MAX_DURATION = 300 # 5 minutes max stream
# ---------------------------------------------------------------------------
# JSON-RPC helpers
# ---------------------------------------------------------------------------
def _error_response(rpc_id, code: int, message: str) -> JsonRpcResponse:
return JsonRpcResponse(id=rpc_id, error={"code": code, "message": message})
def _success_response(rpc_id, result) -> JsonRpcResponse:
return JsonRpcResponse(id=rpc_id, result=result)
def _task_to_dict(task) -> dict:
"""Serialize a Task model to a JSON-safe dict for A2A responses."""
return {
"id": str(task.id),
"status": task.status.value if hasattr(task.status, "value") else task.status,
"messages": task.messages or [],
"artifacts": task.artifacts or [],
"metadata": {
"credits_quoted": float(task.credits_quoted) if task.credits_quoted else 0,
"payment_method": task.payment_method,
"created_at": task.created_at.isoformat() if task.created_at else None,
"completed_at": task.completed_at.isoformat() if task.completed_at else None,
},
}
# ---------------------------------------------------------------------------
# Main JSON-RPC dispatcher
# ---------------------------------------------------------------------------
@router.post("", dependencies=[Depends(a2a_rate_limit)])
async def a2a_jsonrpc(
payload: JsonRpcRequest,
request: Request,
db: AsyncSession = Depends(get_db),
caller: dict = Depends(get_a2a_caller),
):
"""A2A JSON-RPC handler. Dispatches to method handlers.
Requires authentication (Bearer token, API key, or ANP DID signature)
and is rate-limited per caller.
Methods:
- tasks/send β create task and return result
- tasks/get β return task status
- tasks/cancel β cancel task
- tasks/sendSubscribe β return SSE stream of task updates
"""
method = payload.method
params = payload.params
rpc_id = payload.id
if method == "tasks/send":
return await _handle_tasks_send(rpc_id, params, db, caller)
elif method == "tasks/get":
return await _handle_tasks_get(rpc_id, params, db, caller)
elif method == "tasks/cancel":
return await _handle_tasks_cancel(rpc_id, params, db, caller)
elif method == "tasks/sendSubscribe":
return await _handle_tasks_send_subscribe(rpc_id, params, db, caller)
else:
return _error_response(rpc_id, JSONRPC_METHOD_NOT_FOUND, f"Method not found: {method}")
# ---------------------------------------------------------------------------
# tasks/send β create a task and return it
# ---------------------------------------------------------------------------
async def _handle_tasks_send(
rpc_id, params: dict, db: AsyncSession, caller: dict
) -> JsonRpcResponse:
from src.schemas.agent import _validate_public_url
from src.schemas.task import TaskCreate, TaskMessage
try:
# Extract required fields from A2A params
provider_agent_id = params.get("provider_agent_id")
skill_id = params.get("skill_id")
message_data = params.get("message")
if not provider_agent_id or not skill_id or not message_data:
return _error_response(
rpc_id, JSONRPC_INVALID_PARAMS,
"Required: provider_agent_id, skill_id, message"
)
message = TaskMessage(**message_data)
task_data = TaskCreate(
provider_agent_id=UUID(provider_agent_id),
skill_id=skill_id,
messages=[message],
max_credits=params.get("max_credits"),
tier=params.get("tier"),
)
# Use the authenticated caller's ID, not the provider_agent_id from params
caller_id = caller["id"]
try:
user_id = UUID(caller_id)
except (ValueError, AttributeError):
# ANP DID callers have a string ID β use a deterministic UUID
import hashlib
user_id = UUID(hashlib.md5(str(caller_id).encode()).hexdigest())
# Check if the caller owns an agent (for agent-to-agent delegation)
client_agent_id = None
try:
from sqlalchemy import select as sa_select
from src.models.agent import Agent
result = await db.execute(
sa_select(Agent.id).where(Agent.owner_id == user_id).limit(1)
)
agent_row = result.scalar_one_or_none()
if agent_row:
client_agent_id = agent_row
except Exception:
pass # Non-critical β proceed without client_agent_id
broker = TaskBrokerService(db)
task = await broker.create_task(task_data, user_id=user_id, client_agent_id=client_agent_id)
# Store callback URL if push notification config provided (with SSRF check)
push_config = params.get("pushNotification")
if push_config and push_config.get("url"):
try:
_validate_public_url(push_config["url"], allow_debug_bypass=False)
except ValueError as e:
return _error_response(
rpc_id, JSONRPC_INVALID_PARAMS,
f"Invalid callback URL: {e}"
)
task.callback_url = push_config["url"]
await db.commit()
await db.refresh(task)
return _success_response(rpc_id, _task_to_dict(task))
except Exception:
logger.exception("tasks/send failed")
return _error_response(rpc_id, JSONRPC_INTERNAL_ERROR, "Internal error processing task")
# ---------------------------------------------------------------------------
# tasks/get β query task status
# ---------------------------------------------------------------------------
async def _handle_tasks_get(rpc_id, params: dict, db: AsyncSession, caller: dict) -> JsonRpcResponse:
task_id = params.get("id")
if not task_id:
return _error_response(rpc_id, JSONRPC_INVALID_PARAMS, "Required: id")
try:
caller_id = caller["id"]
try:
user_id = UUID(caller_id)
except (ValueError, AttributeError):
import hashlib
user_id = UUID(hashlib.md5(str(caller_id).encode()).hexdigest())
broker = TaskBrokerService(db)
task = await broker.get_task(UUID(task_id), user_id=user_id)
return _success_response(rpc_id, _task_to_dict(task))
except Exception as e:
if "not found" in str(e).lower():
return _error_response(rpc_id, JSONRPC_TASK_NOT_FOUND, "Task not found")
if "forbidden" in str(e).lower() or "do not have access" in str(e).lower():
return _error_response(rpc_id, JSONRPC_INVALID_PARAMS, "Not authorized to view this task")
logger.exception("tasks/get failed")
return _error_response(rpc_id, JSONRPC_INTERNAL_ERROR, "Internal error retrieving task")
# ---------------------------------------------------------------------------
# tasks/cancel β cancel a task
# ---------------------------------------------------------------------------
async def _handle_tasks_cancel(rpc_id, params: dict, db: AsyncSession, caller: dict) -> JsonRpcResponse:
task_id = params.get("id")
if not task_id:
return _error_response(rpc_id, JSONRPC_INVALID_PARAMS, "Required: id")
try:
caller_id = caller["id"]
try:
user_id = UUID(caller_id)
except (ValueError, AttributeError):
import hashlib
user_id = UUID(hashlib.md5(str(caller_id).encode()).hexdigest())
broker = TaskBrokerService(db)
task = await broker.cancel_task(UUID(task_id), user_id=user_id)
return _success_response(rpc_id, _task_to_dict(task))
except Exception as e:
if "not found" in str(e).lower():
return _error_response(rpc_id, JSONRPC_TASK_NOT_FOUND, "Task not found")
if "cannot cancel" in str(e).lower() or "not cancelable" in str(e).lower():
return _error_response(rpc_id, JSONRPC_TASK_NOT_CANCELABLE, "Task cannot be canceled")
if "forbidden" in str(e).lower() or "do not own" in str(e).lower():
return _error_response(rpc_id, JSONRPC_INVALID_PARAMS, "Not authorized to cancel this task")
logger.exception("tasks/cancel failed")
return _error_response(rpc_id, JSONRPC_INTERNAL_ERROR, "Internal error canceling task")
# ---------------------------------------------------------------------------
# tasks/sendSubscribe β create task + return SSE stream
# ---------------------------------------------------------------------------
async def _handle_tasks_send_subscribe(
rpc_id, params: dict, db: AsyncSession, caller: dict
) -> StreamingResponse:
"""Create a task (or subscribe to existing) and stream status updates via SSE."""
async def event_stream():
from src.database import async_session
task_id = params.get("id")
# If no task_id, create a new task first
if not task_id:
try:
response = await _handle_tasks_send(rpc_id, params, db, caller)
if response.error:
yield f"data: {json.dumps({'error': response.error})}\n\n"
return
task_id = response.result["id"]
# Yield initial creation event
yield f"data: {json.dumps(response.result)}\n\n"
except Exception:
logger.exception("tasks/sendSubscribe creation failed")
yield f"data: {json.dumps({'error': {'code': -32603, 'message': 'Internal error'}})}\n\n"
return
# Poll for status changes and stream them
last_status = None
last_artifact_count = 0
elapsed = 0
while elapsed < SSE_MAX_DURATION:
try:
async with async_session() as poll_db:
broker = TaskBrokerService(poll_db)
task = await broker.get_task(UUID(task_id))
current_status = task.status.value if hasattr(task.status, "value") else task.status
current_artifacts = task.artifacts or []
# Emit status update if changed
if current_status != last_status:
is_final = task.status in TERMINAL_STATUSES
event = TaskStatusUpdateEvent(
id=str(task.id),
status=current_status,
final=is_final,
)
yield f"event: status\ndata: {event.model_dump_json()}\n\n"
last_status = current_status
if is_final:
# Emit final task state and close
yield f"event: done\ndata: {json.dumps(_task_to_dict(task))}\n\n"
return
# Emit artifact updates if new ones appeared
if len(current_artifacts) > last_artifact_count:
for artifact in current_artifacts[last_artifact_count:]:
event = TaskArtifactUpdateEvent(
id=str(task.id),
artifact=artifact,
)
yield f"event: artifact\ndata: {event.model_dump_json()}\n\n"
last_artifact_count = len(current_artifacts)
except Exception:
logger.exception(f"SSE poll error for task {task_id}")
yield f"event: error\ndata: {json.dumps({'message': 'Internal error'})}\n\n"
return
# Heartbeat (SSE comment) so CF Worker / proxies see bytes
# flowing during quiet periods and don't abort the connection.
yield ": keepalive\n\n"
await asyncio.sleep(SSE_POLL_INTERVAL)
elapsed += SSE_POLL_INTERVAL
# Timed out
yield f"event: timeout\ndata: {json.dumps({'message': 'Stream max duration reached'})}\n\n"
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
|