From c346d00d1753f19b7996d41a0d7742cf9be5d0f0 Mon Sep 17 00:00:00 2001 From: Jack Amadeo Date: Mon, 22 Jun 2026 15:10:59 -0400 Subject: [PATCH] move OpenAI provider into goose-providers (#9880) --- Cargo.lock | 1 + crates/goose-providers/Cargo.toml | 8 +- crates/goose-providers/examples/streaming.rs | 43 + crates/goose-providers/src/base.rs | 191 ++++ crates/goose-providers/src/formats.rs | 1 + .../src}/formats/openai_responses.rs | 14 +- .../src}/http_status.rs | 4 +- crates/goose-providers/src/lib.rs | 3 + .../src}/openai.rs | 851 ++++-------------- .../src}/openai_compatible.rs | 16 +- .../goose/src/config/declarative_providers.rs | 6 +- crates/goose/src/providers/amp_acp.rs | 12 +- crates/goose/src/providers/anthropic.rs | 9 +- crates/goose/src/providers/avian.rs | 8 +- crates/goose/src/providers/azure.rs | 8 +- crates/goose/src/providers/base.rs | 255 +----- crates/goose/src/providers/bedrock.rs | 11 +- crates/goose/src/providers/chatgpt_codex.rs | 10 +- crates/goose/src/providers/claude_acp.rs | 12 +- crates/goose/src/providers/claude_code.rs | 17 +- crates/goose/src/providers/codex.rs | 14 +- crates/goose/src/providers/codex_acp.rs | 12 +- crates/goose/src/providers/copilot_acp.rs | 12 +- crates/goose/src/providers/cursor_agent.rs | 17 +- crates/goose/src/providers/databricks.rs | 10 +- crates/goose/src/providers/databricks_v2.rs | 11 +- crates/goose/src/providers/formats/mod.rs | 1 - crates/goose/src/providers/gcpvertexai.rs | 9 +- crates/goose/src/providers/gemini_cli.rs | 17 +- crates/goose/src/providers/gemini_oauth.rs | 8 +- crates/goose/src/providers/githubcopilot.rs | 10 +- crates/goose/src/providers/google.rs | 8 +- crates/goose/src/providers/huggingface.rs | 10 +- crates/goose/src/providers/init.rs | 4 +- .../src/providers/inventory/registrations.rs | 2 +- crates/goose/src/providers/kimicode.rs | 9 +- crates/goose/src/providers/litellm.rs | 8 +- crates/goose/src/providers/local_inference.rs | 8 +- crates/goose/src/providers/mod.rs | 13 +- crates/goose/src/providers/nanogpt.rs | 9 +- crates/goose/src/providers/ollama.rs | 8 +- crates/goose/src/providers/openai_def.rs | 488 ++++++++++ crates/goose/src/providers/openrouter.rs | 8 +- crates/goose/src/providers/pi_acp.rs | 12 +- .../goose/src/providers/provider_registry.rs | 4 +- crates/goose/src/providers/sagemaker_tgi.rs | 8 +- crates/goose/src/providers/snowflake.rs | 8 +- crates/goose/src/providers/testprovider.rs | 8 +- crates/goose/src/providers/tetrate.rs | 8 +- crates/goose/src/providers/utils.rs | 2 +- crates/goose/src/providers/xai.rs | 8 +- crates/goose/src/providers/xai_oauth.rs | 8 +- .../goose/src/session/import_formats/codex.rs | 4 +- crates/goose/tests/agent.rs | 32 +- crates/goose/tests/compaction.rs | 8 +- crates/goose/tests/mcp_integration_test.rs | 8 +- crates/goose/tests/providers.rs | 11 +- 57 files changed, 1176 insertions(+), 1129 deletions(-) create mode 100644 crates/goose-providers/examples/streaming.rs rename crates/{goose/src/providers => goose-providers/src}/formats/openai_responses.rs (99%) rename crates/{goose/src/providers => goose-providers/src}/http_status.rs (99%) rename crates/{goose/src/providers => goose-providers/src}/openai.rs (52%) rename crates/{goose/src/providers => goose-providers/src}/openai_compatible.rs (95%) create mode 100644 crates/goose/src/providers/openai_def.rs diff --git a/Cargo.lock b/Cargo.lock index 22aafecf2..b37d68180 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5008,6 +5008,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tokio-stream", + "tokio-util", "tracing", "unicode-normalization", "url", diff --git a/crates/goose-providers/Cargo.toml b/crates/goose-providers/Cargo.toml index 86b7d6b1b..7fd0180c6 100644 --- a/crates/goose-providers/Cargo.toml +++ b/crates/goose-providers/Cargo.toml @@ -46,6 +46,8 @@ uuid = { workspace = true, features = ["v4", "std"] } async-trait = { workspace = true } strum = { workspace = true } tokio = { workspace = true } +tokio-stream = { workspace = true, features = ["io-util"] } +tokio-util = { workspace = true, features = ["compat"] } rand = { workspace = true } url = { workspace = true } pem = { version = "3.0.2", default-features = false, features = ["std"], optional = true } @@ -56,6 +58,10 @@ sec1 = { version = "0.7", default-features = false, features = ["der", "pkcs8", [dev-dependencies] test-case = { workspace = true } tempfile = { workspace = true } -tokio = { workspace = true } +tokio = { workspace = true, features = ["rt-multi-thread"] } tokio-stream = { workspace = true } env-lock = { workspace = true } + +[[example]] +name = "streaming" +required-features = ["rustls-tls"] diff --git a/crates/goose-providers/examples/streaming.rs b/crates/goose-providers/examples/streaming.rs new file mode 100644 index 000000000..1775cb1d6 --- /dev/null +++ b/crates/goose-providers/examples/streaming.rs @@ -0,0 +1,43 @@ +use std::env; + +use anyhow::Result; +use futures::StreamExt; +use goose_providers::{ + api_client::{ApiClient, AuthMethod}, + base::Provider, + conversation::message::Message, + model::ModelConfig, + openai::OpenAiProvider, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let model = ModelConfig::new("gpt-5.4-mini")?; + let key = env::var("OPENAI_API_KEY").map_err(|_| anyhow::anyhow!("need an OpenAI key"))?; + let api_client = ApiClient::new_with_tls( + "https://api.openai.com".to_string(), + AuthMethod::BearerToken(key), + Some(Default::default()), + )?; + let provider = OpenAiProvider::new(api_client, model.clone()); + + let system = "You are a knowledgable geography expert"; + let messages = [Message::user().with_text("what is the capital of France?")]; + + let mut stream = provider + .stream( + &model, + "", // session-id + system, + &messages, + &[], + ) + .await?; + + while let Some((Some(msg), _)) = stream.next().await.transpose()? { + print!("{}", msg.as_concat_text()); + } + println!(); + + Ok(()) +} diff --git a/crates/goose-providers/src/base.rs b/crates/goose-providers/src/base.rs index 5dfe73bd3..8ee303430 100644 --- a/crates/goose-providers/src/base.rs +++ b/crates/goose-providers/src/base.rs @@ -18,6 +18,193 @@ use crate::{ retry::RetryConfig, }; +/// Metadata about a provider's configuration requirements and capabilities +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct ProviderMetadata { + /// The unique identifier for this provider + pub name: String, + /// Display name for the provider in UIs + pub display_name: String, + /// Description of the provider's capabilities + pub description: String, + /// The default/recommended model for this provider + pub default_model: String, + /// A list of currently known models with their capabilities + pub known_models: Vec, + /// Link to the docs where models can be found + pub model_doc_link: String, + /// Required configuration keys + pub config_keys: Vec, + /// step-by-step instructions for set up providers eg: api key + #[serde(default)] + pub setup_steps: Vec, + /// Hint shown in the model picker when this provider manages its own model selection. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model_selection_hint: Option, +} + +impl ProviderMetadata { + pub fn new( + name: &str, + display_name: &str, + description: &str, + default_model: &str, + model_names: Vec<&str>, + model_doc_link: &str, + config_keys: Vec, + ) -> Self { + Self { + name: name.to_string(), + display_name: display_name.to_string(), + description: description.to_string(), + default_model: default_model.to_string(), + known_models: model_names + .iter() + .map(|&model_name| model_info_for_provider_model(name, model_name)) + .collect(), + model_doc_link: model_doc_link.to_string(), + config_keys, + setup_steps: vec![], + model_selection_hint: None, + } + } + + pub fn with_models( + name: &str, + display_name: &str, + description: &str, + default_model: &str, + models: Vec, + model_doc_link: &str, + config_keys: Vec, + ) -> Self { + Self { + name: name.to_string(), + display_name: display_name.to_string(), + description: description.to_string(), + default_model: default_model.to_string(), + known_models: models, + model_doc_link: model_doc_link.to_string(), + config_keys, + setup_steps: vec![], + model_selection_hint: None, + } + } + + pub fn empty() -> Self { + Self { + name: "".to_string(), + display_name: "".to_string(), + description: "".to_string(), + default_model: "".to_string(), + known_models: vec![], + model_doc_link: "".to_string(), + config_keys: vec![], + setup_steps: vec![], + model_selection_hint: None, + } + } + + pub fn with_setup_steps(mut self, steps: Vec<&str>) -> Self { + self.setup_steps = steps.into_iter().map(|s| s.to_string()).collect(); + self + } + + pub fn with_model_selection_hint(mut self, hint: &str) -> Self { + self.model_selection_hint = Some(hint.to_string()); + self + } +} + +/// Configuration key metadata for provider setup +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct ConfigKey { + /// The name of the configuration key (e.g., "API_KEY") + pub name: String, + /// Whether this key is required for the provider to function + pub required: bool, + /// Whether this key should be stored securely (e.g., in keychain) + pub secret: bool, + /// Optional default value for the key + pub default: Option, + /// Whether this key should be configured using an OAuth flow + /// When true, the provider's configure_oauth() method will be called instead of prompting for manual input + pub oauth_flow: bool, + /// Whether this OAuth flow uses the device code grant (RFC 8628) + /// When true, the user must enter a verification code in the browser + #[serde(default)] + pub device_code_flow: bool, + /// Whether this key should be shown prominently during provider setup + /// (onboarding, settings modal, CLI configure) + #[serde(default)] + pub primary: bool, +} + +impl ConfigKey { + /// Create a new ConfigKey + pub fn new( + name: &str, + required: bool, + secret: bool, + default: Option<&str>, + primary: bool, + ) -> Self { + Self { + name: name.to_string(), + required, + secret, + default: default.map(|s| s.to_string()), + oauth_flow: false, + device_code_flow: false, + primary, + } + } + + /// Create a new ConfigKey that uses an OAuth flow for configuration + /// + /// This is used for providers that support OAuth authentication instead of manual API key entry. + /// When oauth_flow is true, the configuration system will call the provider's configure_oauth() method. + pub fn new_oauth( + name: &str, + required: bool, + secret: bool, + default: Option<&str>, + primary: bool, + ) -> Self { + Self { + name: name.to_string(), + required, + secret, + default: default.map(|s| s.to_string()), + oauth_flow: true, + device_code_flow: false, + primary, + } + } + + /// Create a new ConfigKey that uses OAuth device code flow (RFC 8628) for configuration + /// + /// Similar to new_oauth, but indicates the provider uses the device code grant where the user + /// must enter a verification code in the browser. + pub fn new_oauth_device_code( + name: &str, + required: bool, + secret: bool, + default: Option<&str>, + primary: bool, + ) -> Self { + Self { + name: name.to_string(), + required, + secret, + default: default.map(|s| s.to_string()), + oauth_flow: true, + device_code_flow: true, + primary, + } + } +} + /// Information about a model's capabilities #[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)] pub struct ModelInfo { @@ -76,6 +263,10 @@ impl ModelInfo { } } +pub trait ProviderDescriptor { + fn metadata() -> ProviderMetadata; +} + /// A message stream yields partial text content but complete tool calls, all within the Message object /// So a message with text will contain potentially just a word of a longer response, but tool calls /// messages will only be yielded once concatenated. diff --git a/crates/goose-providers/src/formats.rs b/crates/goose-providers/src/formats.rs index d8c308735..4b7d8f21a 100644 --- a/crates/goose-providers/src/formats.rs +++ b/crates/goose-providers/src/formats.rs @@ -1 +1,2 @@ pub mod openai; +pub mod openai_responses; diff --git a/crates/goose/src/providers/formats/openai_responses.rs b/crates/goose-providers/src/formats/openai_responses.rs similarity index 99% rename from crates/goose/src/providers/formats/openai_responses.rs rename to crates/goose-providers/src/formats/openai_responses.rs index ee0c2d8f1..38a3023c5 100644 --- a/crates/goose/src/providers/formats/openai_responses.rs +++ b/crates/goose-providers/src/formats/openai_responses.rs @@ -1,15 +1,15 @@ use crate::conversation::message::{Message, MessageContent}; +use crate::conversation::token_usage::{ProviderUsage, Usage}; +use crate::errors::ProviderError; +use crate::formats::openai::{ + extract_reasoning_effort, is_openai_responses_model, openai_reasoning_effort_for_thinking, +}; use crate::mcp_utils::extract_text_from_resource; +use crate::model::ModelConfig; use anyhow::Error; use async_stream::try_stream; use chrono; use futures::Stream; -use goose_providers::conversation::token_usage::{ProviderUsage, Usage}; -use goose_providers::errors::ProviderError; -use goose_providers::formats::openai::{ - extract_reasoning_effort, is_openai_responses_model, openai_reasoning_effort_for_thinking, -}; -use goose_providers::model::ModelConfig; use rmcp::model::{object, CallToolRequestParams, RawContent, Role, Tool}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -962,8 +962,8 @@ where mod tests { use super::*; use crate::conversation::message::MessageContent; + use crate::model::ModelConfig; use futures::StreamExt; - use goose_providers::model::ModelConfig; use rmcp::model::CallToolRequestParams; use rmcp::object; diff --git a/crates/goose/src/providers/http_status.rs b/crates/goose-providers/src/http_status.rs similarity index 99% rename from crates/goose/src/providers/http_status.rs rename to crates/goose-providers/src/http_status.rs index 2c2415355..13147ccad 100644 --- a/crates/goose/src/providers/http_status.rs +++ b/crates/goose-providers/src/http_status.rs @@ -6,8 +6,8 @@ use std::time::{Duration, SystemTime}; +use crate::errors::ProviderError; use chrono::{DateTime, NaiveDateTime, TimeZone, Utc}; -use goose_providers::errors::ProviderError; use reqwest::header::{HeaderMap, RETRY_AFTER}; use reqwest::{Response, StatusCode}; use serde_json::Value; @@ -107,7 +107,7 @@ fn parse_http_date(value: &str) -> Option { None } -pub(crate) fn is_context_length_exceeded_message(text: &str) -> bool { +pub fn is_context_length_exceeded_message(text: &str) -> bool { let text_lower = text.to_lowercase(); let direct_context_phrases = [ diff --git a/crates/goose-providers/src/lib.rs b/crates/goose-providers/src/lib.rs index 41c62f7b1..e450c7c08 100644 --- a/crates/goose-providers/src/lib.rs +++ b/crates/goose-providers/src/lib.rs @@ -5,10 +5,13 @@ pub mod conversation; pub mod errors; pub mod formats; pub mod goose_mode; +pub mod http_status; pub mod images; pub mod json; pub(crate) mod mcp_utils; pub mod model; +pub mod openai; +pub mod openai_compatible; pub mod permission; pub mod request_log; pub mod retry; diff --git a/crates/goose/src/providers/openai.rs b/crates/goose-providers/src/openai.rs similarity index 52% rename from crates/goose/src/providers/openai.rs rename to crates/goose-providers/src/openai.rs index 21eaa6d58..f0a915eb7 100644 --- a/crates/goose/src/providers/openai.rs +++ b/crates/goose-providers/src/openai.rs @@ -1,37 +1,33 @@ -use super::api_client::{ApiClient, AuthMethod}; -use super::base::{ - ConfigKey, ModelInfo, Provider, ProviderDef, ProviderMetadata, DEFAULT_PROVIDER_TIMEOUT_SECS, -}; -use super::formats::openai_responses::{ - create_responses_request, get_responses_usage, responses_api_to_message, ResponsesApiResponse, -}; -use super::openai_compatible::{ - handle_response_openai_compat, handle_status, stream_openai_compat, stream_responses_compat, -}; +use super::api_client::ApiClient; +use super::base::{ConfigKey, ModelInfo, Provider, ProviderMetadata}; use super::retry::ProviderRetry; -use crate::config::declarative_providers::DeclarativeProviderConfig; use crate::conversation::message::Message; -use anyhow::Result; -use async_trait::async_trait; -use futures::future::BoxFuture; -use goose_providers::conversation::token_usage::ProviderUsage; -use goose_providers::errors::ProviderError; -use goose_providers::formats::openai::is_openai_responses_model; -use goose_providers::formats::openai::{ +use crate::conversation::token_usage::ProviderUsage; +use crate::errors::ProviderError; +use crate::formats::openai::is_openai_responses_model; +use crate::formats::openai::{ create_request_with_options, get_usage, response_to_message, OpenAiFormatOptions, }; -use goose_providers::images::ImageFormat; -use goose_providers::request_log::{start_log, LoggerHandleExt}; +use crate::formats::openai_responses::{ + create_responses_request, get_responses_usage, responses_api_to_message, ResponsesApiResponse, +}; +use crate::images::ImageFormat; +use crate::openai_compatible::{ + handle_response_openai_compat, handle_status, stream_openai_compat, stream_responses_compat, +}; +use crate::request_log::{start_log, LoggerHandleExt}; +use anyhow::Result; +use async_trait::async_trait; use reqwest::StatusCode; use std::collections::HashMap; -use crate::providers::base::MessageStream; -use goose_providers::model::ModelConfig; +use crate::base::{MessageStream, ProviderDescriptor}; +use crate::model::ModelConfig; use rmcp::model::Tool; -pub(crate) const OPEN_AI_PROVIDER_NAME: &str = "openai"; -pub(crate) const OPEN_AI_DEFAULT_BASE_PATH: &str = "v1/chat/completions"; -const OPEN_AI_VERSIONLESS_BASE_PATH: &str = "chat/completions"; +pub const OPEN_AI_PROVIDER_NAME: &str = "openai"; +pub const OPEN_AI_DEFAULT_BASE_PATH: &str = "v1/chat/completions"; +pub const OPEN_AI_VERSIONLESS_BASE_PATH: &str = "chat/completions"; const OPEN_AI_DEFAULT_RESPONSES_PATH: &str = "v1/responses"; const OPEN_AI_DEFAULT_MODELS_PATH: &str = "v1/models"; pub const OPEN_AI_DEFAULT_MODEL: &str = "gpt-4o"; @@ -67,21 +63,6 @@ pub const OPEN_AI_DOC_URL: &str = "https://platform.openai.com/docs/models"; type OpenAiBaseUrlParts = (String, Vec<(String, String)>, bool); -/// Components extracted from an `OPENAI_BASE_URL` value. -struct ParsedBaseUrl { - /// The host (scheme + authority + any path prefix before `/v1`). - host: String, - /// Query parameters to forward on every request. - query_params: Vec<(String, String)>, - /// Whether the URL path ended with `/v1`. - has_v1: bool, - /// `true` when the host was derived from `OPENAI_BASE_URL`. - /// Controls whether `OPENAI_BASE_PATH` is read from env only - /// (to avoid persisted desktop defaults shadowing URL-derived paths) - /// or from config too (to honour Docker Model Runner setups). - from_base_url: bool, -} - /// Ensure a base URL has an explicit scheme. /// /// Users frequently enter hosts like `localhost:1234` without a scheme. The @@ -89,7 +70,7 @@ struct ParsedBaseUrl { /// silently dropping both the host and the port. When no `://` is present we /// prepend a sensible scheme (`http://` for local hosts, `https://` /// otherwise) so the host and port survive parsing. -pub(crate) fn ensure_url_scheme(raw_url: &str) -> String { +pub fn ensure_url_scheme(raw_url: &str) -> String { let trimmed = raw_url.trim(); if trimmed.contains("://") { return trimmed.to_string(); @@ -110,7 +91,7 @@ pub(crate) fn ensure_url_scheme(raw_url: &str) -> String { format!("{}://{}", scheme, trimmed) } -pub(crate) fn parse_openai_base_url(raw_url: &str) -> Result { +pub fn parse_openai_base_url(raw_url: &str) -> Result { let raw_url = ensure_url_scheme(raw_url); let raw_url = raw_url.as_str(); let parsed = url::Url::parse(raw_url) @@ -154,193 +135,27 @@ pub struct OpenAiProvider { preserve_thinking_context: bool, } -impl OpenAiProvider { - pub async fn from_env( - model: ModelConfig, - tls_config: Option, - ) -> Result { - let config = crate::config::Config::global(); +/// Builder for [`OpenAiProvider`]. +/// +/// Exposes every field of the provider so that constructors living outside +/// `openai.rs` (e.g. in `openai_def.rs`) can assemble a provider without +/// needing direct access to the struct's private fields. +pub struct OpenAiProviderBuilder { + api_client: ApiClient, + base_path: String, + organization: Option, + project: Option, + model: ModelConfig, + custom_headers: Option>, + supports_streaming: bool, + name: String, + custom_models: Option>, + dynamic_models: Option, + skip_canonical_filtering: bool, + preserve_thinking_context: bool, +} - // Resolve host and base_path. - // - // Priority (highest first): - // 1. OPENAI_HOST env var — session override (deprecated but still - // honoured so that `OPENAI_HOST=… goose` keeps working) - // 2. OPENAI_BASE_URL (env or config) — ecosystem-standard - // 3. OPENAI_HOST from config file — persisted by `goose configure` - // 4. Default "https://api.openai.com" - // - // OPENAI_BASE_URL is parsed into host + query params + a flag - // indicating whether the URL included a /v1 path segment. When /v1 - // is present the default base_path is "v1/chat/completions"; - // otherwise "chat/completions" to match the OpenAI SDK convention. - // - // OPENAI_BASE_PATH always wins when set explicitly. - let parsed = if let Ok(h) = std::env::var("OPENAI_HOST") { - // OPENAI_HOST env var takes priority as a session override so - // that existing scripts like `OPENAI_HOST=… goose` still work - // even after OPENAI_BASE_URL is persisted in config. - ParsedBaseUrl { - host: h, - query_params: vec![], - has_v1: true, - from_base_url: false, - } - } else if let Some(raw_url) = config - .get_param::("OPENAI_BASE_URL") - .ok() - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) - { - Self::parse_base_url(&raw_url)? - } else { - let h: String = config - .get_param("OPENAI_HOST") - .unwrap_or_else(|_| "https://api.openai.com".to_string()); - ParsedBaseUrl { - host: h, - query_params: vec![], - has_v1: true, - from_base_url: false, - } - }; - - // When the host was derived from OPENAI_BASE_URL, read - // OPENAI_BASE_PATH from env only so that the desktop UI's persisted - // default ("v1/chat/completions") doesn't shadow the versionless - // path. When the host came from OPENAI_HOST (env or config), read - // from config too — Docker Model Runner and similar setups persist a - // custom base_path that must be honoured. - let default_bp = || { - if parsed.has_v1 { - OPEN_AI_DEFAULT_BASE_PATH.to_string() - } else { - OPEN_AI_VERSIONLESS_BASE_PATH.to_string() - } - }; - let base_path: String = if parsed.from_base_url { - std::env::var("OPENAI_BASE_PATH").unwrap_or_else(|_| default_bp()) - } else { - config - .get_param("OPENAI_BASE_PATH") - .unwrap_or_else(|_| default_bp()) - }; - - // Only apply the default fast model when talking to OpenAI directly. - // Custom/compatible endpoints likely don't serve gpt-4o-mini, so - // leave fast_model unset (complete_fast will fall back to the main model). - // Parse the URL and compare the hostname exactly to avoid false positives - // (e.g. https://api.openai.com.local:8000 or proxy paths containing api.openai.com). - let host = parsed.host.clone(); - - // Only apply the default fast model when talking to OpenAI directly. - // Custom/compatible endpoints likely don't serve gpt-4o-mini, so - // leave fast_model unset (complete_fast will fall back to the main model). - // Parse the URL and compare the hostname exactly to avoid false positives - // (e.g. https://api.openai.com.local:8000 or proxy paths containing api.openai.com). - let is_openai = url::Url::parse(&host) - .ok() - .and_then(|u| u.host_str().map(|h| h.to_ascii_lowercase())) - .map(|h| h == "api.openai.com" || h.ends_with(".api.openai.com")) - .unwrap_or(false); - let model = if is_openai { - crate::model_config::with_configured_fast_model( - model, - OPEN_AI_PROVIDER_NAME, - OPEN_AI_DEFAULT_FAST_MODEL, - )? - } else { - model - }; - - let secrets = config - .get_secrets("OPENAI_API_KEY", &["OPENAI_CUSTOM_HEADERS"]) - .unwrap_or_default(); - let api_key: Option = secrets.get("OPENAI_API_KEY").cloned(); - let custom_headers: Option> = secrets - .get("OPENAI_CUSTOM_HEADERS") - .cloned() - .map(parse_custom_headers); - - let organization: Option = config.get_param("OPENAI_ORGANIZATION").ok(); - let project: Option = config.get_param("OPENAI_PROJECT").ok(); - let timeout_secs: u64 = config - .get_param("OPENAI_TIMEOUT") - .unwrap_or(DEFAULT_PROVIDER_TIMEOUT_SECS); - - let auth = match api_key { - Some(key) if !key.is_empty() => AuthMethod::BearerToken(key), - _ => AuthMethod::NoAuth, - }; - let mut api_client = ApiClient::with_timeout_and_tls( - parsed.host, - auth, - std::time::Duration::from_secs(timeout_secs), - tls_config, - )?; - - if !parsed.query_params.is_empty() { - api_client = api_client.with_query(parsed.query_params); - } - - if let Some(org) = &organization { - api_client = api_client.with_header("OpenAI-Organization", org)?; - } - - if let Some(project) = &project { - api_client = api_client.with_header("OpenAI-Project", project)?; - } - - if let Some(headers) = &custom_headers { - let mut header_map = reqwest::header::HeaderMap::new(); - for (key, value) in headers { - let header_name = reqwest::header::HeaderName::from_bytes(key.as_bytes())?; - let header_value = reqwest::header::HeaderValue::from_str(value)?; - header_map.insert(header_name, header_value); - } - api_client = api_client.with_headers(header_map)?; - } - - let mut provider = Self { - api_client, - base_path, - organization, - project, - model, - custom_headers, - supports_streaming: true, - name: OPEN_AI_PROVIDER_NAME.to_string(), - custom_models: None, - dynamic_models: None, - skip_canonical_filtering: false, - preserve_thinking_context: !is_openai, - }; - - // Only fill the context limit when nothing else set it: an existing value may be - // an explicit GOOSE_CONTEXT_LIMIT, an ACP/server per-session override, or a - // GOOSE_PREDEFINED_MODELS entry, none of which we should overwrite. llama.cpp and - // Ollama report the real allocated window via the non-standard meta.n_ctx field; - // reading it fixes auto-compaction for local servers that would otherwise fall - // back to DEFAULT_CONTEXT_LIMIT. The probe is bounded by a short timeout so a - // hung /v1/models can't stall provider construction (the shared ApiClient uses - // OPENAI_TIMEOUT, up to 600s). - if provider.model.context_limit.is_none() { - const N_CTX_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); - let model_name = provider.model.model_name.clone(); - if let Ok(Some(n_ctx)) = tokio::time::timeout( - N_CTX_PROBE_TIMEOUT, - provider.fetch_n_ctx_from_api(&model_name), - ) - .await - { - provider.model.context_limit = Some(n_ctx); - } - } - - Ok(provider) - } - - #[doc(hidden)] +impl OpenAiProviderBuilder { pub fn new(api_client: ApiClient, model: ModelConfig) -> Self { Self { api_client, @@ -358,179 +173,103 @@ impl OpenAiProvider { } } - /// Resolve the API key from a declarative provider config. - /// - /// Returns `Some(key)` if a key is found, `None` if the key is optional/missing, - /// or an error if the key is required but missing/unreadable. - /// - /// The `get_secret` closure is used to look up the secret by key name. This allows - /// testing without depending on `Config::global()`. - pub fn resolve_api_key( - config: &DeclarativeProviderConfig, - get_secret: &dyn Fn(&str) -> Result, - ) -> Result> { - if config.api_key_env.is_empty() { - return Ok(None); - } - - match get_secret(&config.api_key_env) { - Ok(key) => Ok(Some(key)), - Err(e) => { - use crate::config::ConfigError; - match e { - ConfigError::NotFound(_) => { - if config.requires_auth { - anyhow::bail!( - "Required API key {} is not set. Configure it via `goose configure` or set the {} environment variable.", - config.api_key_env, - config.api_key_env - ); - } - Ok(None) - } - other => { - if config.requires_auth { - anyhow::bail!("Failed to read {}: {}", config.api_key_env, other); - } else { - tracing::warn!( - "Failed to read optional API key {}: {}. Proceeding without authentication.", - config.api_key_env, - other - ); - Ok(None) - } - } - } - } - } + pub fn api_client(mut self, api_client: ApiClient) -> Self { + self.api_client = api_client; + self } - pub fn from_custom_config( - model: ModelConfig, - config: DeclarativeProviderConfig, - tls_config: Option, - ) -> Result { - let custom_models = if !config.models.is_empty() { - Some( - config - .models - .iter() - .map(|m| m.name.clone()) - .collect::>(), - ) - } else { - None - }; + pub fn base_path(mut self, base_path: impl Into) -> Self { + self.base_path = base_path.into(); + self + } - if config.dynamic_models == Some(false) && custom_models.is_none() { - return Err(anyhow::anyhow!( - "Provider '{}' has dynamic_models: false but no static models listed; \ - at least one entry in `models` is required.", - config.name - )); + pub fn organization(mut self, organization: Option) -> Self { + self.organization = organization; + self + } + + pub fn project(mut self, project: Option) -> Self { + self.project = project; + self + } + + pub fn model(mut self, model: ModelConfig) -> Self { + self.model = model; + self + } + + pub fn custom_headers(mut self, custom_headers: Option>) -> Self { + self.custom_headers = custom_headers; + self + } + + pub fn supports_streaming(mut self, supports_streaming: bool) -> Self { + self.supports_streaming = supports_streaming; + self + } + + pub fn name(mut self, name: impl Into) -> Self { + self.name = name.into(); + self + } + + pub fn custom_models(mut self, custom_models: Option>) -> Self { + self.custom_models = custom_models; + self + } + + pub fn dynamic_models(mut self, dynamic_models: Option) -> Self { + self.dynamic_models = dynamic_models; + self + } + + pub fn skip_canonical_filtering(mut self, skip_canonical_filtering: bool) -> Self { + self.skip_canonical_filtering = skip_canonical_filtering; + self + } + + pub fn preserve_thinking_context(mut self, preserve_thinking_context: bool) -> Self { + self.preserve_thinking_context = preserve_thinking_context; + self + } + + pub fn build(self) -> OpenAiProvider { + OpenAiProvider { + api_client: self.api_client, + base_path: self.base_path, + organization: self.organization, + project: self.project, + model: self.model, + custom_headers: self.custom_headers, + supports_streaming: self.supports_streaming, + name: self.name, + custom_models: self.custom_models, + dynamic_models: self.dynamic_models, + skip_canonical_filtering: self.skip_canonical_filtering, + preserve_thinking_context: self.preserve_thinking_context, } + } +} - let global_config = crate::config::Config::global(); - let api_key = Self::resolve_api_key(&config, &|key| global_config.get_secret(key))?; - - let normalized_base_url = ensure_url_scheme(&config.base_url); - let url = url::Url::parse(&normalized_base_url) - .map_err(|e| anyhow::anyhow!("Invalid base URL '{}': {}", config.base_url, e))?; - - let host = if let Some(port) = url.port() { - format!( - "{}://{}:{}", - url.scheme(), - url.host_str().unwrap_or(""), - port - ) - } else { - format!("{}://{}", url.scheme(), url.host_str().unwrap_or("")) - }; - let base_path = if let Some(ref explicit_path) = config.base_path { - explicit_path.trim_start_matches('/').to_string() - } else { - Self::derive_base_path(url.path()) - }; - - let timeout_secs = config - .timeout_seconds - .unwrap_or(DEFAULT_PROVIDER_TIMEOUT_SECS); - - let auth = match api_key { - Some(key) if !key.is_empty() => AuthMethod::BearerToken(key), - _ => AuthMethod::NoAuth, - }; - let mut api_client = ApiClient::with_timeout_and_tls( - host, - auth, - std::time::Duration::from_secs(timeout_secs), - tls_config, - )?; - - // Add custom headers if present - if let Some(headers) = &config.headers { - let mut header_map = reqwest::header::HeaderMap::new(); - for (key, value) in headers { - let header_name = reqwest::header::HeaderName::from_bytes(key.as_bytes())?; - let header_value = reqwest::header::HeaderValue::from_str(value)?; - header_map.insert(header_name, header_value); - } - api_client = api_client.with_headers(header_map)?; - } - - let model = if let Some(ref fast_model_name) = config.fast_model { - crate::model_config::with_configured_fast_model(model, &config.name, fast_model_name)? - } else { - model - }; - - Ok(Self { +impl OpenAiProvider { + #[doc(hidden)] + pub fn new(api_client: ApiClient, model: ModelConfig) -> Self { + Self { api_client, - base_path, + base_path: OPEN_AI_DEFAULT_BASE_PATH.to_string(), organization: None, project: None, model, - custom_headers: config.headers, - supports_streaming: config.supports_streaming.unwrap_or(true), - name: config.name.clone(), - custom_models, - dynamic_models: config.dynamic_models, - skip_canonical_filtering: config.skip_canonical_filtering, - preserve_thinking_context: config.preserves_thinking, - }) - } - - fn parse_base_url(raw_url: &str) -> Result { - let (host, query_params, has_v1) = parse_openai_base_url(raw_url)?; - Ok(ParsedBaseUrl { - host, - query_params, - has_v1, - from_base_url: true, - }) - } - - fn derive_base_path(url_path: &str) -> String { - let stripped = url_path.trim_start_matches('/'); - let normalized = stripped.trim_end_matches('/'); - if normalized.is_empty() { - "v1/chat/completions".to_string() - } else if normalized.ends_with("chat/completions") { - stripped.to_string() - } else if Self::ends_with_version_segment(normalized) { - format!("{}/chat/completions", normalized) - } else { - format!("{}/v1/chat/completions", normalized) + custom_headers: None, + supports_streaming: true, + name: OPEN_AI_PROVIDER_NAME.to_string(), + custom_models: None, + dynamic_models: None, + skip_canonical_filtering: false, + preserve_thinking_context: false, } } - fn ends_with_version_segment(path: &str) -> bool { - let last = path.rsplit('/').next().unwrap_or(path); - last.strip_prefix('v') - .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit())) - } - fn normalize_base_path(base_path: &str) -> String { if let Some(path) = base_path.strip_prefix('/') { format!("/{}", path.trim_end_matches('/')) @@ -651,6 +390,28 @@ impl OpenAiProvider { } } + /// Fill the model's context limit from the API when it isn't already set. + /// + /// An existing value may be an explicit GOOSE_CONTEXT_LIMIT, an ACP/server + /// per-session override, or a GOOSE_PREDEFINED_MODELS entry, none of which we + /// should overwrite. llama.cpp and Ollama report the real allocated window via + /// the non-standard meta.n_ctx field; reading it fixes auto-compaction for local + /// servers that would otherwise fall back to DEFAULT_CONTEXT_LIMIT. The probe is + /// bounded by a short timeout so a hung /v1/models can't stall provider + /// construction (the shared ApiClient uses OPENAI_TIMEOUT, up to 600s). + pub async fn probe_context_limit_if_unset(&mut self) { + if self.model.context_limit.is_some() { + return; + } + const N_CTX_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); + let model_name = self.model.model_name.clone(); + if let Ok(Some(n_ctx)) = + tokio::time::timeout(N_CTX_PROBE_TIMEOUT, self.fetch_n_ctx_from_api(&model_name)).await + { + self.model.context_limit = Some(n_ctx); + } + } + async fn fetch_models_from_api(&self) -> Result, ProviderError> { let models_path = Self::map_base_path(&self.base_path, "models", OPEN_AI_DEFAULT_MODELS_PATH); @@ -730,9 +491,7 @@ fn parse_n_ctx_from_models(json: &serde_json::Value, model_name: &str) -> Option } } -impl ProviderDef for OpenAiProvider { - type Provider = Self; - +impl ProviderDescriptor for OpenAiProvider { fn metadata() -> ProviderMetadata { let models = OPEN_AI_KNOWN_MODELS .iter() @@ -775,14 +534,6 @@ impl ProviderDef for OpenAiProvider { "Copy the key and paste it above", ]) } - - fn from_env( - model: ModelConfig, - _extensions: Vec, - tls_config: Option, - ) -> BoxFuture<'static, Result> { - Box::pin(Self::from_env(model, tls_config)) - } } #[async_trait] @@ -936,7 +687,7 @@ impl Provider for OpenAiProvider { } } -fn parse_custom_headers(s: String) -> HashMap { +pub fn parse_custom_headers(s: String) -> HashMap { s.split(',') .filter_map(|header| { let mut parts = header.splitn(2, '='); @@ -950,6 +701,7 @@ fn parse_custom_headers(s: String) -> HashMap { #[cfg(test)] mod tests { use super::*; + use crate::api_client::AuthMethod; use serde_json::json; fn make_provider(name: &str) -> OpenAiProvider { @@ -1158,119 +910,6 @@ mod tests { let models_path = OpenAiProvider::map_base_path("/custom/path", "models", "v1/models"); assert_eq!(models_path, "/v1/models"); } - #[test] - fn parse_base_url_strips_v1_from_standard_openai_url() { - let r = OpenAiProvider::parse_base_url("https://api.openai.com/v1").unwrap(); - assert_eq!(r.host, "https://api.openai.com"); - assert!(r.query_params.is_empty()); - assert!(r.has_v1); - } - - #[test] - fn parse_base_url_preserves_prefix_before_v1() { - let r = OpenAiProvider::parse_base_url("https://gateway.example.com/openai/v1").unwrap(); - assert_eq!(r.host, "https://gateway.example.com/openai"); - assert!(r.has_v1); - } - - #[test] - fn parse_base_url_handles_no_path() { - let r = OpenAiProvider::parse_base_url("https://api.openai.com").unwrap(); - assert_eq!(r.host, "https://api.openai.com"); - assert!(r.has_v1); - } - - #[test] - fn parse_base_url_handles_trailing_slash() { - let r = OpenAiProvider::parse_base_url("https://api.openai.com/v1/").unwrap(); - assert_eq!(r.host, "https://api.openai.com"); - assert!(r.has_v1); - } - - #[test] - fn parse_base_url_preserves_port() { - let r = OpenAiProvider::parse_base_url("https://localhost:8080/v1").unwrap(); - assert_eq!(r.host, "https://localhost:8080"); - assert!(r.has_v1); - } - - #[test] - fn parse_base_url_preserves_non_v1_path() { - let r = OpenAiProvider::parse_base_url("https://example.com/custom/api").unwrap(); - assert_eq!(r.host, "https://example.com/custom/api"); - assert!(!r.has_v1); - } - - #[test] - fn derive_base_path_not_removing_api_path() { - let r = OpenAiProvider::derive_base_path("https://opencode.ai/zen/go"); - assert_eq!(r, "https://opencode.ai/zen/go/v1/chat/completions"); - } - - #[test] - fn derive_base_path_should_support_v1() { - let r = OpenAiProvider::derive_base_path("https://opencode.ai/zen/go/v1"); - assert_eq!(r, "https://opencode.ai/zen/go/v1/chat/completions"); - } - - #[test] - fn derive_base_path_should_support_no_base_path() { - let r = OpenAiProvider::derive_base_path("https://opencode.ai/"); - assert_eq!(r, "https://opencode.ai/v1/chat/completions"); - } - - #[test] - fn derive_base_path_preserves_non_v1_version_prefix() { - // Zhipu's default base_url is https://open.bigmodel.cn/api/paas/v4 and - // from_custom_config passes url.path() ("/api/paas/v4") here. The - // existing /api/paas/v4 version must not gain an extra /v1 segment. - let r = OpenAiProvider::derive_base_path("/api/paas/v4"); - assert_eq!(r, "api/paas/v4/chat/completions"); - } - - #[test] - fn derive_base_path_does_not_treat_v_word_as_version() { - let r = OpenAiProvider::derive_base_path("/api/voice"); - assert_eq!(r, "api/voice/v1/chat/completions"); - } - - #[test] - fn parse_base_url_preserves_query_params() { - let r = OpenAiProvider::parse_base_url("https://gw.example.com/v1?api-version=2024-02-01") - .unwrap(); - assert_eq!(r.host, "https://gw.example.com"); - assert_eq!( - r.query_params, - vec![("api-version".to_string(), "2024-02-01".to_string())] - ); - assert!(r.has_v1); - } - - #[test] - fn parse_base_url_preserves_multiple_query_params() { - let r = OpenAiProvider::parse_base_url("https://example.com/v1?key=val&foo=bar").unwrap(); - assert_eq!(r.query_params.len(), 2); - assert_eq!(r.query_params[0], ("key".to_string(), "val".to_string())); - assert_eq!(r.query_params[1], ("foo".to_string(), "bar".to_string())); - } - - #[test] - fn parse_base_url_preserves_credentials() { - let r = OpenAiProvider::parse_base_url("https://user:pass@gateway.example.com/v1").unwrap(); - assert_eq!(r.host, "https://user:pass@gateway.example.com"); - assert!(r.has_v1); - } - - #[test] - fn parse_base_url_rejects_empty_string() { - assert!(OpenAiProvider::parse_base_url("").is_err()); - } - - #[test] - fn parse_base_url_rejects_whitespace_only() { - assert!(OpenAiProvider::parse_base_url(" ").is_err()); - } - #[test] fn versionless_base_path_opts_out_of_responses_for_codex_models() { assert!(!OpenAiProvider::should_use_responses_api( @@ -1279,62 +918,6 @@ mod tests { )); } - // ── dynamic_models behavior ───────────────────────────────────────────── - - use crate::config::declarative_providers::{DeclarativeProviderConfig, ProviderEngine}; - use wiremock::matchers::method; - use wiremock::{Mock, MockServer, ResponseTemplate}; - - fn make_provider_with_server( - server_uri: &str, - custom_models: Option>, - dynamic_models: Option, - ) -> OpenAiProvider { - OpenAiProvider { - api_client: ApiClient::new_with_tls(server_uri.to_string(), AuthMethod::NoAuth, None) - .unwrap(), - base_path: "v1/chat/completions".to_string(), - organization: None, - project: None, - model: ModelConfig::new_or_fail("test-model"), - custom_headers: None, - supports_streaming: true, - name: "custom_test".to_string(), - custom_models, - dynamic_models, - skip_canonical_filtering: false, - preserve_thinking_context: false, - } - } - - fn base_declarative_config( - models: Vec, - dynamic_models: Option, - ) -> DeclarativeProviderConfig { - DeclarativeProviderConfig { - name: "custom_test".to_string(), - engine: ProviderEngine::OpenAI, - display_name: "Custom Test".to_string(), - description: None, - api_key_env: String::new(), - base_url: "http://localhost:1".to_string(), - models, - headers: None, - timeout_seconds: None, - supports_streaming: Some(true), - requires_auth: false, - catalog_provider_id: None, - base_path: None, - env_vars: None, - dynamic_models, - skip_canonical_filtering: false, - model_doc_link: None, - setup_steps: vec![], - fast_model: None, - preserves_thinking: false, - } - } - #[test] fn ensure_url_scheme_adds_http_for_local_hosts() { assert_eq!(ensure_url_scheme("localhost:1234"), "http://localhost:1234"); @@ -1367,134 +950,6 @@ mod tests { ); } - #[test] - fn from_custom_config_preserves_port_without_scheme() { - let mut config = - base_declarative_config(vec![ModelInfo::new("m1".to_string(), 128000)], None); - config.base_url = "localhost:1234".to_string(); - - let provider = - OpenAiProvider::from_custom_config(ModelConfig::new_or_fail("m1"), config, None) - .unwrap(); - - assert_eq!(provider.api_client.host(), "http://localhost:1234"); - assert_eq!(provider.base_path, "v1/chat/completions"); - } - - #[tokio::test] - async fn fetch_supported_models_static_only_skips_api() { - // Any request to the mock returns 500 — if the fix calls the API, the test fails. - let server = MockServer::start().await; - Mock::given(method("GET")) - .respond_with(ResponseTemplate::new(500)) - .mount(&server) - .await; - - let provider = make_provider_with_server( - &server.uri(), - Some(vec!["m1".to_string(), "m2".to_string()]), - Some(false), - ); - - let models = provider.fetch_supported_models().await.unwrap(); - assert_eq!(models, vec!["m1".to_string(), "m2".to_string()]); - } - - #[test] - fn from_custom_config_rejects_static_only_without_models() { - let config = base_declarative_config(vec![], Some(false)); - let err = OpenAiProvider::from_custom_config( - ModelConfig::new_or_fail("test-model"), - config, - None, - ) - .expect_err("expected construction error for dynamic_models: false with empty models"); - let msg = err.to_string(); - assert!( - msg.contains("dynamic_models: false"), - "error message should mention dynamic_models: false; got: {msg}" - ); - } - - // ── resolve_api_key tests ────────────────────────────────────────────── - - fn config_with_key(api_key_env: &str, requires_auth: bool) -> DeclarativeProviderConfig { - let mut config = base_declarative_config(vec![], None); - config.api_key_env = api_key_env.to_string(); - config.requires_auth = requires_auth; - config - } - - #[test] - fn resolve_api_key_empty_env_returns_none() { - let config = config_with_key("", true); - assert_eq!( - OpenAiProvider::resolve_api_key(&config, &|_| unreachable!()).unwrap(), - None - ); - } - - #[test] - fn resolve_api_key_missing_with_requires_auth_bails() { - let config = config_with_key("MY_KEY", true); - let err = OpenAiProvider::resolve_api_key(&config, &|_| { - Err(crate::config::ConfigError::NotFound("x".into())) - }) - .unwrap_err() - .to_string(); - assert!( - err.contains("MY_KEY"), - "error should mention the key name; got: {err}" - ); - } - - #[test] - fn resolve_api_key_missing_without_requires_auth_returns_none() { - let config = config_with_key("MY_KEY", false); - assert_eq!( - OpenAiProvider::resolve_api_key(&config, &|_| Err( - crate::config::ConfigError::NotFound("x".into()) - )) - .unwrap(), - None - ); - } - - #[test] - fn resolve_api_key_present_returns_value() { - let config = config_with_key("MY_KEY", true); - assert_eq!( - OpenAiProvider::resolve_api_key(&config, &|_| Ok("secret".into())).unwrap(), - Some("secret".to_string()) - ); - } - - #[test] - fn resolve_api_key_other_error_bails_when_required() { - let config = config_with_key("MY_KEY", true); - let err = OpenAiProvider::resolve_api_key(&config, &|_| { - Err(crate::config::ConfigError::KeyringError("ring fail".into())) - }) - .unwrap_err() - .to_string(); - assert!( - err.contains("MY_KEY"), - "error should mention the key name; got: {err}" - ); - } - - #[test] - fn resolve_api_key_other_error_warns_and_returns_none_when_optional() { - let config = config_with_key("MY_KEY", false); - assert_eq!( - OpenAiProvider::resolve_api_key(&config, &|_| Err( - crate::config::ConfigError::KeyringError("ring fail".into()) - )) - .unwrap(), - None - ); - } - #[test] fn parse_n_ctx_falls_back_to_sole_entry_when_id_differs() { let body = json!({ diff --git a/crates/goose/src/providers/openai_compatible.rs b/crates/goose-providers/src/openai_compatible.rs similarity index 95% rename from crates/goose/src/providers/openai_compatible.rs rename to crates/goose-providers/src/openai_compatible.rs index e62ba30b0..cc872f13c 100644 --- a/crates/goose/src/providers/openai_compatible.rs +++ b/crates/goose-providers/src/openai_compatible.rs @@ -1,8 +1,8 @@ +use crate::conversation::token_usage::ProviderUsage; +use crate::images::ImageFormat; use anyhow::Error; use async_stream::try_stream; use futures::TryStreamExt; -use goose_providers::conversation::token_usage::ProviderUsage; -use goose_providers::images::ImageFormat; use reqwest::Response; #[cfg(test)] use reqwest::StatusCode; @@ -16,13 +16,13 @@ use super::api_client::ApiClient; use super::base::{stream_from_single_message, MessageStream, Provider}; use super::retry::ProviderRetry; use crate::conversation::message::Message; -use crate::providers::formats::openai_responses::responses_api_to_streaming_message; -use goose_providers::errors::ProviderError; -use goose_providers::formats::openai::{ +use crate::errors::ProviderError; +use crate::formats::openai::{ create_request, get_usage, response_to_message, response_to_streaming_message, }; -use goose_providers::model::ModelConfig; -use goose_providers::request_log::{start_log, LoggerHandleExt, RequestLogHandle}; +use crate::formats::openai_responses::responses_api_to_streaming_message; +use crate::model::ModelConfig; +use crate::request_log::{start_log, LoggerHandleExt, RequestLogHandle}; use rmcp::model::Tool; pub struct OpenAiCompatibleProvider { @@ -228,7 +228,7 @@ pub fn stream_responses_compat( #[cfg(test)] mod tests { use super::*; - use goose_providers::model::ModelConfig; + use crate::model::ModelConfig; use serde_json::json; use test_case::test_case; diff --git a/crates/goose/src/config/declarative_providers.rs b/crates/goose/src/config/declarative_providers.rs index d3a162a2f..3ccc3aeb7 100644 --- a/crates/goose/src/config/declarative_providers.rs +++ b/crates/goose/src/config/declarative_providers.rs @@ -6,7 +6,7 @@ use crate::providers::huggingface::HuggingFaceProvider; use crate::providers::huggingface_auth; use crate::providers::inventory::declarative_inventory_identity; use crate::providers::ollama::OllamaProvider; -use crate::providers::openai::OpenAiProvider; +use crate::providers::openai_def::OpenAiProviderDef; use anyhow::Result; use include_dir::{include_dir, Dir}; use once_cell::sync::Lazy; @@ -604,14 +604,14 @@ pub fn register_declarative_provider( }, ); } else { - registry.register_with_name::( + registry.register_with_name::( &config, provider_type, config.dynamic_models.unwrap_or(false), move |model, tls_config| { let mut cfg = captured.clone(); resolve_config(&mut cfg)?; - OpenAiProvider::from_custom_config(model, cfg, tls_config) + crate::providers::openai_def::from_custom_config(model, cfg, tls_config) }, move || { let mut cfg = identity_config.clone(); diff --git a/crates/goose/src/providers/amp_acp.rs b/crates/goose/src/providers/amp_acp.rs index 0082df2d3..beae52173 100644 --- a/crates/goose/src/providers/amp_acp.rs +++ b/crates/goose/src/providers/amp_acp.rs @@ -8,7 +8,9 @@ use crate::acp::{ }; use crate::config::search_path::SearchPaths; use crate::config::{Config, GooseMode}; -use crate::providers::base::{current_working_dir, ProviderDef, ProviderMetadata}; +use crate::providers::base::{ + current_working_dir, ProviderDef, ProviderDescriptor, ProviderMetadata, +}; use goose_providers::model::ModelConfig; pub(crate) const AMP_ACP_PROVIDER_NAME: &str = "amp-acp"; @@ -17,9 +19,7 @@ pub(crate) const AMP_ACP_BINARY: &str = "amp-acp"; pub struct AmpAcpProvider; -impl ProviderDef for AmpAcpProvider { - type Provider = AcpProvider; - +impl goose_providers::base::ProviderDescriptor for AmpAcpProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( AMP_ACP_PROVIDER_NAME, @@ -39,6 +39,10 @@ impl ProviderDef for AmpAcpProvider { ]) .with_model_selection_hint("Use the Amp CLI to configure models") } +} + +impl ProviderDef for AmpAcpProvider { + type Provider = AcpProvider; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/anthropic.rs b/crates/goose/src/providers/anthropic.rs index 519f57105..15d2d53af 100644 --- a/crates/goose/src/providers/anthropic.rs +++ b/crates/goose/src/providers/anthropic.rs @@ -2,6 +2,7 @@ use anyhow::Result; use async_stream::try_stream; use async_trait::async_trait; use futures::TryStreamExt; +use goose_providers::base::ProviderDescriptor; use goose_providers::errors::ProviderError; use goose_providers::request_log::{start_log, LoggerHandleExt}; use reqwest::StatusCode; @@ -234,9 +235,7 @@ impl AnthropicProvider { } } -impl ProviderDef for AnthropicProvider { - type Provider = Self; - +impl ProviderDescriptor for AnthropicProvider { fn metadata() -> ProviderMetadata { let models: Vec = ANTHROPIC_KNOWN_MODELS .iter() @@ -267,6 +266,10 @@ impl ProviderDef for AnthropicProvider { "Copy the key and paste it above", ]) } +} + +impl ProviderDef for AnthropicProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/avian.rs b/crates/goose/src/providers/avian.rs index ad179b5ed..17c8e7779 100644 --- a/crates/goose/src/providers/avian.rs +++ b/crates/goose/src/providers/avian.rs @@ -18,9 +18,7 @@ pub const AVIAN_DOC_URL: &str = "https://avian.io/docs"; pub struct AvianProvider; -impl ProviderDef for AvianProvider { - type Provider = OpenAiCompatibleProvider; - +impl goose_providers::base::ProviderDescriptor for AvianProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( AVIAN_PROVIDER_NAME, @@ -35,6 +33,10 @@ impl ProviderDef for AvianProvider { ], ) } +} + +impl ProviderDef for AvianProvider { + type Provider = OpenAiCompatibleProvider; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/azure.rs b/crates/goose/src/providers/azure.rs index b2e096a61..c217b4dbf 100644 --- a/crates/goose/src/providers/azure.rs +++ b/crates/goose/src/providers/azure.rs @@ -50,9 +50,7 @@ impl AuthProvider for AzureAuthProvider { } } -impl ProviderDef for AzureProvider { - type Provider = OpenAiCompatibleProvider; - +impl goose_providers::base::ProviderDescriptor for AzureProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( AZURE_PROVIDER_NAME, @@ -70,6 +68,10 @@ impl ProviderDef for AzureProvider { ], ) } +} + +impl ProviderDef for AzureProvider { + type Provider = OpenAiCompatibleProvider; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/base.rs b/crates/goose/src/providers/base.rs index d64e7309e..c42c97e52 100644 --- a/crates/goose/src/providers/base.rs +++ b/crates/goose/src/providers/base.rs @@ -6,25 +6,16 @@ pub use goose_providers::conversation::token_usage::{ }; use serde::{Deserialize, Serialize}; -/// Default HTTP timeout for all provider API calls. -/// Long-running model inference can take several minutes, so we allow up to 10 minutes -/// before giving up. Individual providers may override this via their own config key. pub const DEFAULT_PROVIDER_TIMEOUT_SECS: u64 = 600; -use crate::config::base::ConfigValue; use crate::config::ExtensionConfig; use goose_providers::model::ModelConfig; use utoipa::ToSchema; -use once_cell::sync::Lazy; use std::path::PathBuf; -use std::sync::Mutex; pub use goose_providers::base::*; -/// A global store for the current model being used, we use this as when a provider returns, it tells us the real model, not an alias -pub static CURRENT_MODEL: Lazy>> = Lazy::new(|| Mutex::new(None)); - #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)] pub enum ProviderType { Preferred, @@ -33,216 +24,13 @@ pub enum ProviderType { Custom, } -/// Metadata about a provider's configuration requirements and capabilities -#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] -pub struct ProviderMetadata { - /// The unique identifier for this provider - pub name: String, - /// Display name for the provider in UIs - pub display_name: String, - /// Description of the provider's capabilities - pub description: String, - /// The default/recommended model for this provider - pub default_model: String, - /// A list of currently known models with their capabilities - pub known_models: Vec, - /// Link to the docs where models can be found - pub model_doc_link: String, - /// Required configuration keys - pub config_keys: Vec, - /// step-by-step instructions for set up providers eg: api key - #[serde(default)] - pub setup_steps: Vec, - /// Hint shown in the model picker when this provider manages its own model selection. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub model_selection_hint: Option, -} - -impl ProviderMetadata { - pub fn new( - name: &str, - display_name: &str, - description: &str, - default_model: &str, - model_names: Vec<&str>, - model_doc_link: &str, - config_keys: Vec, - ) -> Self { - Self { - name: name.to_string(), - display_name: display_name.to_string(), - description: description.to_string(), - default_model: default_model.to_string(), - known_models: model_names - .iter() - .map(|&model_name| model_info_for_provider_model(name, model_name)) - .collect(), - model_doc_link: model_doc_link.to_string(), - config_keys, - setup_steps: vec![], - model_selection_hint: None, - } - } - - pub fn with_models( - name: &str, - display_name: &str, - description: &str, - default_model: &str, - models: Vec, - model_doc_link: &str, - config_keys: Vec, - ) -> Self { - Self { - name: name.to_string(), - display_name: display_name.to_string(), - description: description.to_string(), - default_model: default_model.to_string(), - known_models: models, - model_doc_link: model_doc_link.to_string(), - config_keys, - setup_steps: vec![], - model_selection_hint: None, - } - } - - pub fn empty() -> Self { - Self { - name: "".to_string(), - display_name: "".to_string(), - description: "".to_string(), - default_model: "".to_string(), - known_models: vec![], - model_doc_link: "".to_string(), - config_keys: vec![], - setup_steps: vec![], - model_selection_hint: None, - } - } - - pub fn with_setup_steps(mut self, steps: Vec<&str>) -> Self { - self.setup_steps = steps.into_iter().map(|s| s.to_string()).collect(); - self - } - - pub fn with_model_selection_hint(mut self, hint: &str) -> Self { - self.model_selection_hint = Some(hint.to_string()); - self - } -} - -/// Configuration key metadata for provider setup -#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] -pub struct ConfigKey { - /// The name of the configuration key (e.g., "API_KEY") - pub name: String, - /// Whether this key is required for the provider to function - pub required: bool, - /// Whether this key should be stored securely (e.g., in keychain) - pub secret: bool, - /// Optional default value for the key - pub default: Option, - /// Whether this key should be configured using an OAuth flow - /// When true, the provider's configure_oauth() method will be called instead of prompting for manual input - pub oauth_flow: bool, - /// Whether this OAuth flow uses the device code grant (RFC 8628) - /// When true, the user must enter a verification code in the browser - #[serde(default)] - pub device_code_flow: bool, - /// Whether this key should be shown prominently during provider setup - /// (onboarding, settings modal, CLI configure) - #[serde(default)] - pub primary: bool, -} - -impl ConfigKey { - /// Create a new ConfigKey - pub fn new( - name: &str, - required: bool, - secret: bool, - default: Option<&str>, - primary: bool, - ) -> Self { - Self { - name: name.to_string(), - required, - secret, - default: default.map(|s| s.to_string()), - oauth_flow: false, - device_code_flow: false, - primary, - } - } - - pub fn from_value_type(required: bool, secret: bool, primary: bool) -> Self { - Self { - name: T::KEY.to_string(), - required, - secret, - default: Some(T::DEFAULT.to_string()), - oauth_flow: false, - device_code_flow: false, - primary, - } - } - - /// Create a new ConfigKey that uses an OAuth flow for configuration - /// - /// This is used for providers that support OAuth authentication instead of manual API key entry. - /// When oauth_flow is true, the configuration system will call the provider's configure_oauth() method. - pub fn new_oauth( - name: &str, - required: bool, - secret: bool, - default: Option<&str>, - primary: bool, - ) -> Self { - Self { - name: name.to_string(), - required, - secret, - default: default.map(|s| s.to_string()), - oauth_flow: true, - device_code_flow: false, - primary, - } - } - - /// Create a new ConfigKey that uses OAuth device code flow (RFC 8628) for configuration - /// - /// Similar to new_oauth, but indicates the provider uses the device code grant where the user - /// must enter a verification code in the browser. - pub fn new_oauth_device_code( - name: &str, - required: bool, - secret: bool, - default: Option<&str>, - primary: bool, - ) -> Self { - Self { - name: name.to_string(), - required, - secret, - default: default.map(|s| s.to_string()), - oauth_flow: true, - device_code_flow: true, - primary, - } - } -} - pub(crate) fn current_working_dir() -> PathBuf { std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")) } -pub trait ProviderDef: Send + Sync { +pub trait ProviderDef: ProviderDescriptor + Send + Sync { type Provider: Provider + 'static; - fn metadata() -> ProviderMetadata - where - Self: Sized; - fn from_env( model: ModelConfig, extensions: Vec, @@ -260,47 +48,6 @@ pub trait ProviderDef: Send + Sync { where Self: Sized, { - // ACP subprocess providers must override this so session cwd is preserved. - // Non-subprocess providers can rely on the default because cwd is irrelevant. Self::from_env(model, extensions, tls_config) } } - -#[cfg(test)] -mod tests { - use super::*; - use std::collections::HashMap; - - #[test] - fn test_provider_metadata_context_limits() { - // Test that ProviderMetadata::new correctly sets context limits - let test_models = vec!["gpt-4o", "claude-sonnet-4-20250514", "unknown-model"]; - let metadata = ProviderMetadata::new( - "test", - "Test Provider", - "Test Description", - "gpt-4o", - test_models, - "https://example.com", - vec![], - ); - - let model_info: HashMap = metadata - .known_models - .into_iter() - .map(|m| (m.name, m.context_limit)) - .collect(); - - // gpt-4o should have 128k limit - assert_eq!(*model_info.get("gpt-4o").unwrap(), 128_000); - - // claude-sonnet-4-20250514 should have 200k limit - assert_eq!( - *model_info.get("claude-sonnet-4-20250514").unwrap(), - 200_000 - ); - - // unknown model should have default limit (128k) - assert_eq!(*model_info.get("unknown-model").unwrap(), 128_000); - } -} diff --git a/crates/goose/src/providers/bedrock.rs b/crates/goose/src/providers/bedrock.rs index 0193c6652..c06347e07 100644 --- a/crates/goose/src/providers/bedrock.rs +++ b/crates/goose/src/providers/bedrock.rs @@ -1,7 +1,6 @@ use std::collections::HashMap; use super::base::{ConfigKey, MessageStream, Provider, ProviderDef, ProviderMetadata}; -use super::formats::openai_responses::create_responses_request; use super::openai_compatible::{handle_status, stream_responses_compat}; use super::retry::{ProviderRetry, RetryConfig}; use crate::conversation::message::Message; @@ -19,6 +18,7 @@ use futures::future::BoxFuture; use goose_providers::conversation::token_usage::{ProviderUsage, Usage}; use goose_providers::errors::ProviderError; use goose_providers::formats::openai::extract_reasoning_effort; +use goose_providers::formats::openai_responses::create_responses_request; use goose_providers::model::ModelConfig; use goose_providers::request_log::{start_log, LoggerHandleExt}; use reqwest::header::{HeaderName, HeaderValue, AUTHORIZATION}; @@ -683,9 +683,7 @@ fn process_stream_event( (messages, usage) } -impl ProviderDef for BedrockProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for BedrockProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( BEDROCK_PROVIDER_NAME, @@ -709,6 +707,10 @@ impl ProviderDef for BedrockProvider { ], ) } +} + +impl ProviderDef for BedrockProvider { + type Provider = Self; fn from_env( model: ModelConfig, @@ -904,6 +906,7 @@ impl Provider for BedrockProvider { #[cfg(test)] mod tests { use super::*; + use goose_providers::base::ProviderDescriptor as _; use serial_test::serial; fn create_mock_provider(model_name: &str) -> BedrockProvider { diff --git a/crates/goose/src/providers/chatgpt_codex.rs b/crates/goose/src/providers/chatgpt_codex.rs index cd414a8fe..ff6213d86 100644 --- a/crates/goose/src/providers/chatgpt_codex.rs +++ b/crates/goose/src/providers/chatgpt_codex.rs @@ -2,7 +2,6 @@ use crate::config::paths::Paths; use crate::conversation::message::{Message, MessageContent}; use crate::providers::api_client::AuthProvider; use crate::providers::base::{ConfigKey, MessageStream, Provider, ProviderDef, ProviderMetadata}; -use crate::providers::formats::openai_responses::responses_api_to_streaming_message; use crate::providers::openai_compatible::handle_status; use crate::providers::retry::ProviderRetry; use crate::session_context::SESSION_ID_HEADER; @@ -15,6 +14,7 @@ use chrono::{DateTime, Utc}; use futures::future::BoxFuture; use futures::{StreamExt, TryStreamExt}; use goose_providers::errors::ProviderError; +use goose_providers::formats::openai_responses::responses_api_to_streaming_message; use goose_providers::model::ModelConfig; use jsonwebtoken::jwk::JwkSet; use jsonwebtoken::{decode, decode_header, DecodingKey, Validation}; @@ -951,9 +951,7 @@ impl ChatGptCodexProvider { } } -impl ProviderDef for ChatGptCodexProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for ChatGptCodexProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( CHATGPT_CODEX_PROVIDER_NAME, @@ -971,6 +969,10 @@ impl ProviderDef for ChatGptCodexProvider { )], ) } +} + +impl ProviderDef for ChatGptCodexProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/claude_acp.rs b/crates/goose/src/providers/claude_acp.rs index 839e42fd5..f3ab9d0e2 100644 --- a/crates/goose/src/providers/claude_acp.rs +++ b/crates/goose/src/providers/claude_acp.rs @@ -8,7 +8,9 @@ use crate::acp::{ }; use crate::config::search_path::SearchPaths; use crate::config::{Config, GooseMode}; -use crate::providers::base::{current_working_dir, ProviderDef, ProviderMetadata}; +use crate::providers::base::{ + current_working_dir, ProviderDef, ProviderDescriptor, ProviderMetadata, +}; use goose_providers::model::ModelConfig; pub(crate) const CLAUDE_ACP_PROVIDER_NAME: &str = "claude-acp"; @@ -17,9 +19,7 @@ pub(crate) const CLAUDE_ACP_BINARY: &str = "claude-agent-acp"; pub struct ClaudeAcpProvider; -impl ProviderDef for ClaudeAcpProvider { - type Provider = AcpProvider; - +impl goose_providers::base::ProviderDescriptor for ClaudeAcpProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( CLAUDE_ACP_PROVIDER_NAME, @@ -37,6 +37,10 @@ impl ProviderDef for ClaudeAcpProvider { "Restart goose for changes to take effect", ]) } +} + +impl ProviderDef for ClaudeAcpProvider { + type Provider = AcpProvider; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/claude_code.rs b/crates/goose/src/providers/claude_code.rs index 63bc7388e..55377997e 100644 --- a/crates/goose/src/providers/claude_code.rs +++ b/crates/goose/src/providers/claude_code.rs @@ -22,7 +22,6 @@ use super::base::{ ProviderMetadata, }; use super::utils::filter_extensions_from_system_prompt; -use crate::config::base::ClaudeCodeCommand; use crate::config::paths::Paths; use crate::config::search_path::SearchPaths; use crate::config::{Config, ExtensionConfig, GooseMode}; @@ -583,9 +582,7 @@ fn write_mcp_config_file(state_dir: &Path, json: &str) -> Result ProviderMetadata { ProviderMetadata::new( CLAUDE_CODE_PROVIDER_NAME, @@ -595,11 +592,19 @@ impl ProviderDef for ClaudeCodeProvider { // Only a few agentic choices; fetched dynamically via fetch_supported_models. vec![], CLAUDE_CODE_DOC_URL, - vec![ConfigKey::from_value_type::( - true, false, true, + vec![ConfigKey::new( + "CLAUDE_CODE_COMMAND", + true, + false, + Some("claude"), + true, )], ) } +} + +impl ProviderDef for ClaudeCodeProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/codex.rs b/crates/goose/src/providers/codex.rs index 47456296b..fad5ce799 100644 --- a/crates/goose/src/providers/codex.rs +++ b/crates/goose/src/providers/codex.rs @@ -15,7 +15,6 @@ use tokio::process::Command; use super::base::{ConfigKey, MessageStream, Provider, ProviderDef, ProviderMetadata}; use super::utils::filter_extensions_from_system_prompt; -use crate::config::base::{CodexCommand, CodexSkipGitCheck}; use crate::config::paths::Paths; use crate::config::search_path::SearchPaths; use crate::config::{Config, ExtensionConfig, GooseMode}; @@ -622,9 +621,7 @@ fn codex_mcp_config_overrides(extensions: &[ExtensionConfig]) -> Vec { overrides } -impl ProviderDef for CodexProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for CodexProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( CODEX_PROVIDER_NAME, @@ -634,11 +631,15 @@ impl ProviderDef for CodexProvider { CODEX_KNOWN_MODELS.to_vec(), CODEX_DOC_URL, vec![ - ConfigKey::from_value_type::(true, false, true), - ConfigKey::from_value_type::(false, false, true), + ConfigKey::new("CODEX_COMMAND", true, false, Some("codex"), true), + ConfigKey::new("CODEX_SKIP_GIT_CHECK", false, false, Some("false"), true), ], ) } +} + +impl ProviderDef for CodexProvider { + type Provider = Self; fn from_env( model: ModelConfig, @@ -760,6 +761,7 @@ impl Provider for CodexProvider { mod tests { use super::*; use crate::agents::extension::Envs; + use goose_providers::base::ProviderDescriptor as _; use goose_test_support::TEST_IMAGE_B64; use std::collections::HashMap; use test_case::test_case; diff --git a/crates/goose/src/providers/codex_acp.rs b/crates/goose/src/providers/codex_acp.rs index 83b3095fc..7a3698fb6 100644 --- a/crates/goose/src/providers/codex_acp.rs +++ b/crates/goose/src/providers/codex_acp.rs @@ -8,7 +8,9 @@ use crate::acp::{ }; use crate::config::search_path::SearchPaths; use crate::config::{Config, GooseMode}; -use crate::providers::base::{current_working_dir, ProviderDef, ProviderMetadata}; +use crate::providers::base::{ + current_working_dir, ProviderDef, ProviderDescriptor, ProviderMetadata, +}; use goose_providers::model::ModelConfig; pub(crate) const CODEX_ACP_PROVIDER_NAME: &str = "codex-acp"; @@ -16,9 +18,7 @@ const CODEX_ACP_DOC_URL: &str = "https://github.com/zed-industries/codex-acp"; pub struct CodexAcpProvider; -impl ProviderDef for CodexAcpProvider { - type Provider = AcpProvider; - +impl goose_providers::base::ProviderDescriptor for CodexAcpProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( CODEX_ACP_PROVIDER_NAME, @@ -36,6 +36,10 @@ impl ProviderDef for CodexAcpProvider { "Restart goose for changes to take effect", ]) } +} + +impl ProviderDef for CodexAcpProvider { + type Provider = AcpProvider; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/copilot_acp.rs b/crates/goose/src/providers/copilot_acp.rs index db41641e8..a2f732aa4 100644 --- a/crates/goose/src/providers/copilot_acp.rs +++ b/crates/goose/src/providers/copilot_acp.rs @@ -8,7 +8,9 @@ use crate::acp::{ }; use crate::config::search_path::SearchPaths; use crate::config::{Config, GooseMode}; -use crate::providers::base::{current_working_dir, ProviderDef, ProviderMetadata}; +use crate::providers::base::{ + current_working_dir, ProviderDef, ProviderDescriptor, ProviderMetadata, +}; use goose_providers::model::ModelConfig; pub(crate) const COPILOT_ACP_PROVIDER_NAME: &str = "copilot-acp"; @@ -20,9 +22,7 @@ const MODE_PLAN: &str = "https://agentclientprotocol.com/protocol/session-modes# pub struct CopilotAcpProvider; -impl ProviderDef for CopilotAcpProvider { - type Provider = AcpProvider; - +impl goose_providers::base::ProviderDescriptor for CopilotAcpProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( COPILOT_ACP_PROVIDER_NAME, @@ -40,6 +40,10 @@ impl ProviderDef for CopilotAcpProvider { "Restart goose for changes to take effect", ]) } +} + +impl ProviderDef for CopilotAcpProvider { + type Provider = AcpProvider; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/cursor_agent.rs b/crates/goose/src/providers/cursor_agent.rs index 7b8a4468f..d275d4435 100644 --- a/crates/goose/src/providers/cursor_agent.rs +++ b/crates/goose/src/providers/cursor_agent.rs @@ -11,7 +11,6 @@ use super::base::{ stream_from_single_message, ConfigKey, MessageStream, Provider, ProviderDef, ProviderMetadata, }; use super::utils::filter_extensions_from_system_prompt; -use crate::config::base::CursorAgentCommand; use crate::config::search_path::SearchPaths; use crate::conversation::message::{Message, MessageContent}; use crate::subprocess::configure_subprocess; @@ -280,9 +279,7 @@ impl CursorAgentProvider { } } -impl ProviderDef for CursorAgentProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for CursorAgentProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( CURSOR_AGENT_PROVIDER_NAME, @@ -291,11 +288,19 @@ impl ProviderDef for CursorAgentProvider { CURSOR_AGENT_DEFAULT_MODEL, CURSOR_AGENT_KNOWN_MODELS.to_vec(), CURSOR_AGENT_DOC_URL, - vec![ConfigKey::from_value_type::( - true, false, true, + vec![ConfigKey::new( + "CURSOR_AGENT_COMMAND", + true, + false, + Some("cursor-agent"), + true, )], ) } +} + +impl ProviderDef for CursorAgentProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/databricks.rs b/crates/goose/src/providers/databricks.rs index 683337d1a..012a39d4b 100644 --- a/crates/goose/src/providers/databricks.rs +++ b/crates/goose/src/providers/databricks.rs @@ -18,7 +18,6 @@ use super::base::{ }; use super::databricks_auth::{DatabricksAuth, DatabricksAuthProvider}; use super::formats::databricks::{create_request_for_provider, DATABRICKS_PROVIDER_NAME}; -use super::formats::openai_responses::create_responses_request; use super::openai_compatible::{ handle_status, map_http_error_to_provider_error, sanitize_url, stream_openai_compat, stream_responses_compat, @@ -32,6 +31,7 @@ use crate::providers::retry::{ DEFAULT_MAX_RETRIES, DEFAULT_MAX_RETRY_INTERVAL_MS, }; use goose_providers::errors::ProviderError; +use goose_providers::formats::openai_responses::create_responses_request; use goose_providers::model::ModelConfig; use goose_providers::request_log::{start_log, LoggerHandleExt}; use rmcp::model::Tool; @@ -525,9 +525,7 @@ impl DatabricksProvider { } } -impl ProviderDef for DatabricksProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for DatabricksProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( DATABRICKS_PROVIDER_NAME, @@ -542,6 +540,10 @@ impl ProviderDef for DatabricksProvider { ], ) } +} + +impl ProviderDef for DatabricksProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/databricks_v2.rs b/crates/goose/src/providers/databricks_v2.rs index fb6ee4d8b..2c1d4b30c 100644 --- a/crates/goose/src/providers/databricks_v2.rs +++ b/crates/goose/src/providers/databricks_v2.rs @@ -19,7 +19,7 @@ use super::base::{ DEFAULT_PROVIDER_TIMEOUT_SECS, }; use super::databricks_auth::{DatabricksAuth, DatabricksAuthProvider}; -use super::formats::{anthropic, openai_responses}; +use super::formats::anthropic; use super::openai_compatible::{handle_status, stream_openai_compat, stream_responses_compat}; use super::retry::ProviderRetry; use crate::config::ConfigError; @@ -29,6 +29,7 @@ use crate::providers::retry::{ DEFAULT_MAX_RETRIES, DEFAULT_MAX_RETRY_INTERVAL_MS, }; use goose_providers::errors::ProviderError; +use goose_providers::formats::openai_responses; use goose_providers::model::ModelConfig; use goose_providers::request_log::{start_log, LoggerHandleExt}; use rmcp::model::Tool; @@ -333,9 +334,7 @@ impl DatabricksV2Provider { } } -impl ProviderDef for DatabricksV2Provider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for DatabricksV2Provider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( DATABRICKS_V2_PROVIDER_NAME, @@ -350,6 +349,10 @@ impl ProviderDef for DatabricksV2Provider { ], ) } +} + +impl ProviderDef for DatabricksV2Provider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/formats/mod.rs b/crates/goose/src/providers/formats/mod.rs index abfbf25a6..ed5a9c535 100644 --- a/crates/goose/src/providers/formats/mod.rs +++ b/crates/goose/src/providers/formats/mod.rs @@ -5,6 +5,5 @@ pub mod databricks; pub mod gcpvertexai; pub mod google; pub mod ollama; -pub mod openai_responses; pub mod openrouter; pub mod snowflake; diff --git a/crates/goose/src/providers/gcpvertexai.rs b/crates/goose/src/providers/gcpvertexai.rs index 2d3dc654a..88a3dae63 100644 --- a/crates/goose/src/providers/gcpvertexai.rs +++ b/crates/goose/src/providers/gcpvertexai.rs @@ -528,9 +528,7 @@ impl GcpVertexAIProvider { } } -impl ProviderDef for GcpVertexAIProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for GcpVertexAIProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( GCP_VERTEX_AI_PROVIDER_NAME, @@ -579,6 +577,10 @@ impl ProviderDef for GcpVertexAIProvider { ], ) } +} + +impl ProviderDef for GcpVertexAIProvider { + type Provider = Self; fn from_env( model: ModelConfig, @@ -662,6 +664,7 @@ impl Provider for GcpVertexAIProvider { #[cfg(test)] mod tests { use super::*; + use goose_providers::base::ProviderDescriptor as _; use reqwest::StatusCode; #[test] diff --git a/crates/goose/src/providers/gemini_cli.rs b/crates/goose/src/providers/gemini_cli.rs index 30b51fa8a..d834b80a4 100644 --- a/crates/goose/src/providers/gemini_cli.rs +++ b/crates/goose/src/providers/gemini_cli.rs @@ -12,7 +12,6 @@ use super::base::{ }; use super::cli_common::{error_from_event, extract_usage_tokens}; use super::utils::filter_extensions_from_system_prompt; -use crate::config::base::GeminiCliCommand; use crate::config::search_path::SearchPaths; use crate::config::Config; use crate::conversation::message::{Message, MessageContent}; @@ -157,9 +156,7 @@ impl GeminiCliProvider { } } -impl ProviderDef for GeminiCliProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for GeminiCliProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( GEMINI_CLI_PROVIDER_NAME, @@ -168,11 +165,19 @@ impl ProviderDef for GeminiCliProvider { GEMINI_CLI_DEFAULT_MODEL, GEMINI_CLI_KNOWN_MODELS.to_vec(), GEMINI_CLI_DOC_URL, - vec![ConfigKey::from_value_type::( - true, false, true, + vec![ConfigKey::new( + "GEMINI_CLI_COMMAND", + true, + false, + Some("gemini"), + true, )], ) } +} + +impl ProviderDef for GeminiCliProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/gemini_oauth.rs b/crates/goose/src/providers/gemini_oauth.rs index f7af107fc..92b24cc24 100644 --- a/crates/goose/src/providers/gemini_oauth.rs +++ b/crates/goose/src/providers/gemini_oauth.rs @@ -935,9 +935,7 @@ impl GeminiOAuthProvider { } } -impl ProviderDef for GeminiOAuthProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for GeminiOAuthProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( GEMINI_OAUTH_PROVIDER_NAME, @@ -955,6 +953,10 @@ impl ProviderDef for GeminiOAuthProvider { )], ) } +} + +impl ProviderDef for GeminiOAuthProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/githubcopilot.rs b/crates/goose/src/providers/githubcopilot.rs index b8c65821e..a9c2024a1 100644 --- a/crates/goose/src/providers/githubcopilot.rs +++ b/crates/goose/src/providers/githubcopilot.rs @@ -27,11 +27,11 @@ tokio::task_local! { use super::base::{ collect_stream, Provider, ProviderDef, ProviderMetadata, DEFAULT_PROVIDER_TIMEOUT_SECS, }; -use super::formats::openai_responses::create_responses_request; use super::openai_compatible::handle_response_openai_compat; use super::retry::ProviderRetry; use super::utils::get_model; use goose_providers::formats::openai::{create_request, get_usage, response_to_message}; +use goose_providers::formats::openai_responses::create_responses_request; use crate::config::{Config, ConfigError}; use crate::conversation::message::{Message, MessageContent}; @@ -530,9 +530,7 @@ impl GithubCopilotProvider { } } -impl ProviderDef for GithubCopilotProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for GithubCopilotProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( GITHUB_COPILOT_PROVIDER_NAME, @@ -549,6 +547,10 @@ impl ProviderDef for GithubCopilotProvider { ], ) } +} + +impl ProviderDef for GithubCopilotProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/google.rs b/crates/goose/src/providers/google.rs index 251c3d240..6d2be4b78 100644 --- a/crates/goose/src/providers/google.rs +++ b/crates/goose/src/providers/google.rs @@ -112,9 +112,7 @@ impl GoogleProvider { } } -impl ProviderDef for GoogleProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for GoogleProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( GOOGLE_PROVIDER_NAME, @@ -135,6 +133,10 @@ impl ProviderDef for GoogleProvider { "Copy the key and paste it above", ]) } +} + +impl ProviderDef for GoogleProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/huggingface.rs b/crates/goose/src/providers/huggingface.rs index c72ac3def..2d071ede9 100644 --- a/crates/goose/src/providers/huggingface.rs +++ b/crates/goose/src/providers/huggingface.rs @@ -181,9 +181,7 @@ impl Provider for HuggingFaceProvider { } } -impl ProviderDef for HuggingFaceProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for HuggingFaceProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( huggingface_auth::HUGGINGFACE_PROVIDER_NAME, @@ -204,6 +202,10 @@ impl ProviderDef for HuggingFaceProvider { ], ) } +} + +impl ProviderDef for HuggingFaceProvider { + type Provider = Self; fn from_env( model: ModelConfig, @@ -373,6 +375,8 @@ fn completions_prefix(path: &str) -> String { #[cfg(test)] mod tests { + use goose_providers::base::ProviderDescriptor as _; + use super::*; use crate::providers::base::ModelInfo; diff --git a/crates/goose/src/providers/init.rs b/crates/goose/src/providers/init.rs index 48935e790..e42e05822 100644 --- a/crates/goose/src/providers/init.rs +++ b/crates/goose/src/providers/init.rs @@ -32,7 +32,6 @@ use super::{ litellm::LiteLLMProvider, nanogpt::NanoGptProvider, ollama::OllamaProvider, - openai::OpenAiProvider, openrouter::OpenRouterProvider, pi_acp::PiAcpProvider, provider_registry::ProviderRegistry, @@ -43,6 +42,7 @@ use super::{ }; use crate::config::ExtensionConfig; use crate::providers::base::ProviderType; +use crate::providers::openai_def::OpenAiProviderDef; use crate::{ config::declarative_providers::register_declarative_providers, providers::provider_registry::ProviderEntry, @@ -120,7 +120,7 @@ async fn init_registry() -> RwLock { true, Some(registrations::ollama_inventory()), ); - registry.register_with_inventory::( + registry.register_with_inventory::( true, Some(registrations::openai_inventory()), ); diff --git a/crates/goose/src/providers/inventory/registrations.rs b/crates/goose/src/providers/inventory/registrations.rs index f85c2639a..d51cc63bb 100644 --- a/crates/goose/src/providers/inventory/registrations.rs +++ b/crates/goose/src/providers/inventory/registrations.rs @@ -5,7 +5,7 @@ use super::{ use crate::config::Config; use crate::providers::acp_tooling::{acp_adapter_installed, resolved_acp_command}; use crate::providers::amp_acp::{AMP_ACP_BINARY, AMP_ACP_PROVIDER_NAME}; -use crate::providers::base::ProviderDef; +use crate::providers::base::ProviderDescriptor; use crate::providers::chatgpt_codex::TokenCache as ChatGptCodexTokenCache; use crate::providers::claude_acp::{CLAUDE_ACP_BINARY, CLAUDE_ACP_PROVIDER_NAME}; use crate::providers::codex_acp::CODEX_ACP_PROVIDER_NAME; diff --git a/crates/goose/src/providers/kimicode.rs b/crates/goose/src/providers/kimicode.rs index 92352c7f2..6781ddfd9 100644 --- a/crates/goose/src/providers/kimicode.rs +++ b/crates/goose/src/providers/kimicode.rs @@ -343,9 +343,7 @@ impl KimiCodeProvider { // ── ProviderDef ─────────────────────────────────────────────────────────────── -impl ProviderDef for KimiCodeProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for KimiCodeProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( KIMI_CODE_PROVIDER_NAME, @@ -371,6 +369,10 @@ impl ProviderDef for KimiCodeProvider { "Once authorized, Goose will save your token automatically", ]) } +} + +impl ProviderDef for KimiCodeProvider { + type Provider = Self; fn from_env( model: ModelConfig, @@ -495,6 +497,7 @@ impl Provider for KimiCodeProvider { mod tests { use super::*; use chrono::Utc; + use goose_providers::base::ProviderDescriptor as _; use serde_json::json; use wiremock::matchers::{body_string_contains, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; diff --git a/crates/goose/src/providers/litellm.rs b/crates/goose/src/providers/litellm.rs index b0aeff714..ed446ee29 100644 --- a/crates/goose/src/providers/litellm.rs +++ b/crates/goose/src/providers/litellm.rs @@ -155,9 +155,7 @@ impl LiteLLMProvider { } } -impl ProviderDef for LiteLLMProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for LiteLLMProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( LITELLM_PROVIDER_NAME, @@ -187,6 +185,10 @@ impl ProviderDef for LiteLLMProvider { ], ) } +} + +impl ProviderDef for LiteLLMProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/local_inference.rs b/crates/goose/src/providers/local_inference.rs index 0f821d519..e0d131c50 100644 --- a/crates/goose/src/providers/local_inference.rs +++ b/crates/goose/src/providers/local_inference.rs @@ -493,9 +493,7 @@ impl LocalInferenceProvider { } } -impl ProviderDef for LocalInferenceProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for LocalInferenceProvider { fn metadata() -> ProviderMetadata where Self: Sized, @@ -528,6 +526,10 @@ impl ProviderDef for LocalInferenceProvider { vec![], ) } +} + +impl ProviderDef for LocalInferenceProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/mod.rs b/crates/goose/src/providers/mod.rs index da1eeed45..a58731c28 100644 --- a/crates/goose/src/providers/mod.rs +++ b/crates/goose/src/providers/mod.rs @@ -35,7 +35,9 @@ pub mod gemini_cli; pub mod gemini_oauth; pub mod githubcopilot; pub mod google; -pub mod http_status; +pub mod http_status { + pub use goose_providers::http_status::*; +} pub mod huggingface; pub mod huggingface_auth; mod init; @@ -48,8 +50,12 @@ pub mod nanogpt; pub mod oauth; pub mod oauth_device_flow; pub mod ollama; -pub mod openai; -pub mod openai_compatible; +pub mod openai { + pub use goose_providers::openai::*; +} +pub mod openai_compatible { + pub use goose_providers::openai_compatible::*; +} pub mod openrouter; pub mod pi_acp; pub mod provider_registry; @@ -57,6 +63,7 @@ pub mod provider_test; mod retry { pub use goose_providers::retry::*; } +pub mod openai_def; #[cfg(feature = "aws-providers")] pub mod sagemaker_tgi; pub mod snowflake; diff --git a/crates/goose/src/providers/nanogpt.rs b/crates/goose/src/providers/nanogpt.rs index eb83cb29c..3b9371667 100644 --- a/crates/goose/src/providers/nanogpt.rs +++ b/crates/goose/src/providers/nanogpt.rs @@ -89,9 +89,7 @@ impl NanoGptProvider { } } -impl ProviderDef for NanoGptProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for NanoGptProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( NANOGPT_PROVIDER_NAME, @@ -103,6 +101,10 @@ impl ProviderDef for NanoGptProvider { vec![ConfigKey::new(NANOGPT_API_KEY, true, true, None, true)], ) } +} + +impl ProviderDef for NanoGptProvider { + type Provider = Self; fn from_env( model: ModelConfig, @@ -218,6 +220,7 @@ impl Provider for NanoGptProvider { #[cfg(test)] mod tests { use super::*; + use goose_providers::base::ProviderDescriptor as _; #[test] fn test_metadata() { diff --git a/crates/goose/src/providers/ollama.rs b/crates/goose/src/providers/ollama.rs index 7141cb8f8..ca94704f5 100644 --- a/crates/goose/src/providers/ollama.rs +++ b/crates/goose/src/providers/ollama.rs @@ -246,9 +246,7 @@ impl OllamaProvider { } } -impl ProviderDef for OllamaProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for OllamaProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( OLLAMA_PROVIDER_NAME, @@ -269,6 +267,10 @@ impl ProviderDef for OllamaProvider { ], ) } +} + +impl ProviderDef for OllamaProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/openai_def.rs b/crates/goose/src/providers/openai_def.rs new file mode 100644 index 000000000..d65664103 --- /dev/null +++ b/crates/goose/src/providers/openai_def.rs @@ -0,0 +1,488 @@ +use anyhow::Result; +use futures::future::BoxFuture; +use goose_providers::base::ProviderDescriptor; +use std::collections::HashMap; + +use crate::config::declarative_providers::DeclarativeProviderConfig; +use crate::providers::base::{ProviderDef, DEFAULT_PROVIDER_TIMEOUT_SECS}; +use goose_providers::api_client::{ApiClient, AuthMethod}; +use goose_providers::model::ModelConfig; +use goose_providers::openai::{ + ensure_url_scheme, parse_custom_headers, parse_openai_base_url, OpenAiProvider, + OpenAiProviderBuilder, OPEN_AI_DEFAULT_BASE_PATH, OPEN_AI_DEFAULT_FAST_MODEL, + OPEN_AI_PROVIDER_NAME, OPEN_AI_VERSIONLESS_BASE_PATH, +}; + +pub struct OpenAiProviderDef; + +impl ProviderDescriptor for OpenAiProviderDef { + fn metadata() -> goose_providers::base::ProviderMetadata { + OpenAiProvider::metadata() + } +} + +impl ProviderDef for OpenAiProviderDef { + type Provider = OpenAiProvider; + + fn from_env( + model: ModelConfig, + _extensions: Vec, + tls_config: Option, + ) -> BoxFuture<'static, Result> { + Box::pin(from_env(model, tls_config)) + } +} + +pub async fn from_env( + model: ModelConfig, + tls_config: Option, +) -> Result { + let config = crate::config::Config::global(); + + // Resolve host and base_path. + // + // Priority (highest first): + // 1. OPENAI_HOST env var — session override (deprecated but still + // honoured so that `OPENAI_HOST=… goose` keeps working) + // 2. OPENAI_BASE_URL (env or config) — ecosystem-standard + // 3. OPENAI_HOST from config file — persisted by `goose configure` + // 4. Default "https://api.openai.com" + // + // OPENAI_BASE_URL is parsed into host + query params + a flag + // indicating whether the URL included a /v1 path segment. When /v1 + // is present the default base_path is "v1/chat/completions"; + // otherwise "chat/completions" to match the OpenAI SDK convention. + // + // OPENAI_BASE_PATH always wins when set explicitly. + let parsed = if let Ok(h) = std::env::var("OPENAI_HOST") { + // OPENAI_HOST env var takes priority as a session override so + // that existing scripts like `OPENAI_HOST=… goose` still work + // even after OPENAI_BASE_URL is persisted in config. + ParsedBaseUrl { + host: h, + query_params: vec![], + has_v1: true, + from_base_url: false, + } + } else if let Some(raw_url) = config + .get_param::("OPENAI_BASE_URL") + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + { + parse_base_url(&raw_url)? + } else { + let h: String = config + .get_param("OPENAI_HOST") + .unwrap_or_else(|_| "https://api.openai.com".to_string()); + ParsedBaseUrl { + host: h, + query_params: vec![], + has_v1: true, + from_base_url: false, + } + }; + + // When the host was derived from OPENAI_BASE_URL, read + // OPENAI_BASE_PATH from env only so that the desktop UI's persisted + // default ("v1/chat/completions") doesn't shadow the versionless + // path. When the host came from OPENAI_HOST (env or config), read + // from config too — Docker Model Runner and similar setups persist a + // custom base_path that must be honoured. + let default_bp = || { + if parsed.has_v1 { + OPEN_AI_DEFAULT_BASE_PATH.to_string() + } else { + OPEN_AI_VERSIONLESS_BASE_PATH.to_string() + } + }; + let base_path: String = if parsed.from_base_url { + std::env::var("OPENAI_BASE_PATH").unwrap_or_else(|_| default_bp()) + } else { + config + .get_param("OPENAI_BASE_PATH") + .unwrap_or_else(|_| default_bp()) + }; + + // Only apply the default fast model when talking to OpenAI directly. + // Custom/compatible endpoints likely don't serve gpt-4o-mini, so + // leave fast_model unset (complete_fast will fall back to the main model). + // Parse the URL and compare the hostname exactly to avoid false positives + // (e.g. https://api.openai.com.local:8000 or proxy paths containing api.openai.com). + let host = parsed.host.clone(); + + let is_openai = url::Url::parse(&host) + .ok() + .and_then(|u| u.host_str().map(|h| h.to_ascii_lowercase())) + .map(|h| h == "api.openai.com" || h.ends_with(".api.openai.com")) + .unwrap_or(false); + let model = if is_openai { + crate::model_config::with_configured_fast_model( + model, + OPEN_AI_PROVIDER_NAME, + OPEN_AI_DEFAULT_FAST_MODEL, + )? + } else { + model + }; + + let secrets = config + .get_secrets("OPENAI_API_KEY", &["OPENAI_CUSTOM_HEADERS"]) + .unwrap_or_default(); + let api_key: Option = secrets.get("OPENAI_API_KEY").cloned(); + let custom_headers: Option> = secrets + .get("OPENAI_CUSTOM_HEADERS") + .cloned() + .map(parse_custom_headers); + + let organization: Option = config.get_param("OPENAI_ORGANIZATION").ok(); + let project: Option = config.get_param("OPENAI_PROJECT").ok(); + let timeout_secs: u64 = config + .get_param("OPENAI_TIMEOUT") + .unwrap_or(DEFAULT_PROVIDER_TIMEOUT_SECS); + + let auth = match api_key { + Some(key) if !key.is_empty() => AuthMethod::BearerToken(key), + _ => AuthMethod::NoAuth, + }; + let mut api_client = ApiClient::with_timeout_and_tls( + parsed.host, + auth, + std::time::Duration::from_secs(timeout_secs), + tls_config, + )?; + + if !parsed.query_params.is_empty() { + api_client = api_client.with_query(parsed.query_params); + } + + if let Some(org) = &organization { + api_client = api_client.with_header("OpenAI-Organization", org)?; + } + + if let Some(project) = &project { + api_client = api_client.with_header("OpenAI-Project", project)?; + } + + if let Some(headers) = &custom_headers { + let mut header_map = reqwest::header::HeaderMap::new(); + for (key, value) in headers { + let header_name = reqwest::header::HeaderName::from_bytes(key.as_bytes())?; + let header_value = reqwest::header::HeaderValue::from_str(value)?; + header_map.insert(header_name, header_value); + } + api_client = api_client.with_headers(header_map)?; + } + + let mut provider = OpenAiProviderBuilder::new(api_client, model) + .base_path(base_path) + .organization(organization) + .project(project) + .custom_headers(custom_headers) + .preserve_thinking_context(!is_openai) + .build(); + + provider.probe_context_limit_if_unset().await; + + Ok(provider) +} + +/// Resolve the API key from a declarative provider config. +/// +/// Returns `Some(key)` if a key is found, `None` if the key is optional/missing, +/// or an error if the key is required but missing/unreadable. +/// +/// The `get_secret` closure is used to look up the secret by key name. This allows +/// testing without depending on `Config::global()`. +pub fn resolve_api_key( + config: &DeclarativeProviderConfig, + get_secret: &dyn Fn(&str) -> Result, +) -> Result> { + if config.api_key_env.is_empty() { + return Ok(None); + } + + match get_secret(&config.api_key_env) { + Ok(key) => Ok(Some(key)), + Err(e) => { + use crate::config::ConfigError; + match e { + ConfigError::NotFound(_) => { + if config.requires_auth { + anyhow::bail!( + "Required API key {} is not set. Configure it via `goose configure` or set the {} environment variable.", + config.api_key_env, + config.api_key_env + ); + } + Ok(None) + } + other => { + if config.requires_auth { + anyhow::bail!("Failed to read {}: {}", config.api_key_env, other); + } else { + tracing::warn!( + "Failed to read optional API key {}: {}. Proceeding without authentication.", + config.api_key_env, + other + ); + Ok(None) + } + } + } + } + } +} + +pub fn from_custom_config( + model: ModelConfig, + config: DeclarativeProviderConfig, + tls_config: Option, +) -> Result { + let custom_models = if !config.models.is_empty() { + Some( + config + .models + .iter() + .map(|m| m.name.clone()) + .collect::>(), + ) + } else { + None + }; + + if config.dynamic_models == Some(false) && custom_models.is_none() { + return Err(anyhow::anyhow!( + "Provider '{}' has dynamic_models: false but no static models listed; \ + at least one entry in `models` is required.", + config.name + )); + } + + let global_config = crate::config::Config::global(); + let api_key = resolve_api_key(&config, &|key| global_config.get_secret(key))?; + + let normalized_base_url = ensure_url_scheme(&config.base_url); + let url = url::Url::parse(&normalized_base_url) + .map_err(|e| anyhow::anyhow!("Invalid base URL '{}': {}", config.base_url, e))?; + + let host = if let Some(port) = url.port() { + format!( + "{}://{}:{}", + url.scheme(), + url.host_str().unwrap_or(""), + port + ) + } else { + format!("{}://{}", url.scheme(), url.host_str().unwrap_or("")) + }; + let base_path = if let Some(ref explicit_path) = config.base_path { + explicit_path.trim_start_matches('/').to_string() + } else { + derive_base_path(url.path()) + }; + + let timeout_secs = config + .timeout_seconds + .unwrap_or(DEFAULT_PROVIDER_TIMEOUT_SECS); + + let auth = match api_key { + Some(key) if !key.is_empty() => AuthMethod::BearerToken(key), + _ => AuthMethod::NoAuth, + }; + let mut api_client = ApiClient::with_timeout_and_tls( + host, + auth, + std::time::Duration::from_secs(timeout_secs), + tls_config, + )?; + + if let Some(headers) = &config.headers { + let mut header_map = reqwest::header::HeaderMap::new(); + for (key, value) in headers { + let header_name = reqwest::header::HeaderName::from_bytes(key.as_bytes())?; + let header_value = reqwest::header::HeaderValue::from_str(value)?; + header_map.insert(header_name, header_value); + } + api_client = api_client.with_headers(header_map)?; + } + + let model = if let Some(ref fast_model_name) = config.fast_model { + crate::model_config::with_configured_fast_model(model, &config.name, fast_model_name)? + } else { + model + }; + + Ok(OpenAiProviderBuilder::new(api_client, model) + .base_path(base_path) + .custom_headers(config.headers) + .supports_streaming(config.supports_streaming.unwrap_or(true)) + .name(config.name.clone()) + .custom_models(custom_models) + .dynamic_models(config.dynamic_models) + .skip_canonical_filtering(config.skip_canonical_filtering) + .preserve_thinking_context(config.preserves_thinking) + .build()) +} + +/// Components extracted from an `OPENAI_BASE_URL` value. +struct ParsedBaseUrl { + /// The host (scheme + authority + any path prefix before `/v1`). + pub(crate) host: String, + /// Query parameters to forward on every request. + pub(crate) query_params: Vec<(String, String)>, + /// Whether the URL path ended with `/v1`. + pub(crate) has_v1: bool, + /// `true` when the host was derived from `OPENAI_BASE_URL`. + /// Controls whether `OPENAI_BASE_PATH` is read from env only + /// (to avoid persisted desktop defaults shadowing URL-derived paths) + /// or from config too (to honour Docker Model Runner setups). + pub(crate) from_base_url: bool, +} + +fn parse_base_url(raw_url: &str) -> Result { + let (host, query_params, has_v1) = parse_openai_base_url(raw_url)?; + Ok(ParsedBaseUrl { + host, + query_params, + has_v1, + from_base_url: true, + }) +} + +fn derive_base_path(url_path: &str) -> String { + let stripped = url_path.trim_start_matches('/'); + let normalized = stripped.trim_end_matches('/'); + if normalized.is_empty() { + "v1/chat/completions".to_string() + } else if normalized.ends_with("chat/completions") { + stripped.to_string() + } else if ends_with_version_segment(normalized) { + format!("{}/chat/completions", normalized) + } else { + format!("{}/v1/chat/completions", normalized) + } +} + +fn ends_with_version_segment(path: &str) -> bool { + let last = path.rsplit('/').next().unwrap_or(path); + last.strip_prefix('v') + .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_base_url_strips_v1_from_standard_openai_url() { + let r = parse_base_url("https://api.openai.com/v1").unwrap(); + assert_eq!(r.host, "https://api.openai.com"); + assert!(r.query_params.is_empty()); + assert!(r.has_v1); + } + + #[test] + fn parse_base_url_preserves_prefix_before_v1() { + let r = parse_base_url("https://gateway.example.com/openai/v1").unwrap(); + assert_eq!(r.host, "https://gateway.example.com/openai"); + assert!(r.has_v1); + } + + #[test] + fn parse_base_url_handles_no_path() { + let r = parse_base_url("https://api.openai.com").unwrap(); + assert_eq!(r.host, "https://api.openai.com"); + assert!(r.has_v1); + } + + #[test] + fn parse_base_url_handles_trailing_slash() { + let r = parse_base_url("https://api.openai.com/v1/").unwrap(); + assert_eq!(r.host, "https://api.openai.com"); + assert!(r.has_v1); + } + + #[test] + fn parse_base_url_preserves_port() { + let r = parse_base_url("https://localhost:8080/v1").unwrap(); + assert_eq!(r.host, "https://localhost:8080"); + assert!(r.has_v1); + } + + #[test] + fn parse_base_url_preserves_non_v1_path() { + let r = parse_base_url("https://example.com/custom/api").unwrap(); + assert_eq!(r.host, "https://example.com/custom/api"); + assert!(!r.has_v1); + } + + #[test] + fn derive_base_path_not_removing_api_path() { + let r = derive_base_path("https://opencode.ai/zen/go"); + assert_eq!(r, "https://opencode.ai/zen/go/v1/chat/completions"); + } + + #[test] + fn derive_base_path_should_support_v1() { + let r = derive_base_path("https://opencode.ai/zen/go/v1"); + assert_eq!(r, "https://opencode.ai/zen/go/v1/chat/completions"); + } + + #[test] + fn derive_base_path_should_support_no_base_path() { + let r = derive_base_path("https://opencode.ai/"); + assert_eq!(r, "https://opencode.ai/v1/chat/completions"); + } + + #[test] + fn derive_base_path_preserves_non_v1_version_prefix() { + // Zhipu's default base_url is https://open.bigmodel.cn/api/paas/v4 and + // from_custom_config passes url.path() ("/api/paas/v4") here. The + // existing /api/paas/v4 version must not gain an extra /v1 segment. + let r = derive_base_path("/api/paas/v4"); + assert_eq!(r, "api/paas/v4/chat/completions"); + } + + #[test] + fn derive_base_path_does_not_treat_v_word_as_version() { + let r = derive_base_path("/api/voice"); + assert_eq!(r, "api/voice/v1/chat/completions"); + } + + #[test] + fn parse_base_url_preserves_query_params() { + let r = parse_base_url("https://gw.example.com/v1?api-version=2024-02-01").unwrap(); + assert_eq!(r.host, "https://gw.example.com"); + assert_eq!( + r.query_params, + vec![("api-version".to_string(), "2024-02-01".to_string())] + ); + assert!(r.has_v1); + } + + #[test] + fn parse_base_url_preserves_multiple_query_params() { + let r = parse_base_url("https://example.com/v1?key=val&foo=bar").unwrap(); + assert_eq!(r.query_params.len(), 2); + assert_eq!(r.query_params[0], ("key".to_string(), "val".to_string())); + assert_eq!(r.query_params[1], ("foo".to_string(), "bar".to_string())); + } + + #[test] + fn parse_base_url_preserves_credentials() { + let r = parse_base_url("https://user:pass@gateway.example.com/v1").unwrap(); + assert_eq!(r.host, "https://user:pass@gateway.example.com"); + assert!(r.has_v1); + } + + #[test] + fn parse_base_url_rejects_empty_string() { + assert!(parse_base_url("").is_err()); + } + + #[test] + fn parse_base_url_rejects_whitespace_only() { + assert!(parse_base_url(" ").is_err()); + } +} diff --git a/crates/goose/src/providers/openrouter.rs b/crates/goose/src/providers/openrouter.rs index 695d77a20..826e789a7 100644 --- a/crates/goose/src/providers/openrouter.rs +++ b/crates/goose/src/providers/openrouter.rs @@ -154,9 +154,7 @@ fn is_gemini_model(model_name: &str) -> bool { model_name.starts_with("google/") } -impl ProviderDef for OpenRouterProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for OpenRouterProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( OPENROUTER_PROVIDER_NAME, @@ -182,6 +180,10 @@ impl ProviderDef for OpenRouterProvider { "Copy the key and paste it above", ]) } +} + +impl ProviderDef for OpenRouterProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/pi_acp.rs b/crates/goose/src/providers/pi_acp.rs index dcb292db3..5432e845e 100644 --- a/crates/goose/src/providers/pi_acp.rs +++ b/crates/goose/src/providers/pi_acp.rs @@ -8,7 +8,9 @@ use crate::acp::{ }; use crate::config::search_path::SearchPaths; use crate::config::{Config, GooseMode}; -use crate::providers::base::{current_working_dir, ProviderDef, ProviderMetadata}; +use crate::providers::base::{ + current_working_dir, ProviderDef, ProviderDescriptor, ProviderMetadata, +}; use goose_providers::model::ModelConfig; pub(crate) const PI_ACP_PROVIDER_NAME: &str = "pi-acp"; @@ -17,9 +19,7 @@ pub(crate) const PI_ACP_BINARY: &str = "pi-acp"; pub struct PiAcpProvider; -impl ProviderDef for PiAcpProvider { - type Provider = AcpProvider; - +impl goose_providers::base::ProviderDescriptor for PiAcpProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( PI_ACP_PROVIDER_NAME, @@ -38,6 +38,10 @@ impl ProviderDef for PiAcpProvider { ]) .with_model_selection_hint("Use the Pi CLI to configure models") } +} + +impl ProviderDef for PiAcpProvider { + type Provider = AcpProvider; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/provider_registry.rs b/crates/goose/src/providers/provider_registry.rs index dc313a188..9b5ca3174 100644 --- a/crates/goose/src/providers/provider_registry.rs +++ b/crates/goose/src/providers/provider_registry.rs @@ -390,7 +390,7 @@ impl ProviderRegistry { mod tests { use super::*; use crate::config::declarative_providers::ProviderEngine; - use crate::providers::openai::OpenAiProvider; + use crate::providers::openai_def::OpenAiProviderDef; fn test_config() -> DeclarativeProviderConfig { DeclarativeProviderConfig { @@ -420,7 +420,7 @@ mod tests { #[test] fn register_with_name_can_override_inventory_configured() { let mut registry = ProviderRegistry::new(None); - registry.register_with_name_and_inventory_configured::( + registry.register_with_name_and_inventory_configured::( &test_config(), ProviderType::Declarative, false, diff --git a/crates/goose/src/providers/sagemaker_tgi.rs b/crates/goose/src/providers/sagemaker_tgi.rs index 9aaa6face..cc994b6cf 100644 --- a/crates/goose/src/providers/sagemaker_tgi.rs +++ b/crates/goose/src/providers/sagemaker_tgi.rs @@ -278,9 +278,7 @@ impl SageMakerTgiProvider { } } -impl ProviderDef for SageMakerTgiProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for SageMakerTgiProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( SAGEMAKER_TGI_PROVIDER_NAME, @@ -296,6 +294,10 @@ impl ProviderDef for SageMakerTgiProvider { ], ) } +} + +impl ProviderDef for SageMakerTgiProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/snowflake.rs b/crates/goose/src/providers/snowflake.rs index 4b7923f17..be7fba93c 100644 --- a/crates/goose/src/providers/snowflake.rs +++ b/crates/goose/src/providers/snowflake.rs @@ -303,9 +303,7 @@ impl SnowflakeProvider { } } -impl ProviderDef for SnowflakeProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for SnowflakeProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( SNOWFLAKE_PROVIDER_NAME, @@ -320,6 +318,10 @@ impl ProviderDef for SnowflakeProvider { ], ) } +} + +impl ProviderDef for SnowflakeProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/testprovider.rs b/crates/goose/src/providers/testprovider.rs index 78ba36789..a12988127 100644 --- a/crates/goose/src/providers/testprovider.rs +++ b/crates/goose/src/providers/testprovider.rs @@ -138,9 +138,7 @@ impl TestProvider { } } -impl ProviderDef for TestProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for TestProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( Self::PROVIDER_NAME, @@ -152,6 +150,10 @@ impl ProviderDef for TestProvider { vec![], ) } +} + +impl ProviderDef for TestProvider { + type Provider = Self; fn from_env( _model: ModelConfig, diff --git a/crates/goose/src/providers/tetrate.rs b/crates/goose/src/providers/tetrate.rs index 239343030..3d906c10d 100644 --- a/crates/goose/src/providers/tetrate.rs +++ b/crates/goose/src/providers/tetrate.rs @@ -92,9 +92,7 @@ impl TetrateProvider { } } -impl ProviderDef for TetrateProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for TetrateProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( TETRATE_PROVIDER_NAME, @@ -115,6 +113,10 @@ impl ProviderDef for TetrateProvider { ], ) } +} + +impl ProviderDef for TetrateProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/utils.rs b/crates/goose/src/providers/utils.rs index bf3ac7ad4..283d34d0b 100644 --- a/crates/goose/src/providers/utils.rs +++ b/crates/goose/src/providers/utils.rs @@ -134,7 +134,7 @@ pub async fn handle_response_google_compat(response: Response) -> Result ProviderMetadata { ProviderMetadata::new( XAI_PROVIDER_NAME, @@ -50,6 +48,10 @@ impl ProviderDef for XaiProvider { ], ) } +} + +impl ProviderDef for XaiProvider { + type Provider = OpenAiCompatibleProvider; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/providers/xai_oauth.rs b/crates/goose/src/providers/xai_oauth.rs index 5887d11eb..19b449630 100644 --- a/crates/goose/src/providers/xai_oauth.rs +++ b/crates/goose/src/providers/xai_oauth.rs @@ -760,9 +760,7 @@ impl Provider for XaiOAuthProvider { } } -impl ProviderDef for XaiOAuthProvider { - type Provider = Self; - +impl goose_providers::base::ProviderDescriptor for XaiOAuthProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::new( XAI_OAUTH_PROVIDER_NAME, @@ -777,6 +775,10 @@ impl ProviderDef for XaiOAuthProvider { ], ) } +} + +impl ProviderDef for XaiOAuthProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/src/session/import_formats/codex.rs b/crates/goose/src/session/import_formats/codex.rs index 2c8beb1f0..e76a30350 100644 --- a/crates/goose/src/session/import_formats/codex.rs +++ b/crates/goose/src/session/import_formats/codex.rs @@ -25,8 +25,8 @@ use serde_json::{json, Map, Value}; use crate::conversation::message::Message; use crate::conversation::Conversation; -use crate::providers::formats::openai_responses::{ResponseOutputItem, ResponsesApiResponse}; use goose_providers::conversation::token_usage::Usage; +use goose_providers::formats::openai_responses::{ResponseOutputItem, ResponsesApiResponse}; pub fn convert(content: &str) -> Result { let lines: Vec = content @@ -147,7 +147,7 @@ pub fn convert(content: &str) -> Result { usage: None, }; if let Ok(decoded) = - crate::providers::formats::openai_responses::responses_api_to_message(&stub) + goose_providers::formats::openai_responses::responses_api_to_message(&stub) { if !decoded.content.is_empty() { let mut msg = Message::assistant(); diff --git a/crates/goose/tests/agent.rs b/crates/goose/tests/agent.rs index 347629af3..c0be51adc 100644 --- a/crates/goose/tests/agent.rs +++ b/crates/goose/tests/agent.rs @@ -361,9 +361,7 @@ mod tests { } } - impl ProviderDef for MockToolProvider { - type Provider = Self; - + impl goose::providers::base::ProviderDescriptor for MockToolProvider { fn metadata() -> ProviderMetadata { ProviderMetadata { name: "mock".to_string(), @@ -377,6 +375,10 @@ mod tests { model_selection_hint: None, } } + } + + impl ProviderDef for MockToolProvider { + type Provider = Self; fn from_env( _model: ModelConfig, @@ -532,9 +534,7 @@ mod tests { } } - impl ProviderDef for SummarizationTestProvider { - type Provider = Self; - + impl goose::providers::base::ProviderDescriptor for SummarizationTestProvider { fn metadata() -> ProviderMetadata { ProviderMetadata { name: "mock-summarization".to_string(), @@ -548,6 +548,10 @@ mod tests { model_selection_hint: None, } } + } + + impl ProviderDef for SummarizationTestProvider { + type Provider = Self; fn from_env( _model: ModelConfig, @@ -885,9 +889,7 @@ mod tests { } } - impl ProviderDef for MultiStepProvider { - type Provider = Self; - + impl goose::providers::base::ProviderDescriptor for MultiStepProvider { fn metadata() -> ProviderMetadata { ProviderMetadata { name: "multi-step-mock".to_string(), @@ -901,6 +903,10 @@ mod tests { model_selection_hint: None, } } + } + + impl ProviderDef for MultiStepProvider { + type Provider = Self; fn from_env( _model: ModelConfig, @@ -1156,9 +1162,7 @@ mod tests { } } - impl ProviderDef for GoalTextProvider { - type Provider = Self; - + impl goose::providers::base::ProviderDescriptor for GoalTextProvider { fn metadata() -> ProviderMetadata { ProviderMetadata { name: "goal-mock".to_string(), @@ -1172,6 +1176,10 @@ mod tests { model_selection_hint: None, } } + } + + impl ProviderDef for GoalTextProvider { + type Provider = Self; fn from_env( _model: ModelConfig, diff --git a/crates/goose/tests/compaction.rs b/crates/goose/tests/compaction.rs index dfb4ea780..3b95b2d11 100644 --- a/crates/goose/tests/compaction.rs +++ b/crates/goose/tests/compaction.rs @@ -179,9 +179,7 @@ impl Provider for MockCompactionProvider { } } -impl ProviderDef for MockCompactionProvider { - type Provider = Self; - +impl goose::providers::base::ProviderDescriptor for MockCompactionProvider { fn metadata() -> ProviderMetadata { ProviderMetadata { name: "mock".to_string(), @@ -195,6 +193,10 @@ impl ProviderDef for MockCompactionProvider { model_selection_hint: None, } } +} + +impl ProviderDef for MockCompactionProvider { + type Provider = Self; fn from_env( _model: ModelConfig, diff --git a/crates/goose/tests/mcp_integration_test.rs b/crates/goose/tests/mcp_integration_test.rs index 77ff78625..e7ee4c916 100644 --- a/crates/goose/tests/mcp_integration_test.rs +++ b/crates/goose/tests/mcp_integration_test.rs @@ -51,12 +51,14 @@ impl MockProvider { } } -impl ProviderDef for MockProvider { - type Provider = Self; - +impl goose::providers::base::ProviderDescriptor for MockProvider { fn metadata() -> ProviderMetadata { ProviderMetadata::empty() } +} + +impl ProviderDef for MockProvider { + type Provider = Self; fn from_env( model: ModelConfig, diff --git a/crates/goose/tests/providers.rs b/crates/goose/tests/providers.rs index b215c7d3c..e9125822f 100644 --- a/crates/goose/tests/providers.rs +++ b/crates/goose/tests/providers.rs @@ -161,11 +161,6 @@ impl ProviderTestConfig { self } - fn clear_env(mut self, vars: &'static [&'static str]) -> Self { - self.clear_env = vars; - self - } - fn test_permissions(mut self, v: bool) -> Self { self.test_permissions = v; self @@ -191,6 +186,12 @@ impl ProviderTestConfig { self } + #[allow(dead_code)] // only used by tests that are behind non-default feature flags + fn clear_env(mut self, vars: &'static [&'static str]) -> Self { + self.clear_env = vars; + self + } + fn with_agentic_provider(name: &'static str, model_name: &'static str, binary: &str) -> Self { let skip = which::which(binary).is_err(); Self {