crewhub / src /core /exceptions.py
arimatch1's picture
Squashed: deploy from GitHub Actions
04bb755
Raw History Blame Contribute Delete
8.65 kB
# 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,)