"""Common API response helpers for the v3 contract.""" from __future__ import annotations from dataclasses import dataclass from enum import StrEnum from typing import Any class ErrorCode(StrEnum): UNAUTHORIZED = "UNAUTHORIZED" FORBIDDEN = "FORBIDDEN" VALIDATION_FAILED = "VALIDATION_FAILED" RESOURCE_NOT_FOUND = "RESOURCE_NOT_FOUND" CONFIG_REVISION_CONFLICT = "CONFIG_REVISION_CONFLICT" TASK_NOT_RETRYABLE = "TASK_NOT_RETRYABLE" TASK_NOT_CANCELABLE = "TASK_NOT_CANCELABLE" MODEL_CAPABILITY_UNCONFIRMED = "MODEL_CAPABILITY_UNCONFIRMED" MODEL_CAPABILITY_UNSUPPORTED = "MODEL_CAPABILITY_UNSUPPORTED" GENERATION_FAILED = "GENERATION_FAILED" STORAGE_WRITE_FAILED = "STORAGE_WRITE_FAILED" MEDIA_NOT_FOUND = "MEDIA_NOT_FOUND" UPLOAD_TOO_LARGE = "UPLOAD_TOO_LARGE" UNSUPPORTED_FILE_TYPE = "UNSUPPORTED_FILE_TYPE" INTEGRATION_TOKEN_INVALID = "INTEGRATION_TOKEN_INVALID" UNKNOWN_ERROR = "UNKNOWN_ERROR" @dataclass(eq=False) class ApiError(Exception): """Domain error carrying a contract error code. Deliberately **not** ``frozen``. A frozen dataclass rejects the ``exc.__traceback__ = tb`` assignment that ``contextlib`` performs when an exception escapes a ``@contextmanager`` body, so a frozen ``ApiError`` raised inside any such block was replaced by ``FrozenInstanceError`` — losing the error code, the message, and the real traceback. ``core/ config_writer.py`` used to work around this by hand-rolling its lock instead of using ``@contextmanager``; the constraint is removed here so ordinary context managers are safe to write. ``eq=False`` keeps ``Exception``'s identity semantics (and therefore hashability), which is what exception handling expects. """ error_code: ErrorCode message: str details: dict[str, Any] | None = None def __post_init__(self) -> None: # Give ``Exception`` its args so ``repr`` and pickling behave, while # ``__str__`` below keeps the human-facing text to just the message. super().__init__(self.error_code, self.message, self.details) def __str__(self) -> str: # Without this, ``str(exc)`` renders the whole ``args`` tuple — # ``"(, 'msg', {...})"`` — and ``main.py`` echoes # ``str(exc)`` straight to chat users in ~44 places, leaking the # ``details`` payload along with it. return self.message def to_response(self, request_id: str | None = None) -> dict[str, Any]: return error_response( error_code=self.error_code, message=self.message, details=self.details, request_id=request_id, ) def success_response( data: Any, *, request_id: str | None = None, warnings: list[str] | None = None, ) -> dict[str, Any]: return { "ok": True, "data": data, "warnings": warnings or [], "request_id": request_id, } def error_response( *, error_code: ErrorCode | str, message: str, details: dict[str, Any] | None = None, request_id: str | None = None, ) -> dict[str, Any]: code = error_code.value if isinstance(error_code, ErrorCode) else error_code return { "ok": False, "error_code": code, "message": message, "details": details or {}, "request_id": request_id, } def response_from_exception(exc: Exception, request_id: str | None = None) -> dict[str, Any]: if isinstance(exc, ApiError): return exc.to_response(request_id=request_id) return error_response( error_code=ErrorCode.UNKNOWN_ERROR, message="\u670d\u52a1\u5668\u5185\u90e8\u9519\u8bef", details={"exception": exc.__class__.__name__}, request_id=request_id, )