//! Runtime assembly: configuration to agent. //! //! 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 smith::config::Config; use smith::error::Result; use smith::provider::StreamFn; use smith_ai::auth::{AuthRegistry, Credential}; use smith_ai::models::ProviderKind; use smith_ai::transport::{VendorEndpoint, transport}; use smith_core::agent::Agent; use smith_core::store::open_session; use smith_core::tools::ToolSession; use std::path::{Path, PathBuf}; /// Which provider a runtime uses. #[derive(Clone, Debug, PartialEq, Eq)] pub enum RuntimeProvider { /// Scripted responses; `smh-mock` in the catalog. Mock(Vec>), /// OpenAI-compatible endpoint. OpenAiCompatible { /// Base URL, for example `https://api.openai.com/v1`. base_url: String, /// Model id. 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, }, } 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, .. } => model, } } const fn vendor_kind(&self) -> ProviderKind { match self { Self::Mock(_) | Self::OpenAiCompatible { .. } => ProviderKind::OpenAiCompatible, Self::Anthropic { .. } => ProviderKind::Anthropic, Self::Google { .. } => ProviderKind::Google, } } } /// 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, } impl RuntimeConfig { /// A mock runtime under `workdir` with a fresh session file. #[must_use] pub fn mock(workdir: impl Into, script: Vec>) -> Self { let workdir = workdir.into(); let session_path = workdir.join("session.smh"); Self { provider: RuntimeProvider::Mock(script), workdir, session_path, } } } /// Environment variable per provider family. const KEY_VARIABLES: [(ProviderKind, &str); 3] = [ (ProviderKind::OpenAiCompatible, "OPENAI_API_KEY"), (ProviderKind::Anthropic, "ANTHROPIC_API_KEY"), (ProviderKind::Google, "GEMINI_API_KEY"), ]; /// 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 { let smith_config = Config::default_valid(); let opened = open_session(Path::new(&config.session_path), smith_config)?; let tools = ToolSession::with_session(config.workdir.clone(), opened.session, opened.writer); let stream = resolve_stream(&config.provider)?; Ok(Agent::new( stream, tools, config.provider.model().to_string(), )) } fn resolve_stream(provider: &RuntimeProvider) -> Result { match provider { RuntimeProvider::Mock(script) => { let (stream, _seen) = crate::mock_stream(script.clone()); Ok(stream) } RuntimeProvider::OpenAiCompatible { base_url, model } | RuntimeProvider::Anthropic { base_url, model } | RuntimeProvider::Google { base_url, model } => { let kind = provider.vendor_kind(); let registry = AuthRegistry::new(); let variable = KEY_VARIABLES .iter() .find(|(candidate, _)| *candidate == kind) .map(|(_, variable)| (*variable).to_string()) .unwrap_or_default(); registry.set(format!("{kind:?}"), Credential::from_env(variable)); let credential = registry.get(&format!("{kind:?}")).ok_or_else(|| { smith::error::SmithError::Provider { fault: smith::error::ProviderFault::Authentication { message: format!("no credential for {kind:?}"), }, } })?; let api_key = credential.secret()?; Ok(transport(VendorEndpoint { kind, base_url: base_url.clone(), model: model.clone(), api_key, })) } } } #[cfg(test)] #[expect( clippy::unwrap_used, reason = "runtime tests assert on assembled agents" )] mod tests { use super::*; use crate::mock_text_reply; #[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_fail_fast_without_credentials() { 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(), }, workdir: dir.clone(), session_path: dir.join("s.smh"), }; let Err(err) = build_agent(&config) else { unreachable!("no credential must fail assembly"); }; assert_eq!(err.code(), "PROVIDER_AUTH"); let _ = std::fs::remove_dir_all(&dir); } }