Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-harness/src/runtime.rs

Raw
//! Runtime assembly: configuration to agent (`SMH-SPEC-SPEC0001`,
//! Providers).
//!
//! One shape serves eval and RPC. Mock providers run scripted responses for
//! offline use; real providers post through the vendor transport with
//! credentials resolved from the environment.

use crate::plugin_control::ReloadControl;
use crate::plugins::registry::PackageRegistry;
use crate::protocol::{ProtocolComponent, ProtocolConnection, ProtocolConnectionConfig};
use crate::wasm::bindings::exports::smith::plugin::provider::{
    CatalogModel, CatalogSnapshot, CatalogSource, ModelCapabilities, ProviderSettings,
    SettingsProvenance,
};
use crate::wasm::{ToolPolicy, runtime_tools_dispatcher};
use smith::config::Config;
use smith::error::{Result, SmithError};
use smith::provider::RecordSink;
use smith::provider::StreamFn;
use smith_ai::auth::{AuthStore, CredentialKey, CredentialReference};
use smith_ai::models::{Catalog, ModelCapabilities as CatalogModelCapabilities, ProviderKind};
use smith_ai::refresh::{CatalogProvenance, CatalogSnapshot as ModelCatalogSnapshot};
use smith_core::agent::Agent;
use smith_core::tools::ToolSession;
use std::path::PathBuf;

/// Which provider a runtime uses.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RuntimeProvider {
    /// Scripted responses; `smh-mock` in the catalog.
    Mock(Vec<Vec<smith::stream::StreamEvent>>),
    /// OpenAI-compatible endpoint.
    OpenAiCompatible {
        /// Base URL, for example `https://api.openai.com/v1`.
        base_url: String,
        /// Model id.
        model: String,
    },
    /// Explicit `ChatGPT` subscription profile; never falls back to API billing.
    OpenAiChatGptPlan {
        /// Selected host profile and isolated credential-source authority.
        credential: crate::oauth::source::SubscriptionCredential,
        /// Explicit model id, intersected with account entitlement at dispatch.
        model: String,
    },
    /// Claude subscription with an explicit opaque local profile.
    /// Google subscription with an explicitly admitted project profile.
    GoogleGeminiCliPlan {
        /// Selected Google credential.
        credential: crate::oauth::source::SubscriptionCredential,
        /// Explicit model ID.
        model: String,
    },
    /// Claude subscription with an explicit local profile.
    AnthropicClaudePlan {
        /// Selected vendor-isolated renewable credential.
        credential: crate::oauth::source::SubscriptionCredential,
        /// Explicit model, never an API billing fallback.
        model: String,
    },
    /// Anthropic Messages endpoint.
    Anthropic {
        /// Base URL.
        base_url: String,
        /// Model id.
        model: String,
    },
    /// Google Gemini endpoint.
    Google {
        /// Base URL.
        base_url: String,
        /// Model id.
        model: String,
    },
    /// Z.ai system component and host-scoped endpoint.
    Zai {
        /// Explicit development component override; absent uses the embedded release component.
        artifact: Option<PathBuf>,
        /// Authorized endpoint base URL.
        base_url: String,
        /// Billing connection selected before dispatch.
        connection: ProtocolConnection,
        /// Model id.
        model: String,
    },
}

impl RuntimeProvider {
    /// The catalog model id this provider serves.
    #[must_use]
    pub fn model(&self) -> &str {
        match self {
            Self::Mock(_) => "mock-smith",
            Self::OpenAiCompatible { model, .. }
            | Self::Anthropic { model, .. }
            | Self::Google { model, .. }
            | Self::Zai { model, .. }
            | Self::OpenAiChatGptPlan { model, .. }
            | Self::GoogleGeminiCliPlan { model, .. }
            | Self::AnthropicClaudePlan { model, .. } => model,
        }
    }

    /// Whether startup must load the catalog to validate this connection.
    #[must_use]
    pub fn requires_catalog_validation(&self) -> bool {
        match self {
            Self::Mock(_) => false,
            Self::Zai { .. }
            | Self::OpenAiChatGptPlan { .. }
            | Self::GoogleGeminiCliPlan { .. }
            | Self::AnthropicClaudePlan { .. } => true,
            Self::OpenAiCompatible { base_url, .. }
            | Self::Anthropic { base_url, .. }
            | Self::Google { base_url, .. } => {
                base_url == smith_ai::auth::default_base_url(self.vendor_kind())
            }
        }
    }

    const fn vendor_kind(&self) -> ProviderKind {
        match self {
            Self::Mock(_) | Self::OpenAiCompatible { .. } | Self::OpenAiChatGptPlan { .. } => {
                ProviderKind::OpenAiCompatible
            }
            Self::Anthropic { .. } | Self::AnthropicClaudePlan { .. } => ProviderKind::Anthropic,
            Self::Google { .. } | Self::GoogleGeminiCliPlan { .. } => ProviderKind::Google,
            Self::Zai { .. } => ProviderKind::Zai,
        }
    }
}

