Decouple local provider setup from codex-core (#65234)

## What changed

Have the TUI and `codex exec` pass the selected provider, optional model,
and HTTP client factory to shared OSS setup. Validate the provider's
`base_url` there and connect to Ollama or LM Studio using that URL and
factory. Return a configuration error when Ollama's URL is missing.

Remove the runtime dependency on `codex-core` from the OSS utilities
and both provider crates. Enable the existing Rustls key exchange
preference and vendored OpenSSL for musl builds directly in the provider
crates.

## Testing

Add coverage for the error returned by each provider when `base_url` is
missing. Extend the Ollama client reuse test to check readiness for an
explicitly selected, already installed model.

GitOrigin-RevId: 747ed51c6fcfa2a0ffc61ba5aa8ea4d033450241
This commit is contained in:
jif
2026-12-02 11:36:47 +00:00
committed by copyberry
parent 6b36f44a93
commit a7e4b42b4a
11 changed files with 172 additions and 138 deletions
+7 -3
View File
@@ -4161,7 +4161,8 @@ version = "0.0.0"
dependencies = [
"codex-core",
"codex-http-client",
"codex-model-provider-info",
"openssl-sys",
"rustls",
"serde_json",
"tokio",
"tracing",
@@ -4657,10 +4658,11 @@ dependencies = [
"bytes",
"codex-core",
"codex-http-client",
"codex-model-provider-info",
"futures",
"memchr",
"openssl-sys",
"pretty_assertions",
"rustls",
"semver",
"serde_json",
"tokio",
@@ -5763,10 +5765,12 @@ dependencies = [
name = "codex-utils-oss"
version = "0.0.0"
dependencies = [
"codex-core",
"codex-http-client",
"codex-lmstudio",
"codex-model-provider-info",
"codex-ollama",
"pretty_assertions",
"tokio",
]
[[package]]
+8 -3
View File
@@ -948,9 +948,14 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
));
}
};
ensure_oss_provider_ready(provider_id, &config)
.await
.map_err(|e| anyhow::anyhow!("OSS setup failed: {e}"))?;
ensure_oss_provider_ready(
provider_id,
config.model_providers.get(provider_id),
config.model.as_deref(),
config.http_client_factory(),
)
.await
.map_err(|e| anyhow::anyhow!("OSS setup failed: {e}"))?;
}
let default_cwd = config.cwd.to_path_buf();
+13 -3
View File
@@ -9,17 +9,27 @@ name = "codex_lmstudio"
path = "src/lib.rs"
doctest = false
[package.metadata.cargo-shear]
# Enable the existing key exchange preference for HTTPS with a custom CA.
ignored = ["rustls"]
[dependencies]
codex-core = { path = "../core" }
codex-http-client = { workspace = true }
codex-model-provider-info = { path = "../model-provider-info" }
serde_json = "1"
rustls = { workspace = true, features = ["prefer-post-quantum"] }
serde_json = { workspace = true, features = ["arbitrary_precision"] }
tokio = { version = "1", features = ["rt"] }
tracing = { version = "0.1.44", features = ["log"] }
which = "8.0"
# Build OpenSSL from source for standalone musl builds.
[target.x86_64-unknown-linux-musl.dependencies]
openssl-sys = { workspace = true, features = ["vendored"] }
[target.aarch64-unknown-linux-musl.dependencies]
openssl-sys = { workspace = true, features = ["vendored"] }
[dev-dependencies]
codex-core = { workspace = true }
wiremock = "0.6"
tokio = { version = "1", features = ["full"] }
+13 -21
View File
@@ -1,7 +1,6 @@
use codex_core::config::Config;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::RouteAwareClientPool;
use codex_model_provider_info::LMSTUDIO_OSS_PROVIDER_ID;
use std::io;
use std::path::Path;
use std::time::Duration;
@@ -16,25 +15,13 @@ const LMSTUDIO_CONNECTION_ERROR: &str = "LM Studio is not responding. Install fr
const LMSTUDIO_CONNECTION_TIMEOUT: Duration = Duration::from_secs(5);
impl LMStudioClient {
pub async fn try_from_provider(config: &Config) -> std::io::Result<Self> {
let provider = config
.model_providers
.get(LMSTUDIO_OSS_PROVIDER_ID)
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("Built-in provider {LMSTUDIO_OSS_PROVIDER_ID} not found",),
)
})?;
let base_url = provider.base_url.as_ref().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
"oss provider must have a base_url",
)
})?;
/// Connect to the configured LM Studio endpoint and verify it is reachable.
pub async fn connect(
base_url: &str,
http_client_factory: HttpClientFactory,
) -> std::io::Result<Self> {
let client = RouteAwareClientPool::with_connect_timeout(
config.http_client_factory(),
http_client_factory,
ClientRouteClass::Other,
LMSTUDIO_CONNECTION_TIMEOUT,
);
@@ -244,7 +231,12 @@ mod tests {
.mount(&server)
.await;
let client = client_from_host_root(server.uri(), LMSTUDIO_CONNECTION_TIMEOUT);
let client = LMStudioClient::connect(
&server.uri(),
HttpClientFactory::new(codex_http_client::OutboundProxyPolicy::ReqwestDefault),
)
.await
.expect("connect to configured endpoint");
let models = client.fetch_models().await.expect("fetch models");
assert!(models.contains(&"openai/gpt-oss-20b".to_string()));
}
+8 -7
View File
@@ -1,7 +1,7 @@
mod client;
pub use client::LMStudioClient;
use codex_core::config::Config;
use codex_http_client::HttpClientFactory;
/// Default OSS model to use when `--oss` is passed without an explicit `-m`.
pub const DEFAULT_OSS_MODEL: &str = "openai/gpt-oss-20b";
@@ -10,14 +10,15 @@ pub const DEFAULT_OSS_MODEL: &str = "openai/gpt-oss-20b";
///
/// - Ensures a local LM Studio server is reachable.
/// - Checks if the model exists locally and downloads it if missing.
pub async fn ensure_oss_ready(config: &Config) -> std::io::Result<()> {
let model = match config.model.as_ref() {
Some(model) => model,
None => DEFAULT_OSS_MODEL,
};
pub async fn ensure_oss_ready(
model: Option<&str>,
base_url: &str,
http_client_factory: HttpClientFactory,
) -> std::io::Result<()> {
let model = model.unwrap_or(DEFAULT_OSS_MODEL);
// Verify local LM Studio is reachable.
let lmstudio_client = LMStudioClient::try_from_provider(config).await?;
let lmstudio_client = LMStudioClient::connect(base_url, http_client_factory).await?;
match lmstudio_client.fetch_models().await {
Ok(models) => {
+15 -4
View File
@@ -12,16 +12,19 @@ doctest = false
[lints]
workspace = true
[package.metadata.cargo-shear]
# Enable the existing key exchange preference for HTTPS with a custom CA.
ignored = ["rustls"]
[dependencies]
async-stream = { workspace = true }
bytes = { workspace = true }
codex-core = { workspace = true }
codex-http-client = { workspace = true }
codex-model-provider-info = { workspace = true }
futures = { workspace = true }
memchr = { workspace = true }
rustls = { workspace = true, features = ["prefer-post-quantum"] }
semver = { workspace = true }
serde_json = { workspace = true }
serde_json = { workspace = true, features = ["arbitrary_precision"] }
tokio = { workspace = true, features = [
"io-std",
"macros",
@@ -30,8 +33,16 @@ tokio = { workspace = true, features = [
"signal",
] }
tracing = { workspace = true, features = ["log"] }
wiremock = { workspace = true }
# Build OpenSSL from source for standalone musl builds.
[target.x86_64-unknown-linux-musl.dependencies]
openssl-sys = { workspace = true, features = ["vendored"] }
[target.aarch64-unknown-linux-musl.dependencies]
openssl-sys = { workspace = true, features = ["vendored"] }
[dev-dependencies]
codex-core = { workspace = true }
assert_matches = { workspace = true }
pretty_assertions = { workspace = true }
wiremock = { workspace = true }
+22 -63
View File
@@ -12,19 +12,12 @@ use crate::pull::PullEvent;
use crate::pull::PullProgressReporter;
use crate::url::base_url_to_host_root;
use crate::url::is_openai_compatible_base_url;
use codex_core::config::Config;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
#[cfg(test)]
use codex_http_client::OutboundProxyPolicy;
use codex_http_client::RouteAwareClientPool;
use codex_http_client::RouteAwareRequestError;
use codex_model_provider_info::ModelProviderInfo;
use codex_model_provider_info::OLLAMA_OSS_PROVIDER_ID;
#[cfg(test)]
use codex_model_provider_info::WireApi;
#[cfg(test)]
use codex_model_provider_info::create_oss_provider_with_base_url;
const OLLAMA_CONNECTION_ERROR: &str = "No running Ollama server detected. Start it with: `ollama serve` (after installing). Install instructions: https://github.com/ollama/ollama?tab=readme-ov-file#ollama";
const OLLAMA_CONNECTION_TIMEOUT: Duration = Duration::from_secs(5);
@@ -37,46 +30,11 @@ pub struct OllamaClient {
}
impl OllamaClient {
/// Construct a client for the built‑in open‑source ("oss") model provider
/// and verify that a local Ollama server is reachable. If no server is
/// detected, returns an error with helpful installation/run instructions.
pub async fn try_from_oss_provider(config: &Config) -> io::Result<Self> {
// Note that we must look up the provider from the Config to ensure that
// any overrides the user has in their config.toml are taken into
// account.
let provider = config
.model_providers
.get(OLLAMA_OSS_PROVIDER_ID)
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("Built-in provider {OLLAMA_OSS_PROVIDER_ID} not found",),
)
})?;
Self::try_from_provider(provider, config.http_client_factory()).await
}
#[cfg(test)]
async fn try_from_provider_with_base_url(base_url: &str) -> io::Result<Self> {
let provider = create_oss_provider_with_base_url(base_url, WireApi::Responses);
Self::try_from_provider(
&provider,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.await
}
/// Build a client from a provider definition and verify the server is reachable.
pub(crate) async fn try_from_provider(
provider: &ModelProviderInfo,
/// Connect to the configured Ollama endpoint and verify it is reachable.
pub async fn connect(
base_url: &str,
http_client_factory: HttpClientFactory,
) -> io::Result<Self> {
#![expect(clippy::expect_used)]
let base_url = provider
.base_url
.as_ref()
.expect("oss provider must have a base_url");
let uses_openai_compat = is_openai_compatible_base_url(base_url);
let host_root = base_url_to_host_root(base_url);
let client = RouteAwareClientPool::with_connect_timeout(
@@ -294,6 +252,14 @@ mod tests {
use assert_matches::assert_matches;
use pretty_assertions::assert_eq;
async fn connect(base_url: &str) -> io::Result<OllamaClient> {
OllamaClient::connect(
base_url,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.await
}
// Happy-path tests using a mock HTTP server; skip if sandbox network is disabled.
#[tokio::test]
async fn test_fetch_models_happy_path() {
@@ -354,9 +320,7 @@ mod tests {
.mount(&server)
.await;
let client = OllamaClient::try_from_provider_with_base_url(server.uri().as_str())
.await
.expect("client");
let client = connect(&server.uri()).await.expect("client");
let version = client.fetch_version().await.expect("version fetch");
assert_eq!(version, Some(Version::new(0, 14, 1)));
@@ -433,10 +397,9 @@ mod tests {
.respond_with(wiremock::ResponseTemplate::new(200))
.mount(&server)
.await;
let ollama_client =
OllamaClient::try_from_provider_with_base_url(&format!("{}/v1", server.uri()))
.await
.expect("probe OpenAI compat");
let ollama_client = connect(&format!("{}/v1", server.uri()))
.await
.expect("probe OpenAI compat");
ollama_client
.probe_server()
.await
@@ -462,7 +425,7 @@ mod tests {
.mount(&server)
.await;
OllamaClient::try_from_provider_with_base_url(&format!("{}/v1", server.uri()))
connect(&format!("{}/v1", server.uri()))
.await
.expect("client should be created when probe succeeds");
}
@@ -489,9 +452,8 @@ mod tests {
.mount(&proxy)
.await;
let provider = create_oss_provider_with_base_url(base_url, WireApi::Responses);
let client = OllamaClient::try_from_provider(
&provider,
let client = OllamaClient::connect(
base_url,
HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
)
.await
@@ -563,12 +525,9 @@ mod tests {
.mount(&server)
.await;
let provider = create_oss_provider_with_base_url(&server.uri(), WireApi::Responses);
let result = OllamaClient::try_from_provider(
&provider,
HttpClientFactory::new(outbound_proxy_policy),
)
.await;
let result =
OllamaClient::connect(&server.uri(), HttpClientFactory::new(outbound_proxy_policy))
.await;
match outbound_proxy_policy {
OutboundProxyPolicy::ReqwestDefault => {
@@ -618,7 +577,7 @@ mod tests {
}
let server = wiremock::MockServer::start().await;
let err = OllamaClient::try_from_provider_with_base_url(&format!("{}/v1", server.uri()))
let err = connect(&format!("{}/v1", server.uri()))
.await
.err()
.expect("expected error");
+8 -18
View File
@@ -5,7 +5,6 @@ mod pull;
mod url;
pub use client::OllamaClient;
use codex_core::config::Config;
pub use pull::CliProgressReporter;
pub use pull::PullEvent;
pub use pull::PullProgressReporter;
@@ -19,12 +18,8 @@ pub const DEFAULT_OSS_MODEL: &str = "gpt-oss:20b";
///
/// - Ensures a local Ollama server is reachable.
/// - Checks if the model exists locally and pulls it if missing.
pub async fn ensure_oss_ready(config: &Config, client: &OllamaClient) -> std::io::Result<()> {
// Only download when the requested model is the default OSS model (or when -m is not provided).
let model = match config.model.as_ref() {
Some(model) => model,
None => DEFAULT_OSS_MODEL,
};
pub async fn ensure_oss_ready(model: Option<&str>, client: &OllamaClient) -> std::io::Result<()> {
let model = model.unwrap_or(DEFAULT_OSS_MODEL);
// If the model is not present locally, pull it.
match client.fetch_models().await {
@@ -74,9 +69,6 @@ mod tests {
use super::*;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_model_provider_info::WireApi;
use codex_model_provider_info::create_oss_provider_with_base_url;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn version_check_reuses_existing_ollama_client() {
@@ -93,7 +85,7 @@ mod tests {
.and(wiremock::matchers::path("/api/tags"))
.respond_with(
wiremock::ResponseTemplate::new(200)
.set_body_json(serde_json::json!({"models": [{"name": "gpt-oss:20b"}]})),
.set_body_json(serde_json::json!({"models": [{"name": "custom-model"}]})),
)
.expect(2)
.mount(&server)
@@ -108,9 +100,8 @@ mod tests {
.mount(&server)
.await;
let provider = create_oss_provider_with_base_url(&server.uri(), WireApi::Responses);
let client = OllamaClient::try_from_provider(
&provider,
let client = OllamaClient::connect(
&server.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.await
@@ -119,10 +110,9 @@ mod tests {
ensure_responses_supported(&client)
.await
.expect("version check should reuse the existing client");
assert_eq!(
client.fetch_models().await.expect("fetch models"),
vec!["gpt-oss:20b"]
);
ensure_oss_ready(Some("custom-model"), &client)
.await
.expect("the selected model is already installed");
server.verify().await;
}
+7 -1
View File
@@ -980,7 +980,13 @@ pub(super) async fn run_main_inner(
// Provider setup may print progress or block in an external downloader.
// Restore ordinary signal handling so Ctrl+C can interrupt that process.
crossterm::terminal::disable_raw_mode()?;
ensure_oss_provider_ready(provider_id, &config).await
ensure_oss_provider_ready(
provider_id,
config.model_providers.get(provider_id),
config.model.as_deref(),
config.http_client_factory(),
)
.await
})
.await?;
}
+5 -1
View File
@@ -8,10 +8,14 @@ license.workspace = true
workspace = true
[dependencies]
codex-core = { workspace = true }
codex-http-client = { workspace = true }
codex-lmstudio = { workspace = true }
codex-model-provider-info = { workspace = true }
codex-ollama = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt"] }
[lib]
doctest = false
+66 -14
View File
@@ -1,8 +1,10 @@
//! OSS provider utilities shared between TUI and exec.
use codex_core::config::Config;
use codex_http_client::HttpClientFactory;
use codex_model_provider_info::LMSTUDIO_OSS_PROVIDER_ID;
use codex_model_provider_info::ModelProviderInfo;
use codex_model_provider_info::OLLAMA_OSS_PROVIDER_ID;
use std::io;
/// Returns the default model for a given OSS provider.
pub fn get_default_model_for_oss_provider(provider_id: &str) -> Option<&'static str> {
@@ -16,31 +18,81 @@ pub fn get_default_model_for_oss_provider(provider_id: &str) -> Option<&'static
/// Ensures the specified OSS provider is ready (models downloaded, service reachable).
pub async fn ensure_oss_provider_ready(
provider_id: &str,
config: &Config,
) -> Result<(), std::io::Error> {
provider: Option<&ModelProviderInfo>,
model: Option<&str>,
http_client_factory: HttpClientFactory,
) -> io::Result<()> {
let base_url = || {
let provider = provider.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("Built-in provider {provider_id} not found"),
)
})?;
provider.base_url.as_deref().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
"oss provider must have a base_url",
)
})
};
let setup_error = |err: io::Error| io::Error::other(format!("OSS setup failed: {err}"));
match provider_id {
LMSTUDIO_OSS_PROVIDER_ID => {
codex_lmstudio::ensure_oss_ready(config)
.await
.map_err(|e| std::io::Error::other(format!("OSS setup failed: {e}")))?;
codex_lmstudio::ensure_oss_ready(
model,
base_url().map_err(setup_error)?,
http_client_factory,
)
.await
}
OLLAMA_OSS_PROVIDER_ID => {
let client = codex_ollama::OllamaClient::try_from_oss_provider(config).await?;
// Ollama connection and version errors are reported before model setup.
let client =
codex_ollama::OllamaClient::connect(base_url()?, http_client_factory).await?;
codex_ollama::ensure_responses_supported(&client).await?;
codex_ollama::ensure_oss_ready(config, &client)
.await
.map_err(|e| std::io::Error::other(format!("OSS setup failed: {e}")))?;
}
_ => {
// Unknown provider, skip setup
codex_ollama::ensure_oss_ready(model, &client).await
}
_ => Ok(()),
}
Ok(())
.map_err(setup_error)
}
#[cfg(test)]
mod tests {
use super::*;
use codex_http_client::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn missing_base_url_preserves_provider_errors() {
let provider = ModelProviderInfo::default();
for (provider_id, kind, message) in [
(
OLLAMA_OSS_PROVIDER_ID,
io::ErrorKind::InvalidData,
"oss provider must have a base_url",
),
(
LMSTUDIO_OSS_PROVIDER_ID,
io::ErrorKind::Other,
"OSS setup failed: oss provider must have a base_url",
),
] {
let error = ensure_oss_provider_ready(
provider_id,
Some(&provider),
/*model*/ None,
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.await
.expect_err("local provider setup requires a base URL");
assert_eq!(
(error.kind(), error.to_string()),
(kind, message.to_string())
);
}
}
#[test]
fn test_get_default_model_for_provider_lmstudio() {