File size: 5,146 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
# Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""Agent detection endpoint — fetch and parse a remote agent card."""

import logging

import httpx
from fastapi import APIRouter, Depends, HTTPException

from src.core.exceptions import AgentCardNotFoundError, AgentCardUnreachableError
from src.core.rate_limiter import rate_limit_by_ip
from src.core.url_validator import validate_public_url
from src.schemas.detect import DetectRequest, DetectedSkill, DetectResponse

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/agents", tags=["agents"])


@router.post("/detect", response_model=DetectResponse, dependencies=[Depends(rate_limit_by_ip)])
async def detect_agent(
    data: DetectRequest,
) -> DetectResponse:
    """Auto-detect an agent by fetching its .well-known/agent-card.json."""

    validate_public_url(data.url)
    base_url = data.url.rstrip("/")
    card_url = base_url + "/.well-known/agent-card.json"

    # Fetch the agent card
    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            resp = await client.get(card_url)
    except httpx.TimeoutException:
        raise AgentCardUnreachableError(
            url=base_url, detail="Endpoint timed out after 10s."
        )
    except httpx.ConnectError:
        raise AgentCardUnreachableError(url=base_url)
    except httpx.HTTPError:
        raise AgentCardUnreachableError(url=base_url)

    if resp.status_code == 404:
        raise AgentCardNotFoundError(url=base_url)
    if resp.status_code >= 500:
        raise AgentCardUnreachableError(
            url=base_url,
            detail=f"Agent endpoint returned HTTP {resp.status_code}.",
        )
    if resp.status_code != 200:
        # 4xx other than 404: endpoint exists but refuses. Treat as
        # missing card for UX simplicity — the user can't register from
        # a non-200 card fetch regardless of which 4xx it is.
        raise AgentCardNotFoundError(
            url=base_url,
            detail=f"Agent endpoint returned HTTP {resp.status_code}.",
        )

    try:
        card = resp.json()
    except Exception:
        raise HTTPException(status_code=400, detail="Agent card is not valid JSON")

    if not isinstance(card, dict):
        raise HTTPException(status_code=400, detail="Agent card is not valid JSON")

    # Validate required field
    name = card.get("name")
    if not name:
        raise HTTPException(
            status_code=400,
            detail="Agent card missing required field: name",
        )

    # Extract fields with defaults
    description = card.get("description", "")
    version = card.get("version", "1.0.0")
    url = card.get("url", base_url)
    capabilities = card.get("capabilities", {})

    warnings: list[str] = []
    if not description:
        warnings.append("Missing description")

    # Parse skills
    raw_skills = card.get("skills", [])
    skills: list[DetectedSkill] = []
    if not raw_skills:
        warnings.append("No skills found")

    for s in raw_skills:
        if not isinstance(s, dict):
            continue
        skill_key = s.get("id", s.get("skill_key", ""))
        skill_name = s.get("name", skill_key)
        skill_desc = s.get("description", "")
        input_modes = s.get("inputModes", s.get("input_modes", ["text"]))
        output_modes = s.get("outputModes", s.get("output_modes", ["text"]))
        if skill_key:
            skills.append(
                DetectedSkill(
                    skill_key=skill_key,
                    name=skill_name,
                    description=skill_desc,
                    input_modes=input_modes,
                    output_modes=output_modes,
                )
            )

    # Build suggested registration payload (AgentCreate-compatible)
    suggested_registration = {
        "name": name,
        "description": description or f"Agent: {name}",
        "version": version,
        "endpoint": base_url,
        "capabilities": capabilities,
        "skills": [
            {
                "skill_key": sk.skill_key,
                "name": sk.name,
                "description": sk.description or f"Skill: {sk.name}",
                "input_modes": sk.input_modes,
                "output_modes": sk.output_modes,
                "examples": [],
                "avg_credits": 0,
                "avg_latency_ms": 0,
            }
            for sk in skills
        ],
        "security_schemes": card.get("securitySchemes", []),
        "category": "general",
        "tags": [],
        "pricing": {
            "license_type": "open",
            "tiers": [],
            "model": "per_task",
            "credits": 1,
            "trial_days": None,
            "trial_task_limit": None,
        },
        "accepted_payment_methods": ["credits"],
    }

    return DetectResponse(
        name=name,
        description=description,
        url=url,
        version=version,
        capabilities=capabilities,
        skills=skills,
        suggested_registration=suggested_registration,
        card_url=card_url,
        warnings=warnings,
    )