/// Everything needed to assemble a runtime.
#[derive(Clone, Debug)]
pub struct RuntimeConfig {
    /// Provider selection.
    pub provider: RuntimeProvider,
    /// Working directory for tool effects.
    pub workdir: PathBuf,
    /// Session file path; created when missing.
    pub session_path: PathBuf,
    /// Explicit credential override; the highest-precedence source.
    pub api_key: Option<String>,
    /// Credential store directory; the binary passes the XDG default, tests
    /// an isolated one so a developer's own credentials never leak in.
    pub auth_dir: PathBuf,
    /// Host-published catalog pinned before provider assembly.
    pub catalog_snapshot: Option<ModelCatalogSnapshot>,
    /// Immutable effective connection settings, resolved before instantiation.
    pub provider_settings: smith::provider::ProviderSettingsRecord,
    /// Whether the embedded coding-tools package is active.
    pub coding_tools_enabled: bool,
    /// User-private control endpoint for live plugin reload, if this frontend
    /// exposes one.
    pub plugin_control_path: Option<PathBuf>,
    /// Explicit package registry root; absent uses Smith’s XDG configuration.
    /// Mock runtimes root this beside their session to avoid ambient plugins.
    pub plugin_registry_dir: Option<PathBuf>,
    /// Explicit host-owned model-call availability for qualified plugin tools.
    pub tool_policy: ToolPolicy,
    /// Explicit host-owned directed composition delegations.
    pub composition_grants: crate::wasm::CompositionGrants,
}

impl RuntimeConfig {
    /// A mock runtime under `workdir` with a fresh session file.
    #[must_use]
    pub fn mock(workdir: impl Into<PathBuf>, script: Vec<Vec<smith::stream::StreamEvent>>) -> Self {
        let workdir = workdir.into();
        let session_path = workdir.join("session.smh");
        // An auth store beside the session keeps mock runtimes isolated.
        let auth_dir = workdir.join("auth");
        let plugin_registry_dir = workdir.join("plugins");
        Self {
            provider: RuntimeProvider::Mock(script),
            workdir,
            session_path,
            api_key: None,
            auth_dir,
            catalog_snapshot: None,
            provider_settings: smith::provider::ProviderSettingsRecord {
                include_usage: true,
                provenance: smith::provider::ProviderSettingsProvenance::BuiltIn,
            },
            coding_tools_enabled: false,
            plugin_control_path: None,
            plugin_registry_dir: Some(plugin_registry_dir),
            tool_policy: ToolPolicy::default(),
            composition_grants: crate::wasm::CompositionGrants::default(),
        }
    }
}

impl RuntimeProvider {
    /// A real provider endpoint with an explicit model; the base URL falls
    /// back to the vendor default.
    #[must_use]
    pub fn real(kind: ProviderKind, base_url: Option<String>, model: String) -> Self {
        let base_url =
            base_url.unwrap_or_else(|| smith_ai::auth::default_base_url(kind).to_string());
        match kind {
            ProviderKind::OpenAiCompatible | ProviderKind::Plugin => {
                Self::OpenAiCompatible { base_url, model }
            }
            ProviderKind::Anthropic => Self::Anthropic { base_url, model },
            ProviderKind::Google => Self::Google { base_url, model },
            ProviderKind::Zai => Self::Zai {
                artifact: None,
                base_url,
                connection: ProtocolConnection::Api,
                model,
            },
        }
    }
}

/// Assemble an agent from a configuration, opening or creating its session.
///
/// # Errors
///
/// Returns configuration, session, or credential-resolution failures; a
/// missing credential for a real provider fails here, before any dispatch.
pub fn build_agent(config: &RuntimeConfig) -> Result<Agent> {
    let smith_config = Config::default_valid();
    let storage = crate::storage::StorageWorker::start(config.session_path.clone());
    let opened = storage
        .open_for_execution(smith_config)
        .map_err(execution_access_error)?;
    let control = config
        .plugin_control_path
        .clone()
        .map(ReloadControl::bind_at_path)
        .transpose()?;
    let mut tools =
        ToolSession::with_persist(config.workdir.clone(), opened, move |entry, bytes| {
            storage.append(smith_core::session::EntryFrame {
                id: entry.id,
                parent: entry.parent,
                timestamp_ms: entry.timestamp_ms,
                kind: entry.kind,
                content: bytes.to_vec(),
            })
        });
    let dispatcher = tools_dispatcher(config, control);
    let (stream, records, dispatcher) = provider_stream(config, dispatcher)?;
    tools.set_dispatcher(Box::new(dispatcher));
    Ok(Agent::with_provider_records(
        stream,
        tools,
        config.provider.model().to_string(),
        records,
    ))
}

