trusty-common 0.70.10

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
//! [`InferenceError`] — the structured error surface for inference calls.
//!
//! Why: a library must expose structured errors (not `anyhow`) so callers can
//! programmatically decide "retry this" vs. "this needs an operator". The two
//! classifications every consumer needs — is this transient/retryable, and is
//! this an alarm (config/auth/capability problem a human must fix) — are folded
//! into methods on one enum so the policy lives in one place, not re-derived at
//! each call site. It unions the failure modes tcode's `LlmError` and
//! trusty-review's client already distinguish so #2406 maps onto it directly.
//! What: [`InferenceError`] with a variant per failure class, plus
//! [`InferenceError::is_retryable`] and [`InferenceError::is_alarm`] classifiers.
//! Concrete HTTP adapters (#2403) map `reqwest`/SDK errors into these variants.
//! Test: inline `tests` — `retryable_classification`, `alarm_classification`,
//! `unsupported_capability_alarms_and_does_not_retry`, `display_includes_context`,
//! `bedrock_variant_keeps_the_provider_display_and_classification`.

use crate::inference::registry::ProviderId;

/// Errors raised by an [`super::adapter::InferenceAdapter`] or the configurator.
///
/// Why: structured variants let the agent loop pattern-match on failure mode —
/// a 429 or a transport blip is retryable, a 401 or a missing credential is an
/// alarm — without parsing display strings.
/// What: transport, API (non-2xx), deserialisation, credential-resolution,
/// adapter-registration, provider-specific, and unsupported-capability variants.
/// Kept `String`-carrying (rather than `#[from] reqwest::Error`) so this
/// foundation crate stays free of a concrete HTTP dependency; #2403's adapters
/// stringify their transport errors into [`Self::Transport`].
/// Test: `retryable_classification`, `alarm_classification`.
#[derive(Debug, thiserror::Error)]
pub enum InferenceError {
    /// The HTTP/transport layer failed (connection refused, TLS, timeout).
    #[error("inference transport error: {0}")]
    Transport(String),

    /// The provider returned a non-2xx status.
    #[error("inference API error {status}: {body}")]
    Api {
        /// HTTP status code.
        status: u16,
        /// Raw response body (may be JSON or plain text).
        body: String,
    },

    /// The response body could not be deserialised into a [`super::ChatResponse`].
    #[error("inference response deserialisation failed: {message}")]
    Deserialise {
        /// Human-readable parse error (never contains the API key).
        message: String,
        /// The raw body that failed to parse (aids debugging).
        body: String,
    },

    /// No credential could be resolved for the target provider.
    ///
    /// Why: distinct from an API 401 — this fires before any network call, when
    /// the configurator's env/`.env.local`/store chain yields nothing.
    #[error("no credential resolved for provider {provider}")]
    MissingCredential {
        /// The provider whose key could not be found.
        provider: ProviderId,
    },

    /// The configurator has no adapter factory registered for the resolved
    /// provider.
    ///
    /// Why: the two-stage resolver picked a provider, but no adapter was wired
    /// in for it (in this foundation ticket only the test-support factory exists;
    /// real factories register in #2403).
    #[error("no adapter registered for provider {provider}")]
    NoAdapterRegistered {
        /// The provider that resolved but has no factory.
        provider: ProviderId,
    },

    /// A provider-specific failure that does not fit the HTTP shapes (e.g. an
    /// AWS Bedrock SDK error).
    #[error("inference provider error: {0}")]
    Provider(String),

    /// A requested capability is not supported by the target provider/model.
    #[error("unsupported inference capability: {0}")]
    Unsupported(String),

    /// The request asked for a capability the resolved provider does not have.
    ///
    /// Why (#5588): [`Self::Unsupported`] carries free text, so a caller cannot
    /// tell WHICH provider refused WHICH capability without parsing the display
    /// string — and the structured-output path needs exactly that, because the
    /// recovery is "route this request to a provider that supports it". Raised
    /// before any network call: a schema the provider cannot honour is a
    /// mis-routed request, not a completion to send and hope about.
    /// What: names the provider and the registry capability it lacks.
    /// Classifies as an alarm (route or configure differently) and never as
    /// retryable — the same provider will refuse the same request forever.
    /// Test: `unsupported_capability_alarms_and_does_not_retry`.
    #[error("provider {provider} does not support the {capability} capability")]
    UnsupportedCapability {
        /// The provider that would have served the request.
        provider: ProviderId,
        /// The registry capability the request needed, e.g.
        /// `"structured_output"`.
        capability: &'static str,
    },

