|
| 1 | +"""Exception hierarchy for AgentCore.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Any |
| 6 | + |
| 7 | + |
| 8 | +class AgentCoreError(Exception): |
| 9 | + """Base exception for all AgentCore errors.""" |
| 10 | + |
| 11 | + |
| 12 | +# ── Kernel errors ─────────────────────────────────────────────────────────── |
| 13 | + |
| 14 | + |
| 15 | +class KernelError(AgentCoreError): |
| 16 | + """Errors originating from the OS kernel layer.""" |
| 17 | + |
| 18 | + |
| 19 | +class TaskNotFoundError(KernelError): |
| 20 | + def __init__(self, task_id: str) -> None: |
| 21 | + super().__init__(f"Task not found: {task_id}") |
| 22 | + self.task_id = task_id |
| 23 | + |
| 24 | + |
| 25 | +class InvalidStateTransition(KernelError): |
| 26 | + def __init__(self, task_id: str, current: str, target: str) -> None: |
| 27 | + super().__init__(f"Invalid transition for {task_id}: {current} → {target}") |
| 28 | + |
| 29 | + |
| 30 | +class ServiceNotRegistered(KernelError): |
| 31 | + def __init__(self, service_type: type) -> None: |
| 32 | + super().__init__(f"Service not registered: {service_type.__name__}") |
| 33 | + |
| 34 | + |
| 35 | +class PermissionDenied(KernelError): |
| 36 | + def __init__(self, role: str, tool: str) -> None: |
| 37 | + super().__init__(f"Role '{role}' has no permission for tool '{tool}'") |
| 38 | + |
| 39 | +# LLM request errors |
| 40 | + |
| 41 | +class LLMError(AgentCoreError): |
| 42 | + """Errors from the LLM/provider layer.""" |
| 43 | + |
| 44 | + |
| 45 | +class LLMReasoningRunaway(LLMError): |
| 46 | + """A live stream spent its semantic budget on reasoning-only output. |
| 47 | +
|
| 48 | + Unlike :class:`LLMStreamStalled`, the provider is healthy and actively |
| 49 | + emitting chunks. The failure is semantic: no non-whitespace visible text |
| 50 | + or tool-call delta appeared before the configured time/token guard fired. |
| 51 | +
|
| 52 | + ``partial_response`` is intentionally carried separately from provider |
| 53 | + usage. Early stream cancellation often happens before the terminal usage |
| 54 | + chunk arrives, so its estimated reasoning tokens must never be presented |
| 55 | + as authoritative billing data. |
| 56 | + """ |
| 57 | + |
| 58 | + def __init__( |
| 59 | + self, |
| 60 | + *, |
| 61 | + elapsed_s: float, |
| 62 | + estimated_tokens: int, |
| 63 | + trigger: str, |
| 64 | + partial_response: Any, |
| 65 | + ) -> None: |
| 66 | + self.elapsed_s = float(elapsed_s) |
| 67 | + self.estimated_tokens = int(estimated_tokens) |
| 68 | + self.trigger = trigger |
| 69 | + self.partial_response = partial_response |
| 70 | + super().__init__( |
| 71 | + "reasoning-only stream exceeded " |
| 72 | + f"{trigger} guard (elapsed={self.elapsed_s:.1f}s, " |
| 73 | + f"estimated_tokens={self.estimated_tokens})", |
| 74 | + ) |
| 75 | + |
| 76 | + |
| 77 | +class LLMStreamStalled(LLMError, TimeoutError): |
| 78 | + """A streaming LLM call went silent mid-flight. |
| 79 | +
|
| 80 | + Subclasses ``asyncio.TimeoutError`` so every existing transient- |
| 81 | + timeout handler (retry/backoff in ``call_llm``, chain wrappers, |
| 82 | + classification) treats it identically without changes; carried |
| 83 | + fields make the distinct failure mode visible in logs and traces. |
| 84 | + """ |
| 85 | + |
| 86 | + def __init__( |
| 87 | + self, stall_s: float, chunks_seen: int, elapsed_s: float, |
| 88 | + ) -> None: |
| 89 | + self.stall_s = stall_s |
| 90 | + self.chunks_seen = chunks_seen |
| 91 | + self.elapsed_s = elapsed_s |
| 92 | + super().__init__( |
| 93 | + f"stream stalled: no chunks for {stall_s:.0f}s " |
| 94 | + f"(chunks_seen={chunks_seen}, elapsed={elapsed_s:.0f}s)", |
| 95 | + ) |
| 96 | + |
| 97 | + |
| 98 | +class LLMDeadlineExceeded(LLMError, TimeoutError): |
| 99 | + """An LLM attempt was stopped by an enclosing runtime deadline. |
| 100 | +
|
| 101 | + ``reason`` is deliberately carried on the underlying exception as well as |
| 102 | + on :class:`LLMCallExhausted`. Some callers unwrap ``last_exc`` before |
| 103 | + handing it to a provider-chain policy; a dedicated type prevents that |
| 104 | + policy from mistaking an exhausted run budget for an ordinary transient |
| 105 | + provider timeout. |
| 106 | + """ |
| 107 | + |
| 108 | + def __init__(self, reason: str, detail: str) -> None: |
| 109 | + self.reason = reason |
| 110 | + super().__init__(f"{reason}: {detail}") |
| 111 | + |
| 112 | + |
| 113 | +class LLMCallExhausted(LLMError, RuntimeError): |
| 114 | + """Raised by ``call_llm`` when retries are exhausted or the error is |
| 115 | + structurally unrecoverable (4xx without proxy-wrap, or a chain-aware |
| 116 | + fallback signal like ``model_not_found``). |
| 117 | +
|
| 118 | + Wraps the last exception encountered so the caller (typically the |
| 119 | + product's agent loop) can surface it to a provider-chain wrapper for |
| 120 | + L1→L2→L3 rotation. Carries ``last_exc`` separately because |
| 121 | + ``raise from`` is too opaque for chain-aware classification — a chain |
| 122 | + wrapper calls ``classify_error(last_exc)`` directly. |
| 123 | +
|
| 124 | + ``last_exc`` must always agree with ``reason``: it is the exception that |
| 125 | + *caused this raise*, not merely the most recent failure seen. A deadline |
| 126 | + refusal therefore carries :class:`LLMDeadlineExceeded` even when earlier |
| 127 | + attempts failed for unrelated reasons. The wrapper's ``reason`` remains |
| 128 | + authoritative, while the underlying exception preserves the same reason |
| 129 | + if a caller unwraps it before classification. |
| 130 | +
|
| 131 | + ``prior_exc`` is where that earlier, superseded failure goes: diagnostic |
| 132 | + context for logs and post-mortems, deliberately outside the field |
| 133 | + classification reads. |
| 134 | + """ |
| 135 | + |
| 136 | + def __init__( |
| 137 | + self, |
| 138 | + last_exc: BaseException, |
| 139 | + reason: str, |
| 140 | + *, |
| 141 | + prior_exc: BaseException | None = None, |
| 142 | + ) -> None: |
| 143 | + self.last_exc = last_exc |
| 144 | + self.reason = reason |
| 145 | + self.prior_exc = prior_exc |
| 146 | + detail = f"call_llm {reason}: {last_exc!r}" |
| 147 | + if prior_exc is not None and prior_exc is not last_exc: |
| 148 | + detail += f" (after {prior_exc!r})" |
| 149 | + super().__init__(detail) |
| 150 | + |
| 151 | + |
| 152 | +__all__ = [ |
| 153 | + "AgentCoreError", |
| 154 | + "InvalidStateTransition", |
| 155 | + "KernelError", |
| 156 | + "LLMCallExhausted", |
| 157 | + "LLMDeadlineExceeded", |
| 158 | + "LLMError", |
| 159 | + "LLMReasoningRunaway", |
| 160 | + "LLMStreamStalled", |
| 161 | + "PermissionDenied", |
| 162 | + "ServiceNotRegistered", |
| 163 | + "TaskNotFoundError", |
| 164 | +] |
0 commit comments