pub(crate) fn execution_access_error(error: SmithError) -> SmithError {
    if error.code() == "STORE_BUSY" {
        SmithError::Session {
            code: smith::error::SessionCode::SessionReadOnly,
            message:
                "another process owns writing; use smith observe <session-id> to attach read-only"
                    .into(),
        }
    } else {
        error
    }
}

/// Execute one durably admitted turn through the ordinary agent and plugin pipeline.
///
/// Completion results, mutation evidence, conversation results, and root progress
/// cross one storage acknowledgement before another effect or provider request.
/// Preparation is pure with respect to work state; claim sync precedes dispatch.
/// HTTP, log, and repeated delegated effects retain the ordinary dispatcher
/// capabilities and bounds. Interrupted claims require explicit recovery.
///
/// # Errors
/// Returns preparation, claim, provider, or settlement errors; claimed interrupted
/// work remains blocked and is never automatically retried.
pub fn execute_admitted(
    config: &RuntimeConfig,
    submission_id: smith::id::EntryId,
) -> Result<smith_core::agent::TurnOutcome> {
    let storage = std::sync::Arc::new(crate::storage::StorageWorker::start(
        config.session_path.clone(),
    ));
    execute_on_storage(config, submission_id, &storage, &mut |_| {})
}

/// Admit and execute one foreground prompt through the durable runtime.
///
/// Existing pending work rejects foreground execution before admission;
/// an accepted prompt remains inspectable if preparation or execution fails.
///
/// # Errors
/// Returns session-access, admission, preparation, execution, or settlement faults.
pub fn execute_prompt(
    config: &RuntimeConfig,
    input: &str,
) -> Result<smith_core::agent::TurnOutcome> {
    let storage = std::sync::Arc::new(crate::storage::StorageWorker::start(
        config.session_path.clone(),
    ));
    storage
        .open_for_execution(Config::default_valid())
        .map_err(execution_access_error)?;
    let receipt = storage.admit(
        smith::message::Message::with_text(smith::message::Role::User, input),
        None,
    )?;
    execute_on_storage(config, receipt.submission_id, &storage, &mut |_| {})
}

pub(crate) fn execute_on_storage(
    config: &RuntimeConfig,
    submission_id: smith::id::EntryId,
    storage: &std::sync::Arc<crate::storage::StorageWorker>,
    observe: &mut dyn FnMut(&smith::stream::StreamEvent),
) -> Result<smith_core::agent::TurnOutcome> {
    let control = config
        .plugin_control_path
        .clone()
        .map(ReloadControl::bind_at_path)
        .transpose()?;
    let dispatcher = tools_dispatcher(config, control);
    let (stream, records, mut dispatcher) = provider_stream(config, dispatcher)?;
    // Loading and publication failures leave queued work unclaimed.
    let _definitions = smith_core::tools::ToolDispatcher::begin_provider_round(&mut dispatcher)?;
    let session = storage.claim(submission_id)?;
    let append = std::sync::Arc::clone(storage);
    let completion = std::sync::Arc::clone(storage);
    let mut tools =
        ToolSession::with_persist(config.workdir.clone(), session, move |entry, bytes| {
            append.append(smith_core::session::EntryFrame {
                id: entry.id,
                parent: entry.parent,
                timestamp_ms: entry.timestamp_ms,
                kind: entry.kind,
                content: bytes.to_vec(),
            })
        })
        .with_completion_boundary(submission_id, move |command| {
            completion.commit_completion(command)
        });
    tools.set_dispatcher(Box::new(dispatcher));
    let mut agent = Agent::with_provider_records(stream, tools, config.provider.model(), records);
    storage.register_cancel(submission_id, agent.cancel_handle())?;
    let result = agent.run_admitted_phased(
        submission_id,
        |command| storage.settle_execution(command),
        observe,
        &mut |phase| storage.set_execution_phase(submission_id, phase),
    );
    storage.unregister_cancel(submission_id)?;
    result
}

fn tools_dispatcher(
    config: &RuntimeConfig,
    control: Option<ReloadControl>,
) -> crate::wasm::RuntimeToolsDispatcher {
    let dispatcher = runtime_tools_dispatcher(
        &config.workdir,
        AuthStore::at(&config.auth_dir),
        config.coding_tools_enabled,
        control,
    );
    match &config.plugin_registry_dir {
        Some(root) => dispatcher.with_package_registry(PackageRegistry::at(root.clone())),
        None => dispatcher,
    }
    .with_tool_policy(config.tool_policy.clone())
    .with_composition_grants(config.composition_grants.clone())
}

