merry 0.1.4

Rust SDK facade for the Merry coding agent runtime (CLI available as `merry-cli`).
Documentation
//! Language-neutral error classification for foreign-language bindings.
//!
//! Converts typed Rust facade errors into bounded, non-sensitive
//! [`MerryErrorInfo`] diagnostics so Python, UniFFI/Swift, and future SDKs
//! share one authoritative error taxonomy.

use crate::{AgentBuildError, AgentError, profiles::CodingAgentProfileBuildError};
use merry_core::{MerryErrorDomain, MerryErrorInfo, MerryRetryability};

const MAX_MESSAGE_CHARS: usize = 4096;

/// Classifies an [`AgentBuildError`] into a stable [`MerryErrorInfo`].
#[must_use]
pub fn classify_agent_build_error(error: &AgentBuildError) -> MerryErrorInfo {
    if let AgentBuildError::Runtime {
        source:
            crate::runtime::RuntimeError::SessionStore {
                source: crate::runtime::SessionStoreError::SessionAlreadyReserved { session_id },
            },
    } = error
    {
        return build_error_info(
            error.diagnostic_code(),
            MerryErrorDomain::Runtime,
            MerryRetryability::Retryable,
            &error.to_string(),
            Some(
                "Close the active Agent holding this session lock or wait for the other process to finish before retrying.",
            ),
            Some(("session_id", session_id.as_str())),
        );
    }

    let domain = match error {
        AgentBuildError::Tool { .. } => MerryErrorDomain::Tool,
        AgentBuildError::Runtime { .. } => MerryErrorDomain::Runtime,
        AgentBuildError::Profile { .. }
        | AgentBuildError::LoopConfig { .. }
        | AgentBuildError::MissingPrimaryProvider => MerryErrorDomain::Config,
    };

    build_error_info(
        error.diagnostic_code(),
        domain,
        MerryRetryability::UserActionRequired,
        &error.to_string(),
        Some("Review the provider, workspace, and tool configuration."),
        None,
    )
}

/// Classifies an [`AgentError`] into a stable [`MerryErrorInfo`].
#[must_use]
pub fn classify_agent_error(error: &AgentError) -> MerryErrorInfo {
    if let AgentError::Runtime {
        source: crate::runtime::RuntimeError::SessionClosed { session_id },
    } = error
    {
        return build_error_info(
            error.diagnostic_code(),
            MerryErrorDomain::Runtime,
            MerryRetryability::NotRetryable,
            &error.to_string(),
            Some("Create a new Agent or resume the session from its store after closing."),
            Some(("session_id", session_id.as_str())),
        );
    }

    let (domain, retryability, hint) = match error {
        AgentError::ToolInvocationBatchMismatch { .. }
        | AgentError::ToolInvocationBatchResolved
        | AgentError::ToolInvocationBatchPending
        | AgentError::ToolInvocationBatchNotPending => (
            MerryErrorDomain::Tool,
            MerryRetryability::UserActionRequired,
            "Submit exactly one result for every invocation in the active batch.",
        ),
        AgentError::HookInvocationPending | AgentError::HookInvocationNotPending => (
            MerryErrorDomain::Runtime,
            MerryRetryability::UserActionRequired,
            "Resolve the active hook invocation before advancing the run.",
        ),
        AgentError::AgentRunNotFinished
        | AgentError::AgentRunResultConsumed
        | AgentError::AgentRunResultMissing
        | AgentError::AgentRunProtocol { .. } => (
            MerryErrorDomain::Runtime,
            MerryRetryability::UserActionRequired,
            "Follow the run message and terminal-result lifecycle.",
        ),
        AgentError::FinalOutputContract { .. } => (
            MerryErrorDomain::Config,
            MerryRetryability::UserActionRequired,
            "Review the structured output model and its JSON schema.",
        ),
        AgentError::StructuredOutputNotRecorded { .. }
        | AgentError::StructuredOutputDecode { .. } => (
            MerryErrorDomain::Runtime,
            MerryRetryability::NotRetryable,
            "Inspect the terminal run result before retrying structured decoding.",
        ),
        AgentError::Interactive {
            source: crate::runtime::InteractiveError::Runtime { source },
        }
        | AgentError::Runtime { source }
            if matches!(
                source,
                crate::runtime::RuntimeError::Compaction { .. }
                    | crate::runtime::RuntimeError::CompactionModelRequest { .. }
                    | crate::runtime::RuntimeError::CompactionModelWindowTooSmall { .. }
                    | crate::runtime::RuntimeError::CompactionModelRequestTooLarge { .. }
                    | crate::runtime::RuntimeError::CompactionModelSetup { .. }
                    | crate::runtime::RuntimeError::CompactionModelStream { .. }
                    | crate::runtime::RuntimeError::CompactionModelTruncated { .. }
            ) =>
        {
            (
                MerryErrorDomain::Compaction,
                MerryRetryability::Unknown,
                "Inspect the compaction diagnostic and policy limits before retrying.",
            )
        }
        AgentError::Interactive { .. } | AgentError::InteractiveProtocol { .. } => (
            MerryErrorDomain::Runtime,
            MerryRetryability::UserActionRequired,
            "Review the interactive run lifecycle.",
        ),
        AgentError::ToolHandoffRequired => (
            MerryErrorDomain::Tool,
            MerryRetryability::UserActionRequired,
            "Use the host-tool handoff API for bridge tools.",
        ),
        AgentError::Runtime { .. } | AgentError::Loop { .. } => (
            MerryErrorDomain::Runtime,
            MerryRetryability::Unknown,
            "Inspect the returned diagnostic before retrying.",
        ),
    };

    build_error_info(
        error.diagnostic_code(),
        domain,
        retryability,
        &error.to_string(),
        Some(hint),
        None,
    )
}