    /// A required configuration value is missing, described in free text.
    ///
    /// Why (#4425): [`Self::MissingCredential`] can only name a [`ProviderId`]
    /// — it cannot carry an operator-actionable message, and it cannot describe
    /// a missing NON-credential setting (an unset AWS region, an unconfigured
    /// model slug, a test double with no scripted response left). trusty-code's
    /// former `LlmError::MissingConfig` covered exactly that ground, and its
    /// migration onto this shared enum would otherwise have had to flatten
    /// those messages into [`Self::Unsupported`] — whose display text
    /// ("unsupported inference capability: OPENROUTER_API_KEY not set") would
    /// actively mislead the operator reading the log line.
    /// What: a free-text description of what is missing. Classifies as an alarm
    /// (a human must set something) and never as retryable, matching
    /// [`Self::MissingCredential`].
    /// Test: `missing_config_alarms_and_does_not_retry`.
    #[error("missing configuration: {0}")]
    MissingConfig(String),

    /// A Bedrock `Converse`/`ConverseStream` send failed; the cause is typed.
    ///
    /// Why (#10892): the adapter used to flatten every send failure into
    /// [`Self::Provider`], so a caller that had to tell a missing credential
    /// from a throttle from a timeout parsed the display text. The typed
    /// [`BedrockError`] carries that distinction.
    /// What: wraps a [`BedrockError`]. The display text is the one
    /// [`Self::Provider`] produced for the same failure, and
    /// [`Self::is_retryable`] / [`Self::is_alarm`] both stay `false`, as they
    /// were for [`Self::Provider`]: a caller's retry and alarm policy does not
    /// change. A caller that wants a finer policy matches the inner variant.
    /// Test: `bedrock_variant_keeps_the_provider_display_and_classification`.
    #[error("inference provider error: {0}")]
    Bedrock(#[from] BedrockError),
}

/// Why a Bedrock `Converse` or `ConverseStream` send failed.
///
/// Why (#10892): a consumer that must report WHY a call failed — the
/// delegation-guard evaluator records `timeout|transport|auth|...` on every
/// unavailable verdict — needs the cause as a value. A display string is not
/// a contract.
/// What: one variant per failure class the AWS SDK distinguishes. Every
/// variant carries the full context message
/// (`<Operation> call failed (model=…, region=…): <AWS source chain>`); `Api`
/// also carries the HTTP status and the AWS error code. A failure to resolve
/// AWS credentials is [`Self::MissingCredential`] whatever SDK phase reported
/// it, so it is never mistaken for a network fault.
/// Test: `send_error_service_error_maps_to_api_with_status_and_code`,
/// `send_error_dispatch_io_maps_to_transport`,
/// `send_error_timeouts_map_to_timeout`,
/// `send_error_credentials_error_maps_to_missing_credential`,
/// `send_error_construction_failure_maps_to_other`,
/// `chat_without_credentials_returns_missing_credential`.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum BedrockError {
    /// AWS answered with a non-2xx service error.
    #[error("{message}")]
    Api {
        /// HTTP status of the AWS response.
        status: u16,
        /// AWS error code, e.g. `ThrottlingException`, when AWS sent one.
        code: Option<String>,
        /// Full context message.
        message: String,
    },
    /// The request was not delivered: connect, TLS or I/O failure.
    #[error("{0}")]
    Transport(String),
    /// No AWS credential could be resolved, so nothing was sent.
    #[error("{0}")]
    MissingCredential(String),
    /// The SDK gave up waiting: an operation, attempt or connect timeout.
    #[error("{0}")]
    Timeout(String),
    /// Any other SDK failure: request construction or an unreadable response.
    #[error("{0}")]
    Other(String),
}

impl InferenceError {
    /// Whether retrying the same call may succeed.
    ///
    /// Why: the agent loop applies backoff+retry to transient failures only —
    /// retrying a 401 or a schema mismatch just wastes budget.
    /// What: `true` for [`Self::Transport`] and for [`Self::Api`] with a 429 or
    /// any 5xx status; `false` otherwise.
    /// Test: `retryable_classification`.
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Transport(_) => true,
            Self::Api { status, .. } => *status == 429 || (500..=599).contains(status),
            _ => false,
        }
    }

    /// Whether this failure needs operator attention rather than a retry.
    ///
    /// Why: config/auth/capability problems are dead-ends for automated retry —
    /// surfacing them as alarms lets the caller stop and report instead of
    /// spinning.
    /// What: `true` for missing-credential, no-adapter-registered, unsupported,
    /// and authentication/authorisation/not-found API statuses (401/403/404);
    /// `false` otherwise.
    /// Test: `alarm_classification`.
    pub fn is_alarm(&self) -> bool {
        match self {
            Self::MissingCredential { .. }
            | Self::NoAdapterRegistered { .. }
            | Self::Unsupported(_)
            | Self::UnsupportedCapability { .. }
            | Self::MissingConfig(_) => true,
            Self::Api { status, .. } => matches!(status, 401 | 403 | 404),
            _ => false,
        }
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    /// Why: only transient failures may be retried.
    /// Test: itself.
    #[test]
    fn retryable_classification() {
        assert!(InferenceError::Transport("timeout".into()).is_retryable());
        assert!(
            InferenceError::Api {
                status: 429,
                body: "slow down".into()
            }
            .is_retryable()
        );
        assert!(
            InferenceError::Api {
                status: 503,
                body: "unavailable".into()
            }
            .is_retryable()
        );
        assert!(
            !InferenceError::Api {
                status: 401,
                body: "bad key".into()
            }
            .is_retryable()
        );
        assert!(
            !InferenceError::MissingCredential {
                provider: ProviderId::OpenRouter
            }
            .is_retryable()
        );
    }

    /// Why: config/auth/capability failures must alarm, not retry.
    /// Test: itself.
    #[test]
    fn alarm_classification() {
        assert!(
            InferenceError::MissingCredential {
                provider: ProviderId::Anthropic
            }
            .is_alarm()
        );
        assert!(
            InferenceError::NoAdapterRegistered {
                provider: ProviderId::Fireworks
            }
            .is_alarm()
        );
        assert!(InferenceError::Unsupported("vision".into()).is_alarm());
        assert!(
            InferenceError::Api {
                status: 403,
                body: "denied".into()
            }
            .is_alarm()
        );
        assert!(!InferenceError::Transport("blip".into()).is_alarm());
    }

    /// A missing configuration value alarms and is never retried.
    ///
    /// Why (#4425): retrying a call whose configuration is absent burns budget
    /// and can never succeed — the classification must match
    /// [`InferenceError::MissingCredential`]'s, or trusty-code's migrated
    /// missing-key paths would start spinning under the loop's retry policy.
    /// What: assert `is_alarm()` and `!is_retryable()`, and that the display
    /// carries the operator-facing text verbatim.
    /// Test: this test.
    #[test]
    fn missing_config_alarms_and_does_not_retry() {
        let e = InferenceError::MissingConfig("OPENROUTER_API_KEY not set".into());
        assert!(e.is_alarm());
        assert!(!e.is_retryable());
        assert!(e.to_string().contains("OPENROUTER_API_KEY not set"), "{e}");
    }

    /// A missing provider capability alarms, never retries, and names both parts.
    ///
    /// Why (#5588): the caller's recovery is to route elsewhere or drop the
    /// schema, so this must alarm; retrying the same provider can never succeed.
    /// The display has to carry the provider AND the capability, because
    /// "unsupported capability" alone tells an operator nothing about which
    /// provider to reconfigure.
    /// What: assert `is_alarm()`, `!is_retryable()`, and both halves of the text.
    /// Test: this test.
    #[test]
    fn unsupported_capability_alarms_and_does_not_retry() {
        let e = InferenceError::UnsupportedCapability {
            provider: ProviderId::Local,
            capability: "structured_output",
        };
        assert!(e.is_alarm());
        assert!(!e.is_retryable());
        let s = e.to_string();
        assert!(s.contains("local"), "{s}");
        assert!(s.contains("structured_output"), "{s}");
    }

    /// A wrapped Bedrock failure displays and classifies as `Provider` did.
    ///
    /// Why (#10892): typing the Bedrock send error must not change a caller's
    /// log text or its retry/alarm policy.
    /// What: for each `BedrockError` variant, assert the display equals the
    /// `Provider` display of the same message and neither classifier fires.
    /// Test: this test.
    #[test]
    fn bedrock_variant_keeps_the_provider_display_and_classification() {
        let msg = "Converse call failed (model=m, region=r): boom";
        for inner in [
            BedrockError::Api {
                status: 429,
                code: Some("ThrottlingException".into()),
                message: msg.into(),
            },
            BedrockError::Transport(msg.into()),
            BedrockError::MissingCredential(msg.into()),
            BedrockError::Timeout(msg.into()),
            BedrockError::Other(msg.into()),
        ] {
            let e = InferenceError::from(inner);
            assert_eq!(
                e.to_string(),
                InferenceError::Provider(msg.into()).to_string()
            );
            assert!(!e.is_retryable() && !e.is_alarm(), "{e:?}");
        }
    }

    /// Why: display strings feed logs and must carry the actionable context.
    /// Test: itself.
    #[test]
    fn display_includes_context() {
        let e = InferenceError::Api {
            status: 429,
            body: "rate limited".into(),
        };
        let s = e.to_string();
        assert!(s.contains("429"), "{s}");
        assert!(s.contains("rate limited"), "{s}");
    }
}