fn provider_stream(
    config: &RuntimeConfig,
    dispatcher: crate::wasm::RuntimeToolsDispatcher,
) -> Result<(
    StreamFn,
    Option<smith::provider::RecordDrain>,
    crate::wasm::RuntimeToolsDispatcher,
)> {
    Ok(match &config.provider {
        RuntimeProvider::Mock(script) => (crate::mock_stream(script.clone()), None, dispatcher),
        provider => {
            let (sink, drain) = smith::provider::record_channel();
            let connection = resolve_connection(
                provider,
                config.api_key.clone(),
                &AuthStore::at(&config.auth_dir),
                config.catalog_snapshot.as_ref(),
                sink,
                config.provider_settings,
            )?;
            let (dispatcher, stream) = dispatcher.with_protocol(connection);
            (stream, Some(drain), dispatcher)
        }
    })
}

/// Reject a catalog model that has no explicit binding to this provider implementation.
///
/// # Errors
///
/// Returns a configuration error before credentials or network dispatch when
/// the model is unknown or belongs to another protocol connection.
pub fn validate_catalog_model(catalog: &Catalog, provider: &RuntimeProvider) -> Result<()> {
    if !provider.requires_catalog_validation() {
        return Ok(());
    }
    let model = provider.model();
    catalog
        .model_for_provider(provider.vendor_kind(), model)
        .map(|_| ())
}

fn resolve_connection(
    provider: &RuntimeProvider,
    api_key: Option<String>,
    store: &AuthStore,
    catalog_snapshot: Option<&ModelCatalogSnapshot>,
    records: RecordSink,
    settings: smith::provider::ProviderSettingsRecord,
) -> Result<ProtocolConnectionConfig> {
    let (route, model) = protocol_connection_route(provider, api_key)?;
    let mut connection = protocol_connection_config(
        route,
        store,
        records,
        protocol_catalog_snapshot(catalog_snapshot, provider.vendor_kind(), model)?,
    );
    if !settings.include_usage
        && !matches!(connection.protocol, ProtocolComponent::OpenAiCompatible)
    {
        return Err(SmithError::Config {
            field: "include_usage".into(),
            message: "selected protocol does not support disabling usage".into(),
        });
    }
    connection.settings.include_usage = settings.include_usage;
    connection.settings.provenance = match settings.provenance {
        smith::provider::ProviderSettingsProvenance::BuiltIn => SettingsProvenance::BuiltIn,
        smith::provider::ProviderSettingsProvenance::User => SettingsProvenance::User,
        smith::provider::ProviderSettingsProvenance::TrustedProject => {
            SettingsProvenance::TrustedProject
        }
        smith::provider::ProviderSettingsProvenance::Explicit => SettingsProvenance::Explicit,
    };
    Ok(connection)
}

struct ProtocolConnectionRoute {
    connection_id: &'static str,
    protocol: ProtocolComponent,
    artifact: Option<PathBuf>,
    endpoint: String,
    template_url: &'static str,
    credential_header: &'static str,
    credential_prefix: &'static str,
    static_headers: &'static [(&'static str, &'static str)],
    connection: ProtocolConnection,
    request_path: String,
    credential: crate::protocol::ProtocolCredential,
}

fn subscription_route(
    expected: ProviderKind,
    credential: &crate::oauth::source::SubscriptionCredential,
    api_key: Option<&str>,
) -> Result<ProtocolConnectionRoute> {
    let actual = match credential.provider() {
        crate::oauth::login::SubscriptionProvider::OpenAi => ProviderKind::OpenAiCompatible,
        crate::oauth::login::SubscriptionProvider::Anthropic => ProviderKind::Anthropic,
        crate::oauth::login::SubscriptionProvider::Google => ProviderKind::Google,
    };
    if actual != expected {
        return Err(SmithError::Config {
            field: "provider".into(),
            message: "subscription provider/profile namespace mismatch".into(),
        });
    }
    if api_key.is_some() {
        return Err(SmithError::Config {
            field: "provider".into(),
            message: "subscription cannot accept an API-key override".into(),
        });
    }
    if credential.provider() == crate::oauth::login::SubscriptionProvider::Google {
        return Ok(ProtocolConnectionRoute {
            connection_id: "google-gemini-cli-plan",
            protocol: ProtocolComponent::Google,
            artifact: None,
            endpoint: credential.endpoint().into(),
            template_url: "https://protocol.invalid/code-assist",
            credential_header: "Authorization",
            credential_prefix: "Bearer ",
            static_headers: &[],
            connection: ProtocolConnection::Api,
            request_path: "/v1internal:streamGenerateContent?alt=sse".into(),
            credential: crate::protocol::ProtocolCredential::Subscription(credential.clone()),
        });
    }
    if credential.provider() == crate::oauth::login::SubscriptionProvider::Anthropic {
        return Ok(ProtocolConnectionRoute {
            connection_id: "anthropic-claude-plan",
            protocol: ProtocolComponent::Anthropic,
            artifact: None,
            endpoint: credential.endpoint().into(),
            template_url: "https://protocol.invalid/messages",
            credential_header: "Authorization",
            credential_prefix: "Bearer ",
            static_headers: &[
                ("anthropic-version", "2023-06-01"),
                ("anthropic-beta", "claude-code-20250219,oauth-2025-04-20"),
                ("anthropic-dangerous-direct-browser-access", "true"),
                ("user-agent", "claude-cli/2.1.280"),
                ("x-app", "cli"),
            ],
            connection: ProtocolConnection::Api,
            request_path: "/v1/messages".into(),
            credential: crate::protocol::ProtocolCredential::Subscription(credential.clone()),
        });
    }
    Ok(ProtocolConnectionRoute {
        connection_id: "openai-chatgpt-plan",
        protocol: ProtocolComponent::OpenAiResponses,
        artifact: None,
        endpoint: credential.endpoint().to_string(),
        template_url: "https://protocol.invalid/responses",
        credential_header: "Authorization",
        credential_prefix: "Bearer ",
        static_headers: &[],
        connection: ProtocolConnection::Api,
        request_path: "/v1/responses".into(),
        credential: crate::protocol::ProtocolCredential::Subscription(credential.clone()),
    })
}