/// Classifies a [`CodingAgentProfileBuildError`] into a stable [`MerryErrorInfo`].
#[must_use]
pub fn classify_profile_build_error(error: &CodingAgentProfileBuildError) -> MerryErrorInfo {
    let message = match error {
        CodingAgentProfileBuildError::WorkspaceTools(_) => {
            "workspace tool configuration was rejected"
        }
        CodingAgentProfileBuildError::ProcessTool(_) => "process tool configuration was rejected",
        CodingAgentProfileBuildError::PermissionTool(_) => {
            "permission tool configuration was rejected"
        }
        CodingAgentProfileBuildError::Core(_) => {
            "workspace profile protocol configuration was rejected"
        }
        CodingAgentProfileBuildError::RuntimeProfile(_) => {
            "workspace runtime profile configuration was rejected"
        }
        CodingAgentProfileBuildError::HashSerialization(_) => {
            "workspace profile identity could not be created"
        }
        CodingAgentProfileBuildError::Prompt(_) => {
            "workspace profile prompt configuration was rejected"
        }
        CodingAgentProfileBuildError::WebToolBuild(_) => "web tool configuration was rejected",
    };
    profile_error_info(message)
}

/// Diagnostic for calling a builder method after `build` or `resume` consumed it.
#[must_use]
pub fn builder_consumed_error_info() -> MerryErrorInfo {
    build_error_info(
        "builder_consumed",
        MerryErrorDomain::Config,
        MerryRetryability::UserActionRequired,
        "agent builder has already been consumed",
        Some("Create a new builder after a failed consuming operation."),
        None,
    )
}

/// Diagnostic for an operation interrupted by cooperative cancellation.
#[must_use]
pub fn cancelled_operation_error_info() -> MerryErrorInfo {
    build_error_info(
        "operation_cancelled",
        MerryErrorDomain::Runtime,
        MerryRetryability::Cancelled,
        "the agent run was cancelled before the requested operation completed",
        Some("Inspect the terminal run result after cancellation."),
        None,
    )
}

/// Diagnostic for concurrent or invalid single-consumer run-state usage.
#[must_use]
pub fn run_state_error_info(message: &str) -> MerryErrorInfo {
    build_error_info(
        "runtime.run_state",
        MerryErrorDomain::Runtime,
        MerryRetryability::NotRetryable,
        message,
        Some("Do not use the same AgentRun concurrently; await the active operation first."),
        None,
    )
}

/// Diagnostic for provider configuration construction errors.
#[must_use]
pub fn provider_config_error_info(message: &str) -> MerryErrorInfo {
    build_error_info(
        "provider.config",
        MerryErrorDomain::Provider,
        MerryRetryability::UserActionRequired,
        message,
        Some("Review the provider configuration without exposing credentials."),
        None,
    )
}

/// Diagnostic for workspace profile configuration errors.
#[must_use]
pub fn profile_error_info(message: &str) -> MerryErrorInfo {
    build_error_info(
        "profile.config",
        MerryErrorDomain::Config,
        MerryRetryability::UserActionRequired,
        message,
        Some("Review the workspace profile and its path scopes."),
        None,
    )
}

/// Diagnostic for general configuration validation errors.
#[must_use]
pub fn config_error_info(message: &str) -> MerryErrorInfo {
    build_error_info(
        "config.invalid",
        MerryErrorDomain::Config,
        MerryRetryability::UserActionRequired,
        message,
        Some("Review the supplied configuration value."),
        None,
    )
}

/// Diagnostic for attempting to use a Cargo feature that was disabled at build time.
#[must_use]
pub fn feature_disabled_error_info(feature: &str, capability: &str) -> MerryErrorInfo {
    build_error_info(
        "feature.disabled",
        MerryErrorDomain::Config,
        MerryRetryability::UserActionRequired,
        &format!("{capability} requires the `{feature}` feature, which is disabled in this build"),
        Some("Rebuild with the required feature enabled or choose a supported configuration."),
        None,
    )
}

/// Diagnostic for invalid binding protocol input payloads.
#[must_use]
pub fn protocol_error_info(message: &str) -> MerryErrorInfo {
    build_error_info(
        "protocol.invalid",
        MerryErrorDomain::Runtime,
        MerryRetryability::UserActionRequired,
        message,
        Some("Use the documented provider-neutral JSON protocol."),
        None,
    )
}

/// Diagnostic for internal protocol serialization failures.
#[must_use]
pub fn serialization_error_info(error: &serde_json::Error) -> MerryErrorInfo {
    build_error_info(
        "protocol.serialization",
        MerryErrorDomain::Runtime,
        MerryRetryability::NotRetryable,
        &error.to_string(),
        Some("The Rust-owned protocol could not be serialized."),
        None,
    )
}

/// Builds a bounded, control-character-sanitized [`MerryErrorInfo`].
#[must_use]
pub fn build_error_info(
    code: &str,
    domain: MerryErrorDomain,
    retryability: MerryRetryability,
    message: &str,
    hint: Option<&str>,
    context: Option<(&str, &str)>,
) -> MerryErrorInfo {
    let bounded = bounded_message(message);
    let mut builder = MerryErrorInfo::builder(code, domain.clone(), &bounded, retryability.clone());
    if let Some(hint) = hint {
        builder = builder.hint(hint);
    }
    if let Some((key, value)) = context {
        builder = builder.context(key, value);
    }
    match builder.build() {
        Ok(info) => info,
        Err(_) => MerryErrorInfo::builder(
            "runtime.diagnostic",
            domain,
            "native Merry operation failed",
            retryability,
        )
        .build()
        .expect("static fallback MerryErrorInfo is always valid"),
    }
}

/// Strips control characters and truncates a diagnostic message to a safe bound.
#[must_use]
pub fn bounded_message(message: &str) -> String {
    let mut bounded = String::new();
    for character in message.chars() {
        if character.is_control() {
            if !bounded.is_empty() && !bounded.ends_with(' ') {
                bounded.push(' ');
            }
        } else {
            bounded.push(character);
        }
        if bounded.chars().count() >= MAX_MESSAGE_CHARS {
            break;
        }
    }
    let bounded = bounded.trim().to_owned();
    if bounded.is_empty() {
        "native Merry operation failed".to_owned()
    } else {
        bounded
    }
}