File size: 8,647 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
# Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""Custom exception classes for CrewHub."""

from typing import ClassVar


class MarketplaceError(Exception):
    """Base exception for all marketplace errors."""

    def __init__(self, status_code: int = 500, detail: str = "Internal server error"):
        self.status_code = status_code
        self.detail = detail
        super().__init__(detail)


class BadRequestError(MarketplaceError):
    """Invalid request data."""

    def __init__(self, detail: str = "Bad request"):
        super().__init__(status_code=400, detail=detail)


class NotFoundError(MarketplaceError):
    """Resource not found."""

    def __init__(self, detail: str = "Resource not found"):
        super().__init__(status_code=404, detail=detail)


class UnauthorizedError(MarketplaceError):
    """Authentication required or invalid credentials."""

    def __init__(self, detail: str = "Unauthorized"):
        super().__init__(status_code=401, detail=detail)


class ForbiddenError(MarketplaceError):
    """Insufficient permissions."""

    def __init__(self, detail: str = "Forbidden"):
        super().__init__(status_code=403, detail=detail)


class InsufficientCreditsError(MarketplaceError):
    """User does not have enough credits.

    Carries a machine-readable ``code`` plus optional ``required`` and
    ``available`` amounts so clients can render a precise message (and a
    "Buy Credits" CTA) without regex-matching a human string.

    When ``required`` / ``available`` are provided, ``detail`` is a dict
    containing ``code``, ``message``, ``required``, and ``available`` —
    which FastAPI serialises as ``{"detail": {...}}`` via the global
    MarketplaceError handler. When only a string is provided (legacy call
    sites), ``detail`` remains a string and the structured fields default
    to ``None``.
    """

    code: ClassVar[str] = "INSUFFICIENT_CREDITS"

    def __init__(
        self,
        detail: str | None = None,
        *,
        required: float | None = None,
        available: float | None = None,
    ):
        self.required = required
        self.available = available

        if required is not None and available is not None:
            message = detail or (
                f"Insufficient credits: need {required}, have {available}"
            )
            structured: dict = {
                "code": self.code,
                "message": message,
                "required": required,
                "available": available,
            }
            super().__init__(status_code=402, detail=structured)
            # Keep the human message available via str(exc) for logging.
            self.args = (message,)
        else:
            super().__init__(status_code=402, detail=detail or "Insufficient credits")


class ConflictError(MarketplaceError):
    """Resource conflict (e.g., duplicate entry)."""

    def __init__(self, detail: str = "Conflict"):
        super().__init__(status_code=409, detail=detail)


class TaskTerminalError(MarketplaceError):
    """Raised when attempting to cancel/mutate a task already in a terminal state.

    Emitted as a structured 409 so the frontend can branch on
    ``detail.code == "TASK_TERMINAL"`` and show a user-friendly toast
    ("Task already completed — no credits were released") instead of
    silently swallowing a plain-string 403.
    """

    status_code: ClassVar[int] = 409
    code: ClassVar[str] = "TASK_TERMINAL"

    def __init__(self, status: str, detail: str | None = None):
        self.status = status
        message = detail or f"Task already {status} — cannot cancel"
        structured: dict = {
            "code": self.code,
            "message": message,
            "status": status,
        }
        super().__init__(status_code=self.status_code, detail=structured)
        # Keep the human message available via str(exc) for logging.
        self.args = (message,)


class RunTerminalError(MarketplaceError):
    """Raised when attempting to cancel a workflow run already in a terminal state.

    Mirrors ``TaskTerminalError`` — emits a structured 409 so the frontend
    can branch on ``detail.code == "RUN_TERMINAL"`` and surface a friendly
    toast instead of swallowing a plain-string 400/403. Terminal states
    for a ``WorkflowRun`` are ``completed``, ``failed``, and ``canceled``.
    """

    status_code: ClassVar[int] = 409
    code: ClassVar[str] = "RUN_TERMINAL"

    def __init__(self, status: str, detail: str | None = None):
        self.status = status
        message = detail or f"Workflow run already {status} — cannot cancel"
        structured: dict = {
            "code": self.code,
            "message": message,
            "status": status,
        }
        super().__init__(status_code=self.status_code, detail=structured)
        # Keep the human message available via str(exc) for logging.
        self.args = (message,)


class QuotaExceededError(MarketplaceError):
    """Usage quota exceeded for the pricing tier."""

    def __init__(self, detail: str = "Quota exceeded"):
        super().__init__(status_code=429, detail=detail)


class RateLimitError(MarketplaceError):
    """Rate limit exceeded."""

    def __init__(self, detail: str = "Rate limit exceeded"):
        super().__init__(status_code=429, detail=detail)


class PaymentVerificationError(MarketplaceError):
    """x402 payment verification failed."""

    def __init__(self, detail: str = "Payment verification failed"):
        super().__init__(status_code=402, detail=detail)


class AgentUnavailableError(MarketplaceError):
    """Agent is currently unavailable."""

    def __init__(self, detail: str = "Agent unavailable"):
        super().__init__(status_code=503, detail=detail)


class SpendingLimitError(MarketplaceError):
    """User has exceeded their daily spending limit."""

    def __init__(self, detail: str = "Daily spending limit exceeded"):
        super().__init__(status_code=429, detail=detail)


class ContentModerationError(MarketplaceError):
    """Content failed moderation checks."""

    def __init__(self, detail: str = "Content blocked by moderation policy"):
        super().__init__(status_code=422, detail=detail)


class AbuseDetectedError(MarketplaceError):
    """Abusive behavior detected."""

    def __init__(self, detail: str = "Suspicious activity detected"):
        super().__init__(status_code=429, detail=detail)


class DelegationDepthError(MarketplaceError):
    """Delegation chain too deep."""

    def __init__(self, detail: str = "Maximum delegation depth exceeded"):
        super().__init__(status_code=400, detail=detail)


class AgentCardNotFoundError(MarketplaceError):
    """Raised when the agent endpoint doesn't serve /.well-known/agent-card.json.

    Emitted as a structured 422 so the frontend can branch on
    ``detail.code == "AGENT_CARD_NOT_FOUND"`` and surface a friendly
    toast explaining the missing card instead of a generic 400.
    """

    status_code: ClassVar[int] = 422
    code: ClassVar[str] = "AGENT_CARD_NOT_FOUND"

    def __init__(self, url: str, detail: str | None = None):
        self.url = url
        message = detail or (
            "No agent card at .well-known/agent-card.json. "
            "The URL must serve a public agent card."
        )
        structured: dict = {
            "code": self.code,
            "message": message,
            "url": url,
        }
        super().__init__(status_code=self.status_code, detail=structured)
        # Keep the human message available via str(exc) for logging.
        self.args = (message,)


class AgentCardUnreachableError(MarketplaceError):
    """Raised when the agent endpoint is unreachable (5xx, timeout, DNS).

    Emitted as a structured 422 so the frontend can branch on
    ``detail.code == "AGENT_CARD_UNREACHABLE"`` and surface a friendly
    toast suggesting the user verify the URL is public and HTTPS.
    """

    status_code: ClassVar[int] = 422
    code: ClassVar[str] = "AGENT_CARD_UNREACHABLE"

    def __init__(self, url: str, detail: str | None = None):
        self.url = url
        message = detail or (
            "Could not reach the agent endpoint. "
            "Check the URL is publicly accessible over HTTPS."
        )
        structured: dict = {
            "code": self.code,
            "message": message,
            "url": url,
        }
        super().__init__(status_code=self.status_code, detail=structured)
        # Keep the human message available via str(exc) for logging.
        self.args = (message,)