fn protocol_connection_route(
    provider: &RuntimeProvider,
    api_key: Option<String>,
) -> Result<(ProtocolConnectionRoute, &str)> {
    let route = match provider {
        RuntimeProvider::Mock(_) => {
            return Err(smith::error::SmithError::Config {
                field: "provider".to_string(),
                message: "mock provider has no protocol connection".to_string(),
            });
        }
        RuntimeProvider::OpenAiCompatible { base_url, model: _ } => {
            let (endpoint, request_path) = openai_connection(base_url)?;
            ProtocolConnectionRoute {
                connection_id: "openai-compatible-api",
                protocol: ProtocolComponent::OpenAiCompatible,
                artifact: None,
                endpoint,
                template_url: "https://protocol.invalid/chat/completions",
                credential_header: "Authorization",
                credential_prefix: "Bearer ",
                static_headers: &[],
                connection: ProtocolConnection::Api,
                request_path,
                credential: credential_reference(
                    api_key,
                    CredentialKey::Provider(ProviderKind::OpenAiCompatible),
                )
                .into(),
            }
        }
        RuntimeProvider::OpenAiChatGptPlan { credential, .. }
        | RuntimeProvider::GoogleGeminiCliPlan { credential, .. }
        | RuntimeProvider::AnthropicClaudePlan { credential, .. } => {
            subscription_route(provider.vendor_kind(), credential, api_key.as_deref())?
        }
        RuntimeProvider::Anthropic { base_url, model: _ } => ProtocolConnectionRoute {
            connection_id: "anthropic-api",
            protocol: ProtocolComponent::Anthropic,
            artifact: None,
            endpoint: base_url.clone(),
            template_url: "https://protocol.invalid/messages",
            credential_header: "x-api-key",
            credential_prefix: "",
            static_headers: &[("anthropic-version", "2023-06-01")],
            connection: ProtocolConnection::Api,
            request_path: "/v1/messages".to_string(),
            credential: credential_reference(
                api_key,
                CredentialKey::Provider(ProviderKind::Anthropic),
            )
            .into(),
        },
        RuntimeProvider::Google { base_url, model } => ProtocolConnectionRoute {
            connection_id: "google-api",
            protocol: ProtocolComponent::Google,
            artifact: None,
            endpoint: base_url.clone(),
            template_url: "https://protocol.invalid/models/streamGenerateContent",
            credential_header: "x-goog-api-key",
            credential_prefix: "",
            static_headers: &[],
            connection: ProtocolConnection::Api,
            request_path: format!("/v1beta/models/{model}:streamGenerateContent?alt=sse"),
            credential: credential_reference(
                api_key,
                CredentialKey::Provider(ProviderKind::Google),
            )
            .into(),
        },
        RuntimeProvider::Zai {
            artifact,
            base_url,
            connection,
            model: _,
        } => ProtocolConnectionRoute {
            connection_id: match connection {
                ProtocolConnection::Api => "zai-api",
                ProtocolConnection::CodingPlan => "zai-coding-plan",
            },
            protocol: ProtocolComponent::OpenAiCompatible,
            artifact: artifact.clone(),
            endpoint: base_url.clone(),
            template_url: "https://protocol.invalid/chat/completions",
            credential_header: "Authorization",
            credential_prefix: "Bearer ",
            static_headers: &[],
            connection: *connection,
            request_path: connection.request_path().to_string(),
            credential: credential_reference(
                api_key,
                match connection {
                    ProtocolConnection::Api => CredentialKey::Provider(ProviderKind::Zai),
                    ProtocolConnection::CodingPlan => CredentialKey::ZaiCodingPlan,
                },
            )
            .into(),
        },
    };
    Ok((route, provider.model()))
}

fn protocol_connection_config(
    route: ProtocolConnectionRoute,
    store: &AuthStore,
    records: RecordSink,
    catalog: CatalogSnapshot,
) -> ProtocolConnectionConfig {
    let executor = match &route.credential {
        crate::protocol::ProtocolCredential::Subscription(_) => {
            crate::http::subscription_executor()
        }
        crate::protocol::ProtocolCredential::ApiKey(_) => crate::http::default_executor(),
    };
    let subscription = matches!(
        &route.credential,
        crate::protocol::ProtocolCredential::Subscription(_)
    ) && matches!(
        route.protocol,
        ProtocolComponent::Anthropic | ProtocolComponent::Google
    );
    ProtocolConnectionConfig {
        connection_id: route.connection_id,
        protocol: route.protocol,
        artifact: route.artifact,
        endpoint: route.endpoint,
        template_url: route.template_url,
        credential_header: route.credential_header,
        credential_prefix: route.credential_prefix,
        static_headers: route.static_headers,
        connection: route.connection,
        request_path: route.request_path,
        credential: route.credential,
        auth_store: store.clone(),
        executor,
        records,
        intent_admission_timeout: std::time::Duration::from_secs(30),
        settings: protocol_settings(subscription),
        catalog,
    }
}

fn openai_connection(base_url: &str) -> Result<(String, String)> {
    let scheme_end = base_url
        .find("://")
        .ok_or_else(|| smith::error::SmithError::Config {
            field: "provider.base_url".to_string(),
            message: "OpenAI-compatible endpoint requires an HTTP scheme".to_string(),
        })?
        + 3;
    let path_at = base_url[scheme_end..]
        .find('/')
        .map_or(base_url.len(), |at| scheme_end + at);
    let endpoint = base_url[..path_at].trim_end_matches('/').to_string();
    let base_path = base_url[path_at..].trim_end_matches('/');
    Ok((endpoint, format!("{base_path}/chat/completions")))
}

const fn protocol_settings(subscription: bool) -> ProviderSettings {
    ProviderSettings {
        include_usage: true,
        subscription,
        provenance: SettingsProvenance::BuiltIn,
    }
}

fn protocol_catalog_snapshot(
    snapshot: Option<&ModelCatalogSnapshot>,
    provider: ProviderKind,
    model: &str,
) -> Result<CatalogSnapshot> {
    let (generation, source, model) = match snapshot {
        None => (
            0,
            CatalogSource::Bundled,
            CatalogModel {
                id: model.to_string(),
                capabilities: ModelCapabilities {
                    output_tokens_max: u64::MAX,
                    tool_use: true,
                    thinking: false,
                },
            },
        ),
        Some(snapshot) => {
            let entry = snapshot.catalog.model_for_provider(provider, model)?;
            (
                snapshot.generation,
                catalog_source(snapshot.provenance),
                catalog_model(&entry.capabilities, entry.id.clone()),
            )
        }
    };
    Ok(CatalogSnapshot {
        generation,
        source,
        models: vec![model],
    })
}

const fn catalog_source(provenance: CatalogProvenance) -> CatalogSource {
    match provenance {
        CatalogProvenance::Bundled => CatalogSource::Bundled,
        CatalogProvenance::Cache => CatalogSource::Cache,
        CatalogProvenance::ModelsDev => CatalogSource::ModelsDev,
    }
}

const fn catalog_model(capabilities: &CatalogModelCapabilities, id: String) -> CatalogModel {
    CatalogModel {
        id,
        capabilities: ModelCapabilities {
            output_tokens_max: capabilities.output_tokens_max,
            tool_use: capabilities.tool_use,
            thinking: capabilities.thinking,
        },
    }
}

fn credential_reference(explicit: Option<String>, key: CredentialKey) -> CredentialReference {
    explicit.map_or_else(
        || CredentialReference::store_or_env(key),
        CredentialReference::explicit,
    )
}

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

    #[test]
    #[cfg(unix)]
    fn foreground_preparation_failure_retains_accepted_input_for_explicit_execution() {
        let directory = std::env::temp_dir().join(format!(
            "smith-foreground-preparation-{}",
            smith::id::SessionId::new()
        ));
        std::fs::create_dir(&directory).unwrap();
        let blocker = directory.join("occupied");
        std::fs::write(&blocker, b"occupied").unwrap();
        let mut config = RuntimeConfig::mock(&directory, vec![mock_text_reply("settled")]);
        config.plugin_control_path = Some(blocker);
        assert!(execute_prompt(&config, "accepted once").is_err());
        let limit = Config::default_valid().frame_bytes_max;
        let reader = smith_core::store::SessionReader::open(&config.session_path).unwrap();
        let mut admitted = None;
        reader
            .scan(limit, |frame| {
                if let smith_core::frame::Frame::Admission { entry, .. } = frame {
                    assert!(admitted.is_none(), "one accepted input only");
                    admitted = Some(entry.id);
                }
                Ok(())
            })
            .unwrap();
        let id = admitted.unwrap();
        assert_eq!(
            reader.work_status(id, limit).unwrap(),
            Some(smith_core::store::WorkStatus::Queued)
        );
        assert!(execute_prompt(&config, "must not be accepted").is_err());
        config.plugin_control_path = None;
        assert_eq!(execute_admitted(&config, id).unwrap().text, "settled");
        let reader = smith_core::store::SessionReader::open(&config.session_path).unwrap();
        assert_eq!(
            reader.work_status(id, limit).unwrap(),
            Some(smith_core::store::WorkStatus::Terminal(Some(
                smith::stream::StopReason::EndTurn
            )))
        );
        let session = reader.selected_session(limit).unwrap();
        let entries = session.active_branch();
        assert_eq!(entries.entries().len(), 3);
        let messages = entries
            .entries()
            .iter()
            .filter(|entry| matches!(entry.kind, smith_core::session::EntryKind::Message { .. }))
            .count();
        assert_eq!(
            messages, 2,
            "accepted user input plus terminal assistant output"
        );
        reader.verify_full(limit).unwrap();
        drop(reader);
        std::fs::remove_dir_all(directory).unwrap();
    }

    #[test]
    fn worker_rejects_oversized_turn_without_advancing_live_or_durable_state() {
        let dir =
            std::env::temp_dir().join(format!("smith_harness_oversized_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let cfg = RuntimeConfig::mock(&dir, vec![mock_text_reply("accepted")]);
        let mut agent = build_agent(&cfg).unwrap();
        let oversized = "x".repeat(Config::default_valid().frame_bytes_max + 1);
        assert_eq!(
            agent.run_turn(&oversized).unwrap_err().code(),
            "FRAME_TOO_LARGE"
        );
        assert!(agent.session().selected_id().is_none());
        assert_eq!(agent.run_turn("small").unwrap().text, "accepted");
        drop(agent);
        let reopened =
            smith_core::store::open_session(&cfg.session_path, Config::default_valid()).unwrap();
        assert_eq!(reopened.session.active_branch().entries().len(), 2);
        drop(reopened);
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn mock_runtime_completes_and_persists_a_turn() {
        let dir = std::env::temp_dir().join(format!("smith_harness_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap_or(());
        let config = RuntimeConfig::mock(dir.join("work"), vec![mock_text_reply("assembled")]);
        let mut agent = build_agent(&config).unwrap();
        let outcome = agent.run_turn("hello").unwrap();
        assert_eq!(outcome.text, "assembled");
        drop(agent);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn real_providers_resolve_credentials_only_at_the_authorized_effect_boundary() {
        let dir = std::env::temp_dir().join(format!("smith_harness_auth_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap_or(());
        // The credential check reads the environment; a missing variable
        // is the normal fresh-runner state, so the test does not mutate it.
        let config = RuntimeConfig {
            provider: RuntimeProvider::OpenAiCompatible {
                base_url: "https://example.test/v1".to_string(),
                model: "gpt-5.1".to_string(),
            },
            api_key: None,
            ..RuntimeConfig::mock(&dir, Vec::new())
        };
        let mut agent = build_agent(&config)
            .unwrap_or_else(|error| panic!("assembly must not resolve credentials: {error}"));
        let error = agent
            .run_turn("hello")
            .err()
            .unwrap_or_else(|| panic!("missing credential must fail the request"));
        assert_eq!(error.code(), "PROVIDER_AUTH");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn stored_credential_resolves_without_network() {
        let home = std::env::temp_dir().join(format!("smith_harness_store_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&home);
        let store = AuthStore::at(&home);
        store
            .save(smith_ai::models::ProviderKind::Anthropic, "sk-from-store")
            .unwrap_or(());

        assert_eq!(
            CredentialReference::store_or_env(CredentialKey::Provider(ProviderKind::Anthropic))
                .resolve(&store)
                .unwrap_or_default(),
            "sk-from-store"
        );

        let _ = std::fs::remove_dir_all(&home);
    }

    #[test]
    fn real_provider_defaults_base_url_per_vendor() {
        let anthropic = RuntimeProvider::real(
            smith_ai::models::ProviderKind::Anthropic,
            None,
            "m".to_string(),
        );
        let RuntimeProvider::Anthropic { base_url, model } = anthropic else {
            unreachable!("anthropic kind builds the anthropic endpoint");
        };
        assert_eq!(base_url, "https://api.anthropic.com");
        assert_eq!(model, "m");

        let overridden = RuntimeProvider::real(
            smith_ai::models::ProviderKind::Google,
            Some("https://proxy.test".to_string()),
            "m".to_string(),
        );
        let RuntimeProvider::Google { base_url, .. } = overridden else {
            unreachable!("google kind builds the google endpoint");
        };
        assert_eq!(base_url, "https://proxy.test");
    }

    #[test]
    fn google_default_route_uses_single_version_prefix() {
        let provider =
            RuntimeProvider::real(ProviderKind::Google, None, "gemini-2.5-flash".to_string());
        let (route, _) = protocol_connection_route(&provider, None).unwrap();

        assert_eq!(route.credential_header, "x-goog-api-key");
        assert_eq!(
            format!("{}{}", route.endpoint, route.request_path),
            "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
        );
    }

    #[test]
    fn connection_configuration_preserves_provider_authority_and_billing_mapping() {
        let directory = std::env::temp_dir().join(format!(
            "smith_runtime_connection_mapping_{}",
            smith::id::SessionId::new()
        ));
        std::fs::create_dir(&directory).unwrap();
        let store = AuthStore::at(&directory);
        store
            .save(ProviderKind::OpenAiCompatible, "openai-secret")
            .unwrap();
        store
            .save(ProviderKind::Anthropic, "anthropic-secret")
            .unwrap();
        store.save(ProviderKind::Google, "google-secret").unwrap();
        store.save(ProviderKind::Zai, "zai-api-secret").unwrap();
        store
            .save(CredentialKey::ZaiCodingPlan, "zai-plan-secret")
            .unwrap();
        let configure = |provider: &RuntimeProvider| {
            let (route, model) = protocol_connection_route(provider, None).unwrap();
            let (records, _) = smith::provider::record_channel();
            protocol_connection_config(
                route,
                &store,
                records,
                protocol_catalog_snapshot(None, provider.vendor_kind(), model).unwrap(),
            )
        };

        let openai = configure(&RuntimeProvider::OpenAiCompatible {
            base_url: "https://openai.test/v1".to_string(),
            model: "model".to_string(),
        });
        assert_eq!(openai.connection_id, "openai-compatible-api");
        assert_eq!(openai.connection, ProtocolConnection::Api);
        assert_eq!(openai.endpoint, "https://openai.test");
        assert_eq!(openai.request_path, "/v1/chat/completions");
        assert_eq!(openai.credential_header, "Authorization");
        assert_eq!(
            openai
                .credential
                .resolve(&store, &openai.endpoint, &smith::tool::CancelHandle::new())
                .unwrap()
                .secrets()[0],
            "openai-secret"
        );

        let anthropic = configure(&RuntimeProvider::Anthropic {
            base_url: "https://anthropic.test".to_string(),
            model: "model".to_string(),
        });
        assert_eq!(anthropic.connection_id, "anthropic-api");
        assert_eq!(anthropic.connection, ProtocolConnection::Api);
        assert_eq!(anthropic.request_path, "/v1/messages");
        assert_eq!(anthropic.credential_header, "x-api-key");
        assert_eq!(
            anthropic.static_headers,
            &[("anthropic-version", "2023-06-01")]
        );
        assert_eq!(
            anthropic
                .credential
                .resolve(
                    &store,
                    &anthropic.endpoint,
                    &smith::tool::CancelHandle::new()
                )
                .unwrap()
                .secrets()[0],
            "anthropic-secret"
        );

        let google = configure(&RuntimeProvider::Google {
            base_url: "https://google.test".to_string(),
            model: "model".to_string(),
        });
        assert_eq!(google.connection_id, "google-api");
        assert_eq!(google.connection, ProtocolConnection::Api);
        assert_eq!(
            google.request_path,
            "/v1beta/models/model:streamGenerateContent?alt=sse"
        );
        assert_eq!(google.credential_header, "x-goog-api-key");
        assert_eq!(
            google
                .credential
                .resolve(&store, &google.endpoint, &smith::tool::CancelHandle::new())
                .unwrap()
                .secrets()[0],
            "google-secret"
        );

        for (connection, connection_id, secret) in [
            (ProtocolConnection::Api, "zai-api", "zai-api-secret"),
            (
                ProtocolConnection::CodingPlan,
                "zai-coding-plan",
                "zai-plan-secret",
            ),
        ] {
            let zai = configure(&RuntimeProvider::Zai {
                artifact: None,
                base_url: "https://zai.test".to_string(),
                connection,
                model: "model".to_string(),
            });
            assert_eq!(zai.connection_id, connection_id);
            assert_eq!(zai.connection, connection);
            assert_eq!(zai.request_path, connection.request_path());
            assert_eq!(zai.credential_header, "Authorization");
            assert_eq!(
                zai.credential
                    .resolve(&store, &zai.endpoint, &smith::tool::CancelHandle::new())
                    .unwrap()
                    .secrets()[0],
                secret
            );
        }
        std::fs::remove_dir_all(directory).unwrap();
    }
}