aKode fase 3: provider locali, chiavi per provider, modelli dal server, SearXNG
- Provider: rimossi openai, Bedrock e GCP integrati e ogni fallback a OpenAI;
restano ollama, lmstudio e i provider personalizzati. Senza provider, exec e
TUI mostrano come configurarlo.
- Chiave per provider: api_key = "keyring", provider_api_key_store =
auto|keyring|file (fallback su file 0600 / ACL Windows); `codex login
--provider <id> --with-api-key`, `logout --provider`; login status e doctor
mostrano dove sta la chiave senza rivelarla.
- Modelli letti da GET {base_url}/models; contesto da config, poi dal server
(/props, meta.n_ctx), poi 32768; apply_patch come tool function; niente tool
ospitati; niente piu' avviso "metadata not found".
- Unione dei soli messaggi system/developer iniziali in un unico system;
quelli successivi restano al loro posto come user (cache del server
preservata: turno N prefisso esatto del turno N+1).
- Modelli ausiliari (memorie, guardian-v2) = modello di sessione se il
preferito gpt-* non e' nel catalogo.
- Ricerca web: crate web-tools, backend SearXNG con web_search e web_fetch
(protezione SSRF); senza backend nessuno strumento web.
- Skill: rimossa openai-docs; skill-installer punta a git.difonzo.net.
- apply_patch accetta gli header @@ -a,b +c,d @@ dei diff unificati.
- Rimossi resti: request_plugin_install, AppsInstructions, --cyber-access-program,
URL updater/realtime predefiniti.
- Fix: importazione sessioni con provider vuoto.
- Istruzioni di sistema invariate. Test: cancellati solo quelli del codice
rimosso, test di sicurezza adattati; restano solo fallimenti d'ambiente.
- Prova reale su imeAI + SearXNG: risposta, modifica file, web_search,
cache riusata, connessioni solo verso .25 e .57.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,7 +11,5 @@ pub(crate) fn auth_mode_to_api(auth_mode: AuthMode) -> ApiAuthMode {
|
||||
match auth_mode {
|
||||
AuthMode::ApiKey => ApiAuthMode::ApiKey,
|
||||
AuthMode::Headers => ApiAuthMode::Headers,
|
||||
AuthMode::BedrockApiKey => ApiAuthMode::BedrockApiKey,
|
||||
AuthMode::BedrockAccessKeys => ApiAuthMode::BedrockAccessKeys,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::ThreadConfigLoader;
|
||||
use codex_config::apply_default_gcp_auth;
|
||||
use codex_config::loader::load_config_layers_state;
|
||||
use codex_config::loader::load_managed_requirements_state;
|
||||
use codex_core::config::Config;
|
||||
@@ -13,10 +12,6 @@ use codex_exec_server::LOCAL_FS;
|
||||
use codex_features::feature_for_key;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::default_client::set_default_client_residency_requirement;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_ID;
|
||||
use codex_model_provider_info::GCP_PROVIDER_ID;
|
||||
use codex_model_provider_info::OPENAI_PROVIDER_ID;
|
||||
use codex_model_provider_info::built_in_model_providers;
|
||||
use codex_model_provider_info::merge_configured_model_providers;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
@@ -234,35 +229,19 @@ impl ConfigManager {
|
||||
.model_providers
|
||||
.as_ref()
|
||||
.and_then(|providers| providers.get(¤t.model_provider_id))
|
||||
.cloned();
|
||||
let required_provider = match required_provider {
|
||||
Some(provider)
|
||||
if matches!(
|
||||
current.model_provider_id.as_str(),
|
||||
AMAZON_BEDROCK_PROVIDER_ID
|
||||
| AMAZON_BEDROCK_RUNTIME_PROVIDER_ID
|
||||
| GCP_PROVIDER_ID
|
||||
| OPENAI_PROVIDER_ID
|
||||
) =>
|
||||
{
|
||||
// Managed overrides must receive the same built-in defaults as startup config.
|
||||
// OpenAI's inference URL belongs to the retained session, not the catalog override.
|
||||
let mut provider = merge_configured_model_providers(
|
||||
built_in_model_providers(current.model_provider.base_url.clone()),
|
||||
.cloned()
|
||||
.map(|provider| {
|
||||
merge_configured_model_providers(
|
||||
HashMap::new(),
|
||||
HashMap::from([(current.model_provider_id.clone(), provider)]),
|
||||
)
|
||||
.map_err(|message| std::io::Error::new(std::io::ErrorKind::InvalidData, message))?
|
||||
.remove(¤t.model_provider_id);
|
||||
if current.model_provider_id == GCP_PROVIDER_ID
|
||||
&& let Some(provider) = provider.as_mut()
|
||||
{
|
||||
apply_default_gcp_auth(provider, ¤t.cwd);
|
||||
}
|
||||
provider
|
||||
}
|
||||
Some(provider) => Some(provider),
|
||||
None => None,
|
||||
};
|
||||
.unwrap_or_default()
|
||||
.remove(¤t.model_provider_id)
|
||||
.unwrap_or_default()
|
||||
});
|
||||
// Built-in providers (ollama, lmstudio) cannot be overridden, so managed
|
||||
// definitions apply as configured.
|
||||
|
||||
let definition_changed = required_provider
|
||||
.as_ref()
|
||||
.is_some_and(|provider| provider != ¤t.model_provider);
|
||||
@@ -404,12 +383,16 @@ impl ConfigManager {
|
||||
.as_deref()
|
||||
.or(saved_provider)
|
||||
.or(config.model_provider.as_deref())
|
||||
.unwrap_or("openai");
|
||||
.unwrap_or_default();
|
||||
// Validate the saved route even when a client sends a provider override.
|
||||
// With no provider at all there is nothing to validate (setup is pending).
|
||||
for provider in [
|
||||
saved_provider.unwrap_or(requested_provider),
|
||||
requested_provider,
|
||||
] {
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|provider| !provider.is_empty())
|
||||
{
|
||||
if let Some(required) = layers.required_model_provider()
|
||||
&& required != provider
|
||||
{
|
||||
@@ -422,8 +405,7 @@ impl ConfigManager {
|
||||
));
|
||||
}
|
||||
if !config.model_providers.contains_key(provider)
|
||||
&& !built_in_model_providers(config.openai_base_url.clone())
|
||||
.contains_key(provider)
|
||||
&& !built_in_model_providers().contains_key(provider)
|
||||
{
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
|
||||
@@ -10,67 +10,6 @@ use codex_config::ThreadConfigSource;
|
||||
use codex_config::test_support::ManagedConfigFixture;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
use test_case::test_case;
|
||||
|
||||
#[test_case(AMAZON_BEDROCK_PROVIDER_ID, "aws.region = 'us-west-2'", "us-west-2", "us-east-1", None; "bedrock")]
|
||||
#[test_case(AMAZON_BEDROCK_RUNTIME_PROVIDER_ID, "aws.region = 'us-west-2'", "us-west-2", "us-east-1", None; "bedrock_runtime")]
|
||||
#[test_case(GCP_PROVIDER_ID, "project_id = 'example-project'\nlocation = 'us-central1'", "example-project", "other-project", None; "gcp_project")]
|
||||
#[test_case(GCP_PROVIDER_ID, "project_id = 'example-project'\nlocation = 'us-central1'", "us-central1", "us-east4", None; "gcp_location")]
|
||||
#[test_case(GCP_PROVIDER_ID, "project_id = 'example-project'\nauth.command = 'print-token'", "print-token", "other-token", None; "gcp_auth")]
|
||||
#[tokio::test]
|
||||
async fn provider_requirements_resolve_builtin_overrides(
|
||||
provider_id: &str,
|
||||
provider_config: &str,
|
||||
original: &str,
|
||||
replacement: &str,
|
||||
openai_base_url: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let home = tempdir()?;
|
||||
let workspace = tempdir()?;
|
||||
if let Some(base_url) = openai_base_url {
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!("openai_base_url = '{base_url}'"),
|
||||
)?;
|
||||
}
|
||||
let requirements = format!(
|
||||
"model_provider = '{provider_id}'\n[model_providers.{provider_id}]\n{provider_config}"
|
||||
);
|
||||
let manager = ConfigManager::new_for_tests(home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
(ManagedConfigFixture::requirements(&requirements))
|
||||
.loader_overrides_for_tests(home.path())?,
|
||||
);
|
||||
let current = manager
|
||||
.load_latest_config(Some(workspace.path().to_path_buf()))
|
||||
.await?;
|
||||
if provider_id == "openai" {
|
||||
assert_eq!(current.model_provider.base_url.as_deref(), openai_base_url);
|
||||
// Retained threads keep their inference route even if user defaults later change.
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"openai_base_url = 'https://eu.api.openai.com/v1'",
|
||||
)?;
|
||||
}
|
||||
manager.check_thread_model_provider(¤t).await?;
|
||||
|
||||
let changed = ConfigManager::new_for_tests(home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
(ManagedConfigFixture::requirements(
|
||||
requirements.replace(original, replacement),
|
||||
))
|
||||
.loader_overrides_for_tests(home.path())?,
|
||||
);
|
||||
assert_eq!(
|
||||
changed
|
||||
.check_thread_model_provider(¤t)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct UnavailableThreadConfig;
|
||||
|
||||
@@ -137,11 +76,7 @@ async fn provider_requirements_ignore_system_defaults_but_reject_requirement_cha
|
||||
overrides.system_config_path = Some(system_config_path.clone());
|
||||
overrides.system_requirements_path = Some(requirements_path.clone());
|
||||
overrides.managed_config_path = Some(managed_config_path.clone());
|
||||
let manager = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
overrides,
|
||||
);
|
||||
let manager = ConfigManager::new_for_tests(home.path().to_path_buf(), Vec::new(), overrides);
|
||||
let current = manager.load_latest_config(/*fallback_cwd*/ None).await?;
|
||||
|
||||
std::fs::write(&system_config_path, "invalid toml !!!")?;
|
||||
@@ -239,6 +174,7 @@ Vec::new(),
|
||||
.load_startup_config(/*fallback_cwd*/ None)
|
||||
.await?
|
||||
.config;
|
||||
assert_eq!(refreshed.model_provider_id, "openai");
|
||||
// aKode: with no provider configured there is no default (`openai`) provider.
|
||||
assert_eq!(refreshed.model_provider_id, "");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -33,7 +33,6 @@ use codex_core::path_utils;
|
||||
use codex_core::path_utils::SymlinkWritePaths;
|
||||
use codex_core::path_utils::resolve_symlink_write_paths;
|
||||
use codex_core::path_utils::write_atomically;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde_json::Value as JsonValue;
|
||||
@@ -49,8 +48,6 @@ use toml_edit::Item as TomlItem;
|
||||
mod credential_edits;
|
||||
#[path = "config_manager_service_model_providers.rs"]
|
||||
mod model_providers;
|
||||
#[path = "config_manager_service_provider_setup.rs"]
|
||||
mod provider_setup;
|
||||
#[path = "config_manager_service_provider_write.rs"]
|
||||
mod provider_write;
|
||||
|
||||
@@ -125,11 +122,6 @@ impl ConfigManagerError {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct PreparedProviderWrite {
|
||||
edits: Vec<ApiConfigEdit>,
|
||||
expected_version: String,
|
||||
}
|
||||
|
||||
impl ConfigManager {
|
||||
pub(crate) async fn read(
|
||||
&self,
|
||||
@@ -231,63 +223,6 @@ impl ConfigManager {
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_provider_config<'a>(
|
||||
&self,
|
||||
layers: &ConfigLayerStack,
|
||||
provider_id: &'a str,
|
||||
settings: impl IntoIterator<Item = (&'a str, Option<&'a str>)>,
|
||||
) -> Result<(PreparedProviderWrite, ModelProviderInfo), ConfigManagerError> {
|
||||
let selection = match layers.required_model_provider() {
|
||||
Some(required) if required == provider_id => None,
|
||||
Some(required) => {
|
||||
return Err(ConfigManagerError::write(
|
||||
ConfigWriteErrorCode::ConfigRequirementReadonly,
|
||||
format!(
|
||||
"Cannot select `{provider_id}` because requirements set `model_provider` to `{required}`."
|
||||
),
|
||||
));
|
||||
}
|
||||
None => Some(("model_provider".to_owned(), Some(provider_id))),
|
||||
};
|
||||
let settings = settings
|
||||
.into_iter()
|
||||
.map(|(key, value)| (format!("model_providers.{provider_id}.{key}"), value));
|
||||
let edits = selection
|
||||
.into_iter()
|
||||
.chain(settings)
|
||||
.map(|(key_path, value)| ApiConfigEdit {
|
||||
key_path,
|
||||
value: value.into(),
|
||||
merge_strategy: MergeStrategy::Replace,
|
||||
})
|
||||
.collect();
|
||||
let user_path = self
|
||||
.user_config_path()
|
||||
.map_err(|err| ConfigManagerError::io("failed to resolve user config path", err))?;
|
||||
provider_setup::preview(layers, &user_path, provider_id, edits)
|
||||
}
|
||||
|
||||
pub(crate) async fn commit_provider_config(
|
||||
&self,
|
||||
write: PreparedProviderWrite,
|
||||
) -> Result<(), ConfigManagerError> {
|
||||
let response = self
|
||||
.batch_write(ConfigBatchWriteParams {
|
||||
edits: write.edits,
|
||||
file_path: None,
|
||||
expected_version: Some(write.expected_version),
|
||||
reload_user_config: false,
|
||||
})
|
||||
.await?;
|
||||
if let Some(overridden) = response.overridden_metadata {
|
||||
return Err(ConfigManagerError::write(
|
||||
ConfigWriteErrorCode::ConfigLayerReadonly,
|
||||
overridden.message,
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn batch_write(
|
||||
&self,
|
||||
params: ConfigBatchWriteParams,
|
||||
|
||||
@@ -11,17 +11,9 @@ use codex_app_server_protocol::ProviderSettings;
|
||||
use codex_config::ConfigLayerEntry;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_NAME;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_NAME;
|
||||
use codex_model_provider_info::GCP_PROVIDER_ID;
|
||||
use codex_model_provider_info::GCP_PROVIDER_NAME;
|
||||
use codex_model_provider_info::LMSTUDIO_OSS_PROVIDER_ID;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::OLLAMA_OSS_PROVIDER_ID;
|
||||
use codex_model_provider_info::OPENAI_PROVIDER_ID;
|
||||
use codex_model_provider_info::OPENAI_PROVIDER_NAME;
|
||||
use codex_model_provider_info::built_in_model_providers;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
@@ -37,9 +29,14 @@ pub(super) fn has_external_auth(config: &TomlValue) -> bool {
|
||||
.is_some_and(|url| {
|
||||
!url.username().is_empty() || url.password().is_some() || url.query().is_some()
|
||||
})
|
||||
|| ["auth", "gateway_oauth", "aws", "experimental_bearer_token"]
|
||||
.iter()
|
||||
.any(|key| config.get(key).is_some())
|
||||
|| [
|
||||
"auth",
|
||||
"gateway_oauth",
|
||||
"api_key",
|
||||
"experimental_bearer_token",
|
||||
]
|
||||
.iter()
|
||||
.any(|key| config.get(key).is_some())
|
||||
|| config
|
||||
.get("requires_openai_auth")
|
||||
.and_then(TomlValue::as_bool)
|
||||
@@ -71,7 +68,7 @@ impl ConfigManager {
|
||||
.await
|
||||
.map_err(|e| ConfigManagerError::io("failed to read providers", e))?;
|
||||
let effective = layers.effective_config();
|
||||
let builtins = built_in_model_providers(/*openai_base_url*/ None);
|
||||
let builtins = built_in_model_providers();
|
||||
let writable_user_layer = writable_user_layer(&layers, self.loader_overrides());
|
||||
let configured = effective
|
||||
.get("model_providers")
|
||||
@@ -79,7 +76,7 @@ impl ConfigManager {
|
||||
let default_id = layers
|
||||
.required_model_provider()
|
||||
.or_else(|| effective.get("model_provider").and_then(TomlValue::as_str))
|
||||
.unwrap_or(OPENAI_PROVIDER_ID);
|
||||
.unwrap_or_default();
|
||||
let selection_layer = layers
|
||||
.layers_high_to_low()
|
||||
.find(|layer| layer.config.get("model_provider").is_some());
|
||||
@@ -93,7 +90,6 @@ impl ConfigManager {
|
||||
.flat_map(|table| table.keys().map(String::as_str))
|
||||
// Local OSS built-ins cannot have configured provider tables.
|
||||
.filter(|id| !matches!(*id, OLLAMA_OSS_PROVIDER_ID | LMSTUDIO_OSS_PROVIDER_ID))
|
||||
.chain([OPENAI_PROVIDER_ID])
|
||||
.collect();
|
||||
let data = ids
|
||||
.into_iter()
|
||||
@@ -124,36 +120,19 @@ pub(super) fn summarize_provider(
|
||||
layers: &ConfigLayerStack,
|
||||
writable_user_layer: Option<&ConfigLayerEntry>,
|
||||
) -> ModelProviderSummary {
|
||||
let _ = effective;
|
||||
let display_name = match builtin {
|
||||
Some(_) if id == AMAZON_BEDROCK_PROVIDER_ID => "Amazon Bedrock Mantle",
|
||||
Some(provider) => &provider.name,
|
||||
None => config.and_then(|c| c.get("name")?.as_str()).unwrap_or(id),
|
||||
};
|
||||
let builtin_auth = uses_builtin_auth(display_name);
|
||||
let requires_rename = builtin.is_none() && (display_name.trim().is_empty() || builtin_auth);
|
||||
let external_auth = builtin_auth || config.is_some_and(has_external_auth);
|
||||
let base_url = if id == OPENAI_PROVIDER_ID {
|
||||
effective.get("openai_base_url")
|
||||
} else {
|
||||
config.and_then(|config| config.get("base_url"))
|
||||
}
|
||||
.and_then(TomlValue::as_str)
|
||||
.filter(|url| valid_endpoint(url))
|
||||
.map(str::to_owned);
|
||||
let requires_rename = builtin.is_none() && display_name.trim().is_empty();
|
||||
let external_auth = config.is_some_and(has_external_auth);
|
||||
let base_url = config
|
||||
.and_then(|config| config.get("base_url"))
|
||||
.and_then(TomlValue::as_str)
|
||||
.filter(|url| valid_endpoint(url))
|
||||
.map(str::to_owned);
|
||||
let settings = match id {
|
||||
OPENAI_PROVIDER_ID => ProviderSettings::OpenAi,
|
||||
AMAZON_BEDROCK_PROVIDER_ID | AMAZON_BEDROCK_RUNTIME_PROVIDER_ID => {
|
||||
let aws = config.and_then(|provider| provider.get("aws"));
|
||||
ProviderSettings::Bedrock {
|
||||
profile: string_field(aws, "profile"),
|
||||
region: string_field(aws, "region"),
|
||||
}
|
||||
}
|
||||
GCP_PROVIDER_ID => ProviderSettings::Gcp {
|
||||
project_id: string_field(config, "project_id"),
|
||||
location: string_field(config, "location"),
|
||||
credential_file: string_field(config, "credential_file"),
|
||||
},
|
||||
_ => {
|
||||
let env_key = string_field(config, "env_key");
|
||||
let auth = if external_auth {
|
||||
@@ -180,16 +159,6 @@ pub(super) fn summarize_provider(
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn uses_builtin_auth(name: &str) -> bool {
|
||||
matches!(
|
||||
name,
|
||||
OPENAI_PROVIDER_NAME
|
||||
| AMAZON_BEDROCK_PROVIDER_NAME
|
||||
| AMAZON_BEDROCK_RUNTIME_PROVIDER_NAME
|
||||
| GCP_PROVIDER_NAME
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn writable_user_layer<'a>(
|
||||
layers: &'a ConfigLayerStack,
|
||||
overrides: &LoaderOverrides,
|
||||
@@ -204,18 +173,8 @@ pub(super) fn supported_fields(
|
||||
config: Option<&TomlValue>,
|
||||
builtin: Option<&ModelProviderInfo>,
|
||||
) -> &'static [&'static str] {
|
||||
let aws_config = config.and_then(|config| config.get("aws"));
|
||||
let _ = (id, config);
|
||||
match (builtin, id) {
|
||||
(Some(_), AMAZON_BEDROCK_PROVIDER_ID | AMAZON_BEDROCK_RUNTIME_PROVIDER_ID) => {
|
||||
if config.is_some_and(|config| config.get("auth").is_some()) {
|
||||
&[]
|
||||
} else if aws_config.is_some_and(|aws| aws.get("credential_export").is_some()) {
|
||||
&["aws.region"]
|
||||
} else {
|
||||
&["aws.profile", "aws.region"]
|
||||
}
|
||||
}
|
||||
(Some(_), GCP_PROVIDER_ID) => &["project_id", "location", "credential_file"],
|
||||
(Some(_), _) => &[],
|
||||
(None, _) => &["name", "base_url", "env_key"],
|
||||
}
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
//! Previews the effective provider configuration and captures the user layer version for commit.
|
||||
|
||||
use super::ConfigManagerError;
|
||||
use super::MergeError;
|
||||
use super::PreparedProviderWrite;
|
||||
use super::apply_merge;
|
||||
use super::find_effective_layer;
|
||||
use super::override_message;
|
||||
use super::parse_value;
|
||||
use super::value_at_path;
|
||||
use super::writable_key_path;
|
||||
use codex_app_server_protocol::ConfigEdit;
|
||||
use codex_app_server_protocol::ConfigWriteErrorCode;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::version_for_toml;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
pub(super) fn preview(
|
||||
layers: &ConfigLayerStack,
|
||||
user_path: &AbsolutePathBuf,
|
||||
provider_id: &str,
|
||||
edits: Vec<ConfigEdit>,
|
||||
) -> Result<(PreparedProviderWrite, ModelProviderInfo), ConfigManagerError> {
|
||||
let (mut user_config, expected_version) = match layers.get_active_user_layer() {
|
||||
Some(layer) => (layer.config.clone(), layer.version.clone()),
|
||||
None => {
|
||||
let empty = TomlValue::Table(Default::default());
|
||||
let version = version_for_toml(&empty);
|
||||
(empty, version)
|
||||
}
|
||||
};
|
||||
let mut fields = Vec::with_capacity(edits.len());
|
||||
for edit in &edits {
|
||||
let path = writable_key_path(layers, &edit.key_path)?;
|
||||
let value = parse_value(edit.value.clone())?;
|
||||
apply_merge(
|
||||
&mut user_config,
|
||||
&path,
|
||||
value.as_ref(),
|
||||
edit.merge_strategy.clone(),
|
||||
)
|
||||
.map_err(|MergeError::Validation(message)| {
|
||||
ConfigManagerError::write(ConfigWriteErrorCode::ConfigValidationError, message)
|
||||
})?;
|
||||
fields.push((&edit.key_path, path, value));
|
||||
}
|
||||
|
||||
let preview = layers
|
||||
.with_user_config(user_path, user_config)
|
||||
.map_err(|err| {
|
||||
ConfigManagerError::write(ConfigWriteErrorCode::ConfigValidationError, err.to_string())
|
||||
})?;
|
||||
let effective = preview.effective_config();
|
||||
for (key, path, expected) in fields {
|
||||
if value_at_path(&effective, &path) != expected.as_ref() {
|
||||
let source = find_effective_layer(&preview, &path)
|
||||
.map(|layer| override_message(&layer.name))
|
||||
.unwrap_or_else(|| "Overridden by another configuration layer".to_owned());
|
||||
return Err(ConfigManagerError::write(
|
||||
ConfigWriteErrorCode::ConfigLayerReadonly,
|
||||
format!("Cannot configure `{key}`: {source}"),
|
||||
));
|
||||
}
|
||||
}
|
||||
let provider = effective
|
||||
.get("model_providers")
|
||||
.and_then(|providers| providers.get(provider_id))
|
||||
.cloned()
|
||||
.map(TomlValue::try_into)
|
||||
.transpose()
|
||||
.map_err(|_| {
|
||||
ConfigManagerError::write(
|
||||
ConfigWriteErrorCode::ConfigValidationError,
|
||||
format!("Invalid `{provider_id}` provider configuration."),
|
||||
)
|
||||
})?
|
||||
.unwrap_or_default();
|
||||
Ok((
|
||||
PreparedProviderWrite {
|
||||
edits,
|
||||
expected_version,
|
||||
},
|
||||
provider,
|
||||
))
|
||||
}
|
||||
@@ -10,22 +10,16 @@ use super::model_providers::field_is_writable;
|
||||
use super::model_providers::has_external_auth;
|
||||
use super::model_providers::summarize_provider;
|
||||
use super::model_providers::supported_fields;
|
||||
use super::model_providers::uses_builtin_auth;
|
||||
use super::model_providers::valid_endpoint;
|
||||
use super::model_providers::writable_user_layer;
|
||||
use codex_app_server_protocol::BedrockProviderId;
|
||||
use codex_app_server_protocol::ConfigBatchWriteParams;
|
||||
use codex_app_server_protocol::ConfigWriteErrorCode;
|
||||
use codex_app_server_protocol::CustomGatewaySettingsParams;
|
||||
use codex_app_server_protocol::GcpProviderId;
|
||||
use codex_app_server_protocol::ModelProviderConfigWriteParams;
|
||||
use codex_app_server_protocol::ModelProviderConfigWriteResponse;
|
||||
use codex_app_server_protocol::ProviderSettingsPatch;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_ID;
|
||||
use codex_model_provider_info::GCP_PROVIDER_ID;
|
||||
use codex_model_provider_info::LEGACY_OLLAMA_CHAT_PROVIDER_ID;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::built_in_model_providers;
|
||||
@@ -40,7 +34,7 @@ impl ConfigManager {
|
||||
.load_thread_agnostic_config()
|
||||
.await
|
||||
.map_err(|err| ConfigManagerError::io("failed to read providers", err))?;
|
||||
let builtins = built_in_model_providers(/*openai_base_url*/ None);
|
||||
let builtins = built_in_model_providers();
|
||||
let (provider_id, edits) =
|
||||
provider_edits(¶ms, &layers, self.loader_overrides(), &builtins)?;
|
||||
let response = self
|
||||
@@ -126,30 +120,6 @@ fn provider_edits(
|
||||
}
|
||||
(id, fields)
|
||||
}
|
||||
ProviderSettingsPatch::Bedrock(patch) => {
|
||||
let id = match patch.provider_id {
|
||||
BedrockProviderId::AmazonBedrock => AMAZON_BEDROCK_PROVIDER_ID,
|
||||
BedrockProviderId::AmazonBedrockRuntime => AMAZON_BEDROCK_RUNTIME_PROVIDER_ID,
|
||||
};
|
||||
(
|
||||
id.to_owned(),
|
||||
patch_fields([
|
||||
("aws.profile", &patch.profile),
|
||||
("aws.region", &patch.region),
|
||||
]),
|
||||
)
|
||||
}
|
||||
ProviderSettingsPatch::Gcp(patch) => {
|
||||
let GcpProviderId::Gcp = patch.provider_id;
|
||||
(
|
||||
GCP_PROVIDER_ID.to_owned(),
|
||||
patch_fields([
|
||||
("project_id", &patch.project_id),
|
||||
("location", &patch.location),
|
||||
("credential_file", &patch.credential_file),
|
||||
]),
|
||||
)
|
||||
}
|
||||
};
|
||||
if fields.iter().any(|(_, value)| *value == Some("")) {
|
||||
return Err(invalid(
|
||||
@@ -241,14 +211,7 @@ fn validate_custom_patch<'a>(
|
||||
}
|
||||
}
|
||||
let existing_name = existing.and_then(|config| config.get("name")?.as_str());
|
||||
if patch.env_key.is_some()
|
||||
&& existing.is_some_and(|config| {
|
||||
has_external_auth(config)
|
||||
|| existing_name
|
||||
.or(patch.provider_id.as_deref())
|
||||
.is_some_and(uses_builtin_auth)
|
||||
})
|
||||
{
|
||||
if patch.env_key.is_some() && existing.is_some_and(has_external_auth) {
|
||||
return Err(invalid(
|
||||
"Authentication is configured externally. Omit envKey to preserve it.",
|
||||
));
|
||||
@@ -260,12 +223,6 @@ fn validate_custom_patch<'a>(
|
||||
.or(existing_name)
|
||||
.filter(|name| !name.trim().is_empty())
|
||||
.ok_or_else(|| invalid("Enter a provider name."))?;
|
||||
// Legacy names select built-in authentication even on a custom provider.
|
||||
if uses_builtin_auth(name) {
|
||||
return Err(invalid(
|
||||
"This name is reserved for a built-in provider. Enter a different custom provider name.",
|
||||
));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
|
||||
@@ -1056,11 +1056,7 @@ writable_roots = ["~/code"]
|
||||
),
|
||||
);
|
||||
|
||||
let service = ConfigManager::new_for_tests(
|
||||
tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
loader_overrides,
|
||||
);
|
||||
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(), vec![], loader_overrides);
|
||||
|
||||
let response = service
|
||||
.write_value(ConfigValueWriteParams {
|
||||
@@ -1138,25 +1134,8 @@ async fn write_value_reports_override() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn provider_setup_checks_versions_and_provider_write_uses_last_write_wins() -> Result<()> {
|
||||
async fn provider_write_uses_last_write_wins() -> Result<()> {
|
||||
let tmp = tempdir()?;
|
||||
let service = ConfigManager::without_managed_config_for_tests(tmp.path().to_path_buf());
|
||||
let layers = service.load_config_layers(/*cwd*/ None).await?;
|
||||
let (write, _) = service.prepare_provider_config(
|
||||
&layers,
|
||||
codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID,
|
||||
[("aws.region", Some("us-west-2"))],
|
||||
)?;
|
||||
|
||||
let user_path = tmp.path().join(CONFIG_TOML_FILE);
|
||||
let newer_config = "model = 'newer'";
|
||||
std::fs::write(&user_path, newer_config)?;
|
||||
let error = service.commit_provider_config(write).await.unwrap_err();
|
||||
assert_eq!(
|
||||
error.write_error_code(),
|
||||
Some(ConfigWriteErrorCode::ConfigVersionConflict)
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(user_path)?, newer_config);
|
||||
// An intervening writer changes both the requested field and an omitted sibling.
|
||||
// The patch wins for the requested field and preserves the newer sibling value.
|
||||
std::fs::write(
|
||||
@@ -1266,141 +1245,6 @@ async fn write_value_defaults_to_user_config_path() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_provider_settings_use_the_active_profile_layer() -> Result<()> {
|
||||
use codex_app_server_protocol::CustomGatewaySettingsParams;
|
||||
use codex_app_server_protocol::GatewayAuth;
|
||||
use codex_app_server_protocol::ModelProviderConfigWriteParams;
|
||||
use codex_app_server_protocol::ModelProviderListParams;
|
||||
use codex_app_server_protocol::ProviderSettings;
|
||||
use codex_app_server_protocol::ProviderSettingsPatch;
|
||||
|
||||
let home = tempdir()?;
|
||||
let profile = home.path().join("work.config.toml");
|
||||
let system = home.path().join("system.toml");
|
||||
std::fs::write(
|
||||
&system,
|
||||
"model_provider = 'gcp'\n[model_providers.gateway]\nname = 'System'\nenv_key = 'SYSTEM_KEY'",
|
||||
)?;
|
||||
let overrides = LoaderOverrides {
|
||||
system_config_path: Some(system.clone()),
|
||||
user_config_path: Some(AbsolutePathBuf::from_absolute_path(&profile)?),
|
||||
user_config_profile: Some("work".parse()?),
|
||||
..LoaderOverrides::without_managed_config_for_tests()
|
||||
};
|
||||
let service = |cli_overrides| {
|
||||
ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
cli_overrides,
|
||||
overrides.clone(),
|
||||
)
|
||||
};
|
||||
let manager = service(vec![]);
|
||||
let list = ModelProviderListParams {};
|
||||
let initial = manager.model_provider_list(list.clone()).await?;
|
||||
assert_eq!(initial.default_provider_id, "gcp");
|
||||
assert!(initial.can_change_default);
|
||||
|
||||
std::fs::write(&profile, "model_provider = 'openai'")?;
|
||||
let write = ModelProviderConfigWriteParams {
|
||||
settings: ProviderSettingsPatch::CustomGateway(CustomGatewaySettingsParams {
|
||||
name: Some("Gateway".to_owned()),
|
||||
base_url: Some(Some("https://gateway.example.test".to_owned())),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
let created = manager.model_provider_config_write(write).await?;
|
||||
let selected = manager.model_provider_list(list.clone()).await?;
|
||||
assert_eq!(selected.default_provider_id, "openai");
|
||||
assert!(selected.can_change_default);
|
||||
assert!(selected.data[0].can_edit);
|
||||
|
||||
let write = ModelProviderConfigWriteParams {
|
||||
settings: ProviderSettingsPatch::CustomGateway(CustomGatewaySettingsParams {
|
||||
provider_id: Some(created.provider.id.clone()),
|
||||
name: Some("Renamed".to_owned()),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
manager.model_provider_config_write(write).await?;
|
||||
let saved: TomlValue = toml::from_str(&std::fs::read_to_string(&profile)?)?;
|
||||
assert_eq!(
|
||||
saved["model_providers"][&created.provider.id]["name"].as_str(),
|
||||
Some("Renamed")
|
||||
);
|
||||
assert!(!home.path().join(CONFIG_TOML_FILE).exists());
|
||||
|
||||
let inherited = |mut settings: serde_json::Value| {
|
||||
settings["type"] = "customGateway".into();
|
||||
settings["providerId"] = "gateway".into();
|
||||
serde_json::from_value(serde_json::json!({"settings":settings}))
|
||||
};
|
||||
let before = std::fs::read_to_string(&profile)?;
|
||||
manager
|
||||
.model_provider_config_write(inherited(serde_json::json!({"baseUrl":null}))?)
|
||||
.await?;
|
||||
assert_eq!(std::fs::read_to_string(&profile)?, before);
|
||||
|
||||
manager
|
||||
.model_provider_config_write(inherited(serde_json::json!({"envKey":"USER_KEY"}))?)
|
||||
.await?;
|
||||
let cleared = manager
|
||||
.model_provider_config_write(inherited(
|
||||
serde_json::json!({"name":"Work", "envKey":null}),
|
||||
)?)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
cleared.provider.settings,
|
||||
ProviderSettings::CustomGateway {
|
||||
auth: GatewayAuth::EnvironmentVariable {
|
||||
env_key: "SYSTEM_KEY".to_owned()
|
||||
}
|
||||
}
|
||||
);
|
||||
let saved: serde_json::Value = toml::from_str(&std::fs::read_to_string(&profile)?)?;
|
||||
assert_eq!(
|
||||
saved["model_providers"]["gateway"],
|
||||
serde_json::json!({"name":"Work"})
|
||||
);
|
||||
let pinned_manager = service(vec![(
|
||||
"model_providers.gateway.env_key".to_owned(),
|
||||
"CLI_KEY".into(),
|
||||
)]);
|
||||
let before = std::fs::read_to_string(&profile)?;
|
||||
let err = pinned_manager
|
||||
.model_provider_config_write(inherited(
|
||||
serde_json::json!({"name":"Must not save", "envKey":"USER_KEY"}),
|
||||
)?)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
err.write_error_code(),
|
||||
Some(ConfigWriteErrorCode::ConfigLayerReadonly)
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(&profile)?, before);
|
||||
let renamed = pinned_manager
|
||||
.model_provider_config_write(inherited(serde_json::json!({"name":"Allowed"}))?)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
(renamed.provider.name.as_str(), renamed.provider.settings),
|
||||
(
|
||||
"Allowed",
|
||||
ProviderSettings::CustomGateway {
|
||||
auth: GatewayAuth::EnvironmentVariable {
|
||||
env_key: "CLI_KEY".to_owned()
|
||||
}
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
let pinned = service(vec![("model_provider".to_owned(), "gcp".into())])
|
||||
.model_provider_list(list)
|
||||
.await?;
|
||||
assert_eq!(pinned.default_provider_id, "gcp");
|
||||
assert!(!pinned.can_change_default);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_value_defaults_to_selected_user_config_path() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
@@ -1413,11 +1257,7 @@ async fn write_value_defaults_to_selected_user_config_path() {
|
||||
loader_overrides.user_config_path =
|
||||
Some(AbsolutePathBuf::from_absolute_path(&selected_path).expect("selected config path"));
|
||||
loader_overrides.user_config_profile = Some("work".parse().expect("profile-v2 name"));
|
||||
let service = ConfigManager::new_for_tests(
|
||||
tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
loader_overrides,
|
||||
);
|
||||
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(), vec![], loader_overrides);
|
||||
service
|
||||
.write_value(ConfigValueWriteParams {
|
||||
file_path: None,
|
||||
@@ -1457,11 +1297,7 @@ async fn load_default_config_preserves_managed_requirements_and_selected_user_co
|
||||
LoaderOverrides::with_managed_config_path_for_tests(tmp.path().join("managed_config.toml"));
|
||||
loader_overrides.user_config_path = Some(selected_file.clone());
|
||||
loader_overrides.user_config_profile = Some("work".parse().expect("profile-v2 name"));
|
||||
let service = ConfigManager::new_for_tests(
|
||||
tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
loader_overrides,
|
||||
);
|
||||
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(), vec![], loader_overrides);
|
||||
|
||||
service
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
@@ -1624,7 +1460,8 @@ async fn thread_refresh_resolves_preserved_layers_before_materialization() -> Re
|
||||
.load_for_cwd(
|
||||
Some(HashMap::from([(
|
||||
"model_provider".to_string(),
|
||||
serde_json::json!("openai"),
|
||||
// aKode: `openai` is no longer built in; use a remaining built-in.
|
||||
serde_json::json!("ollama"),
|
||||
)])),
|
||||
ConfigOverrides::default(),
|
||||
Some(tmp.path().to_path_buf()),
|
||||
@@ -1650,7 +1487,7 @@ async fn thread_refresh_resolves_preserved_layers_before_materialization() -> Re
|
||||
let refreshed = service
|
||||
.load_latest_config_with_session_layers(&thread.config_layer_stack, &thread.cwd)
|
||||
.await?;
|
||||
assert_eq!(refreshed.model_provider_id, "openai");
|
||||
assert_eq!(refreshed.model_provider_id, "ollama");
|
||||
assert_eq!(refreshed.cwd, thread.cwd);
|
||||
assert_eq!(refreshed.log_dir, tmp.path().join("new-logs"));
|
||||
assert!(refreshed.features.enabled(Feature::SecretAuthStorage));
|
||||
@@ -1712,8 +1549,9 @@ async fn reserved_builtin_provider_override_rejected() {
|
||||
let error = service
|
||||
.write_value(ConfigValueWriteParams {
|
||||
file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()),
|
||||
key_path: "model_providers.openai.name".to_string(),
|
||||
value: serde_json::json!("OpenAI Override"),
|
||||
// aKode: `openai` is no longer a built-in provider; `ollama` stays reserved.
|
||||
key_path: "model_providers.ollama.name".to_string(),
|
||||
value: serde_json::json!("Ollama Override"),
|
||||
merge_strategy: MergeStrategy::Replace,
|
||||
expected_version: None,
|
||||
})
|
||||
@@ -1725,7 +1563,7 @@ async fn reserved_builtin_provider_override_rejected() {
|
||||
Some(ConfigWriteErrorCode::ConfigValidationError)
|
||||
);
|
||||
assert!(error.to_string().contains("reserved built-in provider IDs"));
|
||||
assert!(error.to_string().contains("`openai`"));
|
||||
assert!(error.to_string().contains("`ollama`"));
|
||||
|
||||
let contents = std::fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).expect("read config");
|
||||
assert_eq!(contents, "model = \"user\"\n");
|
||||
@@ -1763,16 +1601,18 @@ async fn write_value_rejects_feature_requirement_conflict() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "").unwrap();
|
||||
|
||||
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements(
|
||||
let service = ConfigManager::new_for_tests(
|
||||
tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements(
|
||||
r#"
|
||||
[features]
|
||||
fast_mode = true
|
||||
"#,
|
||||
))
|
||||
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
|
||||
);
|
||||
.loader_overrides_for_tests(tmp.path())
|
||||
.expect("write managed config fixture"),
|
||||
);
|
||||
|
||||
let error = service
|
||||
.write_value(ConfigValueWriteParams {
|
||||
@@ -1807,11 +1647,13 @@ async fn write_value_rejects_exact_managed_requirement() {
|
||||
let path = tmp.path().join(CONFIG_TOML_FILE);
|
||||
std::fs::write(&path, "allow_login_shell = true\n").unwrap();
|
||||
|
||||
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements("allow_login_shell = false"))
|
||||
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
|
||||
);
|
||||
let service = ConfigManager::new_for_tests(
|
||||
tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements("allow_login_shell = false"))
|
||||
.loader_overrides_for_tests(tmp.path())
|
||||
.expect("write managed config fixture"),
|
||||
);
|
||||
|
||||
let error = service
|
||||
.write_value(ConfigValueWriteParams {
|
||||
@@ -1840,9 +1682,10 @@ async fn write_value_rejects_managed_otel_values_and_preserves_unmanaged_sibling
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let path = tmp.path().join(CONFIG_TOML_FILE);
|
||||
std::fs::write(&path, "").expect("write user config");
|
||||
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements(
|
||||
let service = ConfigManager::new_for_tests(
|
||||
tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements(
|
||||
r#"[otel]
|
||||
tool_result = { max_bytes = 1024 }
|
||||
log_user_prompt = false
|
||||
@@ -1854,8 +1697,9 @@ metrics_exporter = "none"
|
||||
span_attributes = { "service.name" = "managed-service" }
|
||||
tracestate = { managed = { tenant = "enterprise" }, empty = {} }"#,
|
||||
))
|
||||
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
|
||||
);
|
||||
.loader_overrides_for_tests(tmp.path())
|
||||
.expect("write managed config fixture"),
|
||||
);
|
||||
for (key_path, managed) in [
|
||||
("otel", true),
|
||||
("otel.log_user_prompt", true),
|
||||
@@ -1925,11 +1769,13 @@ enabled = false
|
||||
"#,
|
||||
toml_path(tmp.path(), "managed-sqlite"),
|
||||
);
|
||||
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements(requirements))
|
||||
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
|
||||
);
|
||||
let service = ConfigManager::new_for_tests(
|
||||
tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements(requirements))
|
||||
.loader_overrides_for_tests(tmp.path())
|
||||
.expect("write managed config fixture"),
|
||||
);
|
||||
|
||||
let response = service
|
||||
.read(ConfigReadParams {
|
||||
@@ -1972,17 +1818,19 @@ span_attributes = { "service.name" = "user-service", "service.version" = "user-v
|
||||
tracestate = { managed = { tenant = "user-tenant", region = "us" }, local = { tenant = "preserved" }, empty = { tenant = "also-preserved" } }"#,
|
||||
)
|
||||
.expect("write user config");
|
||||
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements(
|
||||
let service = ConfigManager::new_for_tests(
|
||||
tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements(
|
||||
r#"[otel]
|
||||
log_user_prompt = false
|
||||
exporter = "none"
|
||||
span_attributes = { "service.name" = "managed-service" }
|
||||
tracestate = { managed = { tenant = "enterprise" }, empty = {} }"#,
|
||||
))
|
||||
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
|
||||
);
|
||||
.loader_overrides_for_tests(tmp.path())
|
||||
.expect("write managed config fixture"),
|
||||
);
|
||||
let response = service
|
||||
.read(ConfigReadParams {
|
||||
include_layers: false,
|
||||
@@ -2030,14 +1878,16 @@ async fn read_projects_managed_otel_tool_result_and_omits_its_origin() {
|
||||
tool_result = { max_bytes = 1234 }"#,
|
||||
)
|
||||
.expect("write user config");
|
||||
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements(
|
||||
let service = ConfigManager::new_for_tests(
|
||||
tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements(
|
||||
r#"[otel]
|
||||
tool_result = { max_bytes = 4096 }"#,
|
||||
))
|
||||
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
|
||||
);
|
||||
.loader_overrides_for_tests(tmp.path())
|
||||
.expect("write managed config fixture"),
|
||||
);
|
||||
|
||||
let response = service
|
||||
.read(ConfigReadParams {
|
||||
@@ -2112,15 +1962,17 @@ async fn write_value_allows_unmanaged_setting_with_exact_requirement() {
|
||||
let path = tmp.path().join(CONFIG_TOML_FILE);
|
||||
std::fs::write(&path, "").unwrap();
|
||||
|
||||
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements(
|
||||
let service = ConfigManager::new_for_tests(
|
||||
tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
(ManagedConfigFixture::requirements(
|
||||
r#"
|
||||
allow_login_shell = false
|
||||
"#,
|
||||
))
|
||||
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
|
||||
);
|
||||
.loader_overrides_for_tests(tmp.path())
|
||||
.expect("write managed config fixture"),
|
||||
);
|
||||
|
||||
service
|
||||
.write_value(ConfigValueWriteParams {
|
||||
@@ -2434,11 +2286,8 @@ async fn structured_feature_toggle_ignores_unrelated_managed_settings() -> Resul
|
||||
let mut loader_overrides = LoaderOverrides::with_managed_config_path_for_tests(managed_path);
|
||||
loader_overrides.user_config_path = Some(AbsolutePathBuf::from_absolute_path(&selected_path)?);
|
||||
loader_overrides.user_config_profile = Some("work".parse()?);
|
||||
let profile_service = ConfigManager::new_for_tests(
|
||||
tmp.path().to_path_buf(),
|
||||
vec![],
|
||||
loader_overrides,
|
||||
);
|
||||
let profile_service =
|
||||
ConfigManager::new_for_tests(tmp.path().to_path_buf(), vec![], loader_overrides);
|
||||
profile_service
|
||||
.write_value(ConfigValueWriteParams {
|
||||
file_path: Some(selected_path.display().to_string()),
|
||||
@@ -3333,13 +3182,15 @@ async fn model_provider_list_allows_user_overrides_of_system_defaults() -> Resul
|
||||
"System gateway",
|
||||
"environmentVariable",
|
||||
),
|
||||
// aKode: provider names no longer imply built-in auth, so a gateway named
|
||||
// "OpenAI" is an ordinary editable env-key gateway.
|
||||
(
|
||||
vec![("model_providers.team.name", "OpenAI")],
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
"OpenAI",
|
||||
"externallyConfigured",
|
||||
"environmentVariable",
|
||||
),
|
||||
(
|
||||
vec![("model_providers.team.name", " ")],
|
||||
@@ -3368,7 +3219,7 @@ async fn model_provider_list_allows_user_overrides_of_system_defaults() -> Resul
|
||||
assert_eq!(
|
||||
serde_json::to_value(response.data)?,
|
||||
serde_json::json!([
|
||||
{"id": "openai", "name": "OpenAI", "canEdit": false, "baseUrl":null, "settings":{"type":"openai"}},
|
||||
// aKode: no built-in `openai` provider is listed.
|
||||
{
|
||||
"id": "team", "name": name,
|
||||
"canEdit": can_edit, "baseUrl": "https://system.example.test/v1",
|
||||
@@ -3381,113 +3232,132 @@ async fn model_provider_list_allows_user_overrides_of_system_defaults() -> Resul
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_provider_list_checks_builtin_configuration_fields() -> Result<()> {
|
||||
async fn model_provider_settings_use_the_active_profile_layer() -> Result<()> {
|
||||
use codex_app_server_protocol::CustomGatewaySettingsParams;
|
||||
use codex_app_server_protocol::GatewayAuth;
|
||||
use codex_app_server_protocol::ModelProviderConfigWriteParams;
|
||||
use codex_app_server_protocol::ModelProviderListParams;
|
||||
use codex_app_server_protocol::ModelProviderSummary;
|
||||
use codex_app_server_protocol::ProviderSettings;
|
||||
use codex_app_server_protocol::ProviderSettingsPatch;
|
||||
|
||||
let home = tempdir()?;
|
||||
let profile = home.path().join("work.config.toml");
|
||||
let system = home.path().join("system.toml");
|
||||
std::fs::write(
|
||||
home.path().join(CONFIG_TOML_FILE),
|
||||
"[model_providers.amazon-bedrock.aws]\nregion = 'us-east-1'\n[model_providers.amazon-bedrock-runtime.aws]\nregion = 'us-east-1'\n[model_providers.gcp]\nproject_id = 'test-project'\n",
|
||||
&system,
|
||||
"model_provider = 'ollama'\n[model_providers.gateway]\nname = 'System'\nenv_key = 'SYSTEM_KEY'",
|
||||
)?;
|
||||
let credential_file = home.path().join("credentials.json").display().to_string();
|
||||
for (id, name, settings) in [
|
||||
(
|
||||
"amazon-bedrock",
|
||||
"Amazon Bedrock Mantle",
|
||||
&[("aws.profile", "default"), ("aws.region", "us-east-1")][..],
|
||||
),
|
||||
(
|
||||
"amazon-bedrock-runtime",
|
||||
"Amazon Bedrock Runtime",
|
||||
&[("aws.profile", "default"), ("aws.region", "us-east-1")][..],
|
||||
),
|
||||
(
|
||||
"gcp",
|
||||
"Google Cloud Vertex AI",
|
||||
&[
|
||||
("project_id", "test-project"),
|
||||
("location", "global"),
|
||||
("credential_file", credential_file.as_str()),
|
||||
][..],
|
||||
),
|
||||
] {
|
||||
for pinned_fields in [1, settings.len()] {
|
||||
let overrides = settings
|
||||
.iter()
|
||||
.take(pinned_fields)
|
||||
.map(|(field, value)| {
|
||||
(
|
||||
format!("model_providers.{id}.{field}"),
|
||||
TomlValue::String((*value).to_owned()),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let service = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
overrides,
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
);
|
||||
let list = service
|
||||
.model_provider_list(ModelProviderListParams {})
|
||||
.await?;
|
||||
assert_eq!(
|
||||
list.data.into_iter().find(|provider| provider.id == id),
|
||||
Some(ModelProviderSummary {
|
||||
id: id.to_owned(),
|
||||
name: name.to_owned(),
|
||||
can_edit: pinned_fields < settings.len(),
|
||||
base_url: None,
|
||||
settings: if id == "gcp" {
|
||||
ProviderSettings::Gcp {
|
||||
project_id: Some("test-project".to_owned()),
|
||||
location: (pinned_fields == settings.len())
|
||||
.then(|| "global".to_owned()),
|
||||
credential_file: (pinned_fields == settings.len())
|
||||
.then(|| credential_file.clone()),
|
||||
}
|
||||
} else {
|
||||
ProviderSettings::Bedrock {
|
||||
profile: Some("default".to_owned()),
|
||||
region: Some("us-east-1".to_owned()),
|
||||
}
|
||||
},
|
||||
})
|
||||
);
|
||||
let overrides = LoaderOverrides {
|
||||
system_config_path: Some(system.clone()),
|
||||
user_config_path: Some(AbsolutePathBuf::from_absolute_path(&profile)?),
|
||||
user_config_profile: Some("work".parse()?),
|
||||
..LoaderOverrides::without_managed_config_for_tests()
|
||||
};
|
||||
let service = |cli_overrides| {
|
||||
ConfigManager::new_for_tests(home.path().to_path_buf(), cli_overrides, overrides.clone())
|
||||
};
|
||||
let manager = service(vec![]);
|
||||
let list = ModelProviderListParams {};
|
||||
let initial = manager.model_provider_list(list.clone()).await?;
|
||||
assert_eq!(initial.default_provider_id, "ollama");
|
||||
assert!(initial.can_change_default);
|
||||
|
||||
std::fs::write(&profile, "model_provider = 'openai'")?;
|
||||
let write = ModelProviderConfigWriteParams {
|
||||
settings: ProviderSettingsPatch::CustomGateway(CustomGatewaySettingsParams {
|
||||
name: Some("Gateway".to_owned()),
|
||||
base_url: Some(Some("https://gateway.example.test".to_owned())),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
let created = manager.model_provider_config_write(write).await?;
|
||||
let selected = manager.model_provider_list(list.clone()).await?;
|
||||
assert_eq!(selected.default_provider_id, "openai");
|
||||
assert!(selected.can_change_default);
|
||||
assert!(selected.data[0].can_edit);
|
||||
|
||||
let write = ModelProviderConfigWriteParams {
|
||||
settings: ProviderSettingsPatch::CustomGateway(CustomGatewaySettingsParams {
|
||||
provider_id: Some(created.provider.id.clone()),
|
||||
name: Some("Renamed".to_owned()),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
manager.model_provider_config_write(write).await?;
|
||||
let saved: TomlValue = toml::from_str(&std::fs::read_to_string(&profile)?)?;
|
||||
assert_eq!(
|
||||
saved["model_providers"][&created.provider.id]["name"].as_str(),
|
||||
Some("Renamed")
|
||||
);
|
||||
assert!(!home.path().join(CONFIG_TOML_FILE).exists());
|
||||
|
||||
let inherited = |mut settings: serde_json::Value| {
|
||||
settings["type"] = "customGateway".into();
|
||||
settings["providerId"] = "gateway".into();
|
||||
serde_json::from_value(serde_json::json!({"settings":settings}))
|
||||
};
|
||||
let before = std::fs::read_to_string(&profile)?;
|
||||
manager
|
||||
.model_provider_config_write(inherited(serde_json::json!({"baseUrl":null}))?)
|
||||
.await?;
|
||||
assert_eq!(std::fs::read_to_string(&profile)?, before);
|
||||
|
||||
manager
|
||||
.model_provider_config_write(inherited(serde_json::json!({"envKey":"USER_KEY"}))?)
|
||||
.await?;
|
||||
let cleared = manager
|
||||
.model_provider_config_write(inherited(
|
||||
serde_json::json!({"name":"Work", "envKey":null}),
|
||||
)?)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
cleared.provider.settings,
|
||||
ProviderSettings::CustomGateway {
|
||||
auth: GatewayAuth::EnvironmentVariable {
|
||||
env_key: "SYSTEM_KEY".to_owned()
|
||||
}
|
||||
}
|
||||
}
|
||||
for id in ["amazon-bedrock", "amazon-bedrock-runtime"] {
|
||||
for (section, overrides) in [
|
||||
("auth", vec![]),
|
||||
(
|
||||
"aws.credential_export",
|
||||
vec![(
|
||||
format!("model_providers.{id}.aws.region"),
|
||||
"us-east-1".into(),
|
||||
)],
|
||||
),
|
||||
] {
|
||||
std::fs::write(
|
||||
home.path().join(CONFIG_TOML_FILE),
|
||||
format!("[model_providers.{id}.{section}]\ncommand = 'helper'\n"),
|
||||
)?;
|
||||
let service = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
overrides,
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
);
|
||||
let list = service
|
||||
.model_provider_list(ModelProviderListParams {})
|
||||
.await?;
|
||||
assert_eq!(
|
||||
list.data
|
||||
.into_iter()
|
||||
.find(|provider| provider.id == id)
|
||||
.map(|provider| provider.can_edit),
|
||||
Some(false)
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
let saved: serde_json::Value = toml::from_str(&std::fs::read_to_string(&profile)?)?;
|
||||
assert_eq!(
|
||||
saved["model_providers"]["gateway"],
|
||||
serde_json::json!({"name":"Work"})
|
||||
);
|
||||
let pinned_manager = service(vec![(
|
||||
"model_providers.gateway.env_key".to_owned(),
|
||||
"CLI_KEY".into(),
|
||||
)]);
|
||||
let before = std::fs::read_to_string(&profile)?;
|
||||
let err = pinned_manager
|
||||
.model_provider_config_write(inherited(
|
||||
serde_json::json!({"name":"Must not save", "envKey":"USER_KEY"}),
|
||||
)?)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
err.write_error_code(),
|
||||
Some(ConfigWriteErrorCode::ConfigLayerReadonly)
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(&profile)?, before);
|
||||
let renamed = pinned_manager
|
||||
.model_provider_config_write(inherited(serde_json::json!({"name":"Allowed"}))?)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
(renamed.provider.name.as_str(), renamed.provider.settings),
|
||||
(
|
||||
"Allowed",
|
||||
ProviderSettings::CustomGateway {
|
||||
auth: GatewayAuth::EnvironmentVariable {
|
||||
env_key: "CLI_KEY".to_owned()
|
||||
}
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
let pinned = service(vec![("model_provider".to_owned(), "ollama".into())])
|
||||
.model_provider_list(list)
|
||||
.await?;
|
||||
assert_eq!(pinned.default_provider_id, "ollama");
|
||||
assert!(!pinned.can_change_default);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -868,6 +868,23 @@ mod tests {
|
||||
use tempfile::TempDir;
|
||||
|
||||
async fn build_test_config(codex_home: &Path) -> Config {
|
||||
// aKode has no built-in default provider or bundled catalog seed; give the
|
||||
// runtime the bundled catalog explicitly so thread/start resolves a model.
|
||||
let catalog_path = codex_home.join("test-models.json");
|
||||
std::fs::write(
|
||||
&catalog_path,
|
||||
include_str!("../../models-manager/models.json"),
|
||||
)
|
||||
.expect("write test model catalog");
|
||||
std::fs::write(
|
||||
codex_home.join(codex_config::CONFIG_TOML_FILE),
|
||||
format!(
|
||||
"model_catalog_json = {}\n",
|
||||
serde_json::to_string(&catalog_path.display().to_string())
|
||||
.expect("serialize catalog path")
|
||||
),
|
||||
)
|
||||
.expect("write test config");
|
||||
match ConfigBuilder::default()
|
||||
.codex_home(codex_home.to_path_buf())
|
||||
.build()
|
||||
|
||||
@@ -8,8 +8,6 @@ use codex_config::NoopThreadConfigLoader;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core::config::ConfigOverrides;
|
||||
use codex_core::config::set_project_trust_level;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::DEFAULT_CHATGPT_BASE_URL;
|
||||
use codex_protocol::config_types::TrustLevel;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
@@ -67,24 +65,6 @@ async fn startup_reloads_the_callers_selected_project() -> anyhow::Result<()> {
|
||||
);
|
||||
assert_eq!(config.chatgpt_base_url, selected_url);
|
||||
|
||||
let marked = CodexAuth::from_api_key("sk-proj-fedramp-test-key");
|
||||
for (configured_url, expected_url) in [
|
||||
(None, "https://gov.chatgpt.com/backend-api/"),
|
||||
(Some(DEFAULT_CHATGPT_BASE_URL), DEFAULT_CHATGPT_BASE_URL),
|
||||
] {
|
||||
let setting = configured_url
|
||||
.map(|url| format!("chatgpt_base_url = '{url}'\n"))
|
||||
.unwrap_or_default();
|
||||
std::fs::write(&user_config, format!("{setting}{trust}"))?;
|
||||
let _auth = configure(
|
||||
&manager,
|
||||
&mut config,
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(config.chatgpt_backend_url().resolve(&marked), expected_url);
|
||||
}
|
||||
|
||||
std::fs::write(&project_config, "[malformed")?;
|
||||
let error = configure(
|
||||
&manager,
|
||||
|
||||
@@ -441,9 +441,19 @@ enabled = false
|
||||
let bad_cwd = temp_dir.path().join("bad");
|
||||
std::fs::create_dir_all(&good_cwd)?;
|
||||
std::fs::create_dir_all(&bad_cwd)?;
|
||||
// aKode has no built-in default provider or bundled catalog seed; give the
|
||||
// test threads the bundled catalog explicitly so a default model resolves.
|
||||
let catalog_path = temp_dir.path().join("test-models.json");
|
||||
std::fs::write(
|
||||
&catalog_path,
|
||||
include_str!("../../models-manager/models.json"),
|
||||
)?;
|
||||
std::fs::write(
|
||||
temp_dir.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
"[features]\nsecret_auth_storage = false\n",
|
||||
format!(
|
||||
"model_catalog_json = {}\n[features]\nsecret_auth_storage = false\n",
|
||||
serde_json::to_string(&catalog_path.display().to_string())?
|
||||
),
|
||||
)?;
|
||||
|
||||
let initial_config_manager =
|
||||
|
||||
@@ -45,7 +45,6 @@ use crate::request_processors::ThreadRequestProcessor;
|
||||
use crate::request_processors::ThreadResumeTarget;
|
||||
use crate::request_processors::TurnRequestProcessor;
|
||||
use crate::request_processors::WindowsSandboxRequestProcessor;
|
||||
use crate::request_processors::account_processor::handle_gcp_setup;
|
||||
use crate::request_processors::read_server_diagnostics;
|
||||
use crate::request_serialization::QueuedInitializedRequest;
|
||||
use crate::request_serialization::RequestSerializationQueueKey;
|
||||
@@ -927,8 +926,7 @@ impl MessageProcessor {
|
||||
)
|
||||
.await?;
|
||||
if connection_initialized {
|
||||
self.connection_initialized(connection_id)
|
||||
.await;
|
||||
self.connection_initialized(connection_id).await;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -1702,20 +1700,6 @@ impl MessageProcessor {
|
||||
.login_account(request_id.clone(), params)
|
||||
.await
|
||||
}
|
||||
ClientRequest::BedrockDiscover { params, .. } => {
|
||||
self.account_processor.bedrock_discover(params).await
|
||||
}
|
||||
ClientRequest::BedrockSetup { params, .. } => {
|
||||
self.account_processor.bedrock_setup(params).await
|
||||
}
|
||||
ClientRequest::GcpSetup { params, .. } => {
|
||||
handle_gcp_setup(&self.account_processor, params).await
|
||||
}
|
||||
ClientRequest::BedrockCheckGovCloudRequirements { .. } => {
|
||||
self.account_processor
|
||||
.bedrock_check_gov_cloud_requirements()
|
||||
.await
|
||||
}
|
||||
ClientRequest::GatewayOAuthRead { params, .. } => Box::pin(
|
||||
self.account_processor
|
||||
.gateway_oauth_read(params.unwrap_or_default()),
|
||||
@@ -1866,4 +1850,3 @@ mod gateway_oauth_tests;
|
||||
#[cfg(test)]
|
||||
#[path = "message_processor_thread_lifecycle_tests.rs"]
|
||||
mod thread_lifecycle_tests;
|
||||
|
||||
|
||||
@@ -331,9 +331,7 @@ async fn disconnected_v2_child_lifecycle(unload_delay_secs: u64, ephemeral: bool
|
||||
.await;
|
||||
let _: InitializeResponse =
|
||||
read_response_from(&mut outgoing, owner_id, /*request_id*/ 1).await;
|
||||
processor
|
||||
.connection_initialized(owner_id)
|
||||
.await;
|
||||
processor.connection_initialized(owner_id).await;
|
||||
send_request(
|
||||
&processor,
|
||||
owner_id,
|
||||
@@ -607,9 +605,7 @@ decision = "prompt-user"
|
||||
.await;
|
||||
let _: InitializeResponse =
|
||||
read_response_from(&mut outgoing, id, /*request_id*/ 1).await;
|
||||
processor
|
||||
.connection_initialized(id)
|
||||
.await;
|
||||
processor.connection_initialized(id).await;
|
||||
}
|
||||
send_request(
|
||||
&processor,
|
||||
@@ -679,9 +675,7 @@ decision = "prompt-user"
|
||||
.await;
|
||||
let _: InitializeResponse =
|
||||
read_response_from(&mut outgoing, unrelated_id, /*request_id*/ 1).await;
|
||||
processor
|
||||
.connection_initialized(unrelated_id)
|
||||
.await;
|
||||
processor.connection_initialized(unrelated_id).await;
|
||||
for connection_id in [incompatible_id, unrelated_id] {
|
||||
processor
|
||||
.process_response(
|
||||
|
||||
@@ -3,14 +3,12 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_features::Feature;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
use codex_protocol::openai_models::ModelPreset;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::config_manager::ConfigManager;
|
||||
@@ -50,16 +48,6 @@ impl ModelCatalog {
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the same startup context used to reload the catalog after account setup.
|
||||
pub(crate) async fn load_startup_config_layers(&self) -> std::io::Result<ConfigLayerStack> {
|
||||
let cwd = self
|
||||
.startup_cwd
|
||||
.as_deref()
|
||||
.map(AbsolutePathBuf::from_absolute_path)
|
||||
.transpose()?;
|
||||
self.config_manager.load_config_layers(cwd).await
|
||||
}
|
||||
|
||||
/// Marks catalog configuration stale after an account transition.
|
||||
pub(crate) async fn invalidate(&self) {
|
||||
self.state.lock().await.needs_reload = true;
|
||||
|
||||
@@ -196,12 +196,13 @@ async fn refreshes_immediately_periodically_and_stops_when_dropped() {
|
||||
));
|
||||
|
||||
// The catalog follows a new managed route without reusing the old endpoint.
|
||||
std::fs::write(&requirements_path, "model_provider = 'openai'").unwrap();
|
||||
// aKode: `openai` is no longer built in; route to the other remaining built-in.
|
||||
std::fs::write(&requirements_path, "model_provider = 'lmstudio'").unwrap();
|
||||
catalog.invalidate().await;
|
||||
catalog.list_models(RefreshStrategy::Offline).await.unwrap();
|
||||
assert_eq!(
|
||||
catalog.current().await.unwrap().0.model_provider_id,
|
||||
"openai"
|
||||
"lmstudio"
|
||||
);
|
||||
std::fs::remove_file(&requirements_path).unwrap();
|
||||
catalog.invalidate().await;
|
||||
@@ -312,6 +313,20 @@ async fn background_refresh_blocks_invalid_requirements_then_recovers() -> anyho
|
||||
#[tokio::test]
|
||||
async fn catalog_reload_recovers_after_requirements_failure() -> anyhow::Result<()> {
|
||||
let home = tempdir()?;
|
||||
// aKode: providers without a catalog URL no longer fall back to the bundled catalog
|
||||
// (ollama would list its local server); configure the bundled catalog explicitly.
|
||||
let catalog_path = home.path().join("test-models.json");
|
||||
std::fs::write(
|
||||
&catalog_path,
|
||||
include_str!("../../models-manager/models.json"),
|
||||
)?;
|
||||
std::fs::write(
|
||||
home.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
format!(
|
||||
"model_catalog_json = {}\n",
|
||||
serde_json::to_string(&catalog_path.display().to_string())?
|
||||
),
|
||||
)?;
|
||||
let requirements_path = home.path().join("requirements.toml");
|
||||
std::fs::write(&requirements_path, "model_provider = 'ollama'")?;
|
||||
let manager = crate::config_manager::ConfigManager::new_for_tests(
|
||||
@@ -336,7 +351,8 @@ async fn catalog_reload_recovers_after_requirements_failure() -> anyhow::Result<
|
||||
));
|
||||
std::fs::write(&requirements_path, "[malformed")?;
|
||||
catalog.invalidate().await;
|
||||
assert_eq!(catalog.current().await?.0.model_provider_id, "openai");
|
||||
// aKode: the fallback config has no default provider (previously `openai`).
|
||||
assert_eq!(catalog.current().await?.0.model_provider_id, "");
|
||||
assert!(catalog.list_models(RefreshStrategy::Offline).await.is_err());
|
||||
std::fs::write(&requirements_path, "model_provider = 'ollama'")?;
|
||||
// Exercise the same online request used by the periodic background worker.
|
||||
|
||||
@@ -328,7 +328,6 @@ use codex_git_utils::resolve_root_git_project_for_trust;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::login_with_api_key;
|
||||
use codex_login::login_with_bedrock_api_key;
|
||||
use codex_mcp::McpRuntimeContext;
|
||||
use codex_mcp::McpServerStatusSnapshot;
|
||||
use codex_mcp::McpSnapshotDetail;
|
||||
@@ -445,7 +444,6 @@ use uuid::Uuid;
|
||||
use codex_app_server_protocol::ServerRequest;
|
||||
|
||||
pub(crate) mod account_processor;
|
||||
mod bedrock_auth;
|
||||
mod catalog_processor;
|
||||
mod command_exec_processor;
|
||||
pub(crate) mod config_processor;
|
||||
|
||||
@@ -1,43 +1,18 @@
|
||||
use super::bedrock_auth::BedrockProviderConfig;
|
||||
use super::bedrock_auth::clear_user_model_provider_if_bedrock;
|
||||
use super::bedrock_auth::prepare_bedrock_provider;
|
||||
use super::config_processor::map_error as map_config_error;
|
||||
use super::*;
|
||||
use crate::auth_mode::auth_mode_to_api;
|
||||
use crate::model_catalog::ModelCatalog;
|
||||
use crate::outgoing_message::AccountNotification;
|
||||
use codex_login::login_with_bedrock_access_keys;
|
||||
use codex_model_provider::is_supported_amazon_bedrock_region;
|
||||
|
||||
mod account_read;
|
||||
mod bedrock_gov_cloud;
|
||||
mod bedrock_setup;
|
||||
mod gateway_oauth;
|
||||
mod gcp_setup;
|
||||
mod security_setup;
|
||||
|
||||
pub(crate) use gcp_setup::handle_gcp_setup;
|
||||
|
||||
enum RefreshTokenRequestOutcome {
|
||||
NotAttemptedOrSucceeded,
|
||||
FailedTransiently,
|
||||
FailedPermanently,
|
||||
}
|
||||
|
||||
enum CloudLoginProvider {
|
||||
AmazonBedrock,
|
||||
Gcp,
|
||||
}
|
||||
|
||||
enum BedrockLoginCredentials {
|
||||
ApiKey(String),
|
||||
AccessKeys {
|
||||
access_key_id: String,
|
||||
secret_access_key: String,
|
||||
session_token: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct AccountRequestProcessor {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
@@ -178,50 +153,6 @@ impl AccountRequestProcessor {
|
||||
self.login_api_key_v2(request_id, LoginApiKeyParams { api_key })
|
||||
.await;
|
||||
}
|
||||
LoginAccountParams::AmazonBedrock { api_key, region } => {
|
||||
self.login_amazon_bedrock_v2(
|
||||
request_id,
|
||||
BedrockLoginCredentials::ApiKey(api_key),
|
||||
region,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
LoginAccountParams::AmazonBedrockAccessKeys {
|
||||
access_key_id,
|
||||
secret_access_key,
|
||||
session_token,
|
||||
region,
|
||||
} => {
|
||||
self.login_amazon_bedrock_v2(
|
||||
request_id,
|
||||
BedrockLoginCredentials::AccessKeys {
|
||||
access_key_id,
|
||||
secret_access_key,
|
||||
session_token,
|
||||
},
|
||||
region,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_provider_login_allowed(
|
||||
&self,
|
||||
provider: CloudLoginProvider,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
if !self
|
||||
.auth_manager
|
||||
.is_login_method_allowed(ForcedLoginMethod::Api)
|
||||
{
|
||||
let operation = match provider {
|
||||
CloudLoginProvider::AmazonBedrock => "Amazon Bedrock login",
|
||||
CloudLoginProvider::Gcp => "Google Cloud setup",
|
||||
};
|
||||
return Err(invalid_request(format!(
|
||||
"{operation} is disabled by the configured login policy."
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -270,99 +201,6 @@ impl AccountRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
async fn login_amazon_bedrock_v2(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
credentials: BedrockLoginCredentials,
|
||||
region: String,
|
||||
) {
|
||||
let result = async {
|
||||
self.ensure_provider_login_allowed(CloudLoginProvider::AmazonBedrock)?;
|
||||
|
||||
match &credentials {
|
||||
BedrockLoginCredentials::ApiKey(api_key) => {
|
||||
if api_key.trim().is_empty() {
|
||||
return Err(invalid_request("Amazon Bedrock API key must not be empty."));
|
||||
}
|
||||
}
|
||||
BedrockLoginCredentials::AccessKeys {
|
||||
access_key_id,
|
||||
secret_access_key,
|
||||
..
|
||||
} => {
|
||||
if access_key_id.trim().is_empty() || secret_access_key.trim().is_empty() {
|
||||
return Err(invalid_request(
|
||||
"AWS access key ID and secret access key must not be empty.",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let region = region.trim();
|
||||
if !is_supported_amazon_bedrock_region(region) {
|
||||
return Err(invalid_request(format!(
|
||||
"Amazon Bedrock does not support region `{region}`"
|
||||
)));
|
||||
}
|
||||
|
||||
self.cancel_active_login().await;
|
||||
let write = prepare_bedrock_provider(
|
||||
&self.config_manager,
|
||||
BedrockProviderConfig {
|
||||
region: matches!(&credentials, BedrockLoginCredentials::AccessKeys { .. })
|
||||
.then_some(region),
|
||||
profile: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
self.config_manager
|
||||
.commit_provider_config(write)
|
||||
.await
|
||||
.map_err(map_config_error)?;
|
||||
|
||||
match credentials {
|
||||
BedrockLoginCredentials::ApiKey(api_key) => login_with_bedrock_api_key(
|
||||
&self.config.codex_home,
|
||||
api_key.trim(),
|
||||
region,
|
||||
self.config.cli_auth_credentials_store_mode,
|
||||
self.config.auth_keyring_backend_kind(),
|
||||
),
|
||||
BedrockLoginCredentials::AccessKeys {
|
||||
access_key_id,
|
||||
secret_access_key,
|
||||
session_token,
|
||||
} => {
|
||||
let session_token = session_token
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|token| !token.is_empty());
|
||||
login_with_bedrock_access_keys(
|
||||
&self.config.codex_home,
|
||||
access_key_id.trim(),
|
||||
secret_access_key.trim(),
|
||||
session_token,
|
||||
self.config.cli_auth_credentials_store_mode,
|
||||
self.config.auth_keyring_backend_kind(),
|
||||
)
|
||||
}
|
||||
}
|
||||
.map_err(|err| internal_error(format!("failed to save Amazon Bedrock auth: {err}")))?;
|
||||
self.auth_manager.reload().await;
|
||||
Ok(LoginAccountResponse::AmazonBedrock {})
|
||||
}
|
||||
.await;
|
||||
let logged_in = result.is_ok();
|
||||
if logged_in {
|
||||
self.model_catalog.invalidate().await;
|
||||
}
|
||||
self.outgoing.send_result(request_id, result).await;
|
||||
|
||||
if logged_in {
|
||||
self.send_login_success_notifications(/*login_id*/ None)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn cancel_login_response(
|
||||
&self,
|
||||
params: CancelLoginAccountParams,
|
||||
@@ -582,8 +420,7 @@ pub(crate) async fn clear_account_configuration(
|
||||
config_manager: &ConfigManager,
|
||||
config: &Config,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
if config.model_provider.is_amazon_bedrock() {
|
||||
clear_user_model_provider_if_bedrock(config_manager, config).await?;
|
||||
}
|
||||
// No built-in cloud provider keeps account-scoped settings in config.toml.
|
||||
let _ = (config_manager, config);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
//! Post-login GovCloud checks use current authentication and freshly loaded configuration.
|
||||
//! Official endpoint hostnames take precedence over credential and configured AWS regions.
|
||||
//! Results are advisory; configuration and region resolution failures remain RPC errors.
|
||||
|
||||
use super::AccountRequestProcessor;
|
||||
use crate::error_code::internal_error;
|
||||
use codex_app_server_protocol::BedrockCheckGovCloudRequirementsResponse;
|
||||
use codex_app_server_protocol::ClientResponsePayload;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_config::NetworkDomainPermissionToml;
|
||||
use codex_model_provider::is_amazon_bedrock_gov_cloud_region;
|
||||
use codex_model_provider::resolve_amazon_bedrock_region;
|
||||
use codex_protocol::config_types::ForcedLoginMethod;
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) async fn bedrock_check_gov_cloud_requirements(
|
||||
&self,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to load configuration: {err}")))?;
|
||||
let provider = &config.model_provider;
|
||||
if !provider.is_amazon_bedrock() {
|
||||
return Ok(Some(
|
||||
BedrockCheckGovCloudRequirementsResponse {
|
||||
is_gov_cloud: false,
|
||||
should_warn: false,
|
||||
}
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
|
||||
let endpoint_domain = provider
|
||||
.base_url
|
||||
.as_deref()
|
||||
.map(|base_url| {
|
||||
url::Url::parse(base_url)
|
||||
.ok()
|
||||
.and_then(|url| {
|
||||
url.host_str()
|
||||
.map(|host| host.trim_end_matches('.').to_string())
|
||||
})
|
||||
.ok_or_else(|| internal_error("Amazon Bedrock endpoint has no valid hostname"))
|
||||
})
|
||||
.transpose()?;
|
||||
let endpoint_region = endpoint_domain.as_deref().and_then(|domain| {
|
||||
let (service, rest) = domain.split_once('.')?;
|
||||
let region = match service {
|
||||
"bedrock-mantle" => rest.strip_suffix(".api.aws"),
|
||||
"bedrock-runtime" | "bedrock-runtime-fips" => rest.strip_suffix(".amazonaws.com"),
|
||||
_ => None,
|
||||
}?;
|
||||
// Require a single region label, not a substring in a proxy hostname.
|
||||
(!region.is_empty() && !region.contains('.')).then_some(region)
|
||||
});
|
||||
let region = match endpoint_region {
|
||||
Some(region) => region.to_string(),
|
||||
None => {
|
||||
resolve_amazon_bedrock_region(provider.clone(), Some(self.auth_manager.clone()))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to resolve Amazon Bedrock region: {err}"))
|
||||
})?
|
||||
}
|
||||
};
|
||||
let is_gov_cloud = is_amazon_bedrock_gov_cloud_region(®ion);
|
||||
let mut should_warn = false;
|
||||
if is_gov_cloud {
|
||||
let domain = if let Some(domain) = endpoint_domain {
|
||||
domain
|
||||
} else if provider.is_amazon_bedrock_runtime() {
|
||||
format!("bedrock-runtime.{region}.amazonaws.com")
|
||||
} else {
|
||||
format!("bedrock-mantle.{region}.api.aws")
|
||||
};
|
||||
let requirements = config.config_layer_stack.requirements_toml();
|
||||
let api_only = requirements
|
||||
.allowed_login_methods
|
||||
.as_ref()
|
||||
.is_some_and(|methods| {
|
||||
!methods.is_empty()
|
||||
&& methods
|
||||
.iter()
|
||||
.all(|method| *method == ForcedLoginMethod::Api)
|
||||
});
|
||||
let network_allowed = requirements
|
||||
.application
|
||||
.as_ref()
|
||||
.and_then(|application| application.network.as_ref())
|
||||
.is_some_and(|network| {
|
||||
network.enabled
|
||||
&& network.domains.get(&domain) == Some(&NetworkDomainPermissionToml::Allow)
|
||||
});
|
||||
should_warn = !api_only || !network_allowed;
|
||||
}
|
||||
|
||||
Ok(Some(
|
||||
BedrockCheckGovCloudRequirementsResponse {
|
||||
is_gov_cloud,
|
||||
should_warn,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
use super::super::bedrock_auth::BedrockProviderConfig;
|
||||
use super::super::bedrock_auth::prepare_bedrock_provider;
|
||||
use super::super::config_processor::map_error as map_config_error;
|
||||
use super::AccountRequestProcessor;
|
||||
use super::CloudLoginProvider;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use codex_app_server_protocol::AwsCredentialType;
|
||||
use codex_app_server_protocol::BedrockAwsProfile;
|
||||
use codex_app_server_protocol::BedrockDiscoverParams;
|
||||
use codex_app_server_protocol::BedrockDiscoverResponse;
|
||||
use codex_app_server_protocol::BedrockEnvironmentCredential;
|
||||
use codex_app_server_protocol::BedrockSetupParams;
|
||||
use codex_app_server_protocol::BedrockSetupResponse;
|
||||
use codex_app_server_protocol::ClientResponsePayload;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::is_supported_amazon_bedrock_region;
|
||||
|
||||
const AWS_ACCESS_KEY_ID: &str = "AWS_ACCESS_KEY_ID";
|
||||
const AWS_SECRET_ACCESS_KEY: &str = "AWS_SECRET_ACCESS_KEY";
|
||||
const AWS_BEARER_TOKEN_BEDROCK: &str = "AWS_BEARER_TOKEN_BEDROCK";
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) async fn bedrock_discover(
|
||||
&self,
|
||||
_params: BedrockDiscoverParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.ensure_provider_login_allowed(CloudLoginProvider::AmazonBedrock)?;
|
||||
let profiles = codex_aws_auth::discover_aws_profiles()
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to discover AWS profiles: {err}")))?
|
||||
.into_iter()
|
||||
.map(|profile| BedrockAwsProfile {
|
||||
name: profile.name,
|
||||
region: profile.region,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let region = non_empty_env_var("AWS_REGION");
|
||||
let environment_credentials = [
|
||||
(
|
||||
AwsCredentialType::AccessKeys,
|
||||
non_empty_env_var(AWS_ACCESS_KEY_ID).is_some()
|
||||
&& non_empty_env_var(AWS_SECRET_ACCESS_KEY).is_some(),
|
||||
),
|
||||
(
|
||||
AwsCredentialType::BedrockApiKey,
|
||||
non_empty_env_var(AWS_BEARER_TOKEN_BEDROCK).is_some(),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|(_, available)| *available)
|
||||
.map(|(credential_type, _)| BedrockEnvironmentCredential {
|
||||
credential_type,
|
||||
region: region.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Some(
|
||||
BedrockDiscoverResponse {
|
||||
profiles,
|
||||
environment_credentials,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn bedrock_setup(
|
||||
&self,
|
||||
params: BedrockSetupParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.ensure_provider_login_allowed(CloudLoginProvider::AmazonBedrock)?;
|
||||
let (profile, region) = match ¶ms {
|
||||
BedrockSetupParams::Profile { profile, region } => {
|
||||
(Some(profile.trim()), region.trim())
|
||||
}
|
||||
BedrockSetupParams::Environment { region } => (None, region.trim()),
|
||||
};
|
||||
let write = prepare_bedrock_provider(
|
||||
&self.config_manager,
|
||||
BedrockProviderConfig {
|
||||
region: Some(region),
|
||||
profile,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
if profile.is_none()
|
||||
&& matches!(
|
||||
self.auth_manager.auth_cached(),
|
||||
Some(CodexAuth::BedrockApiKey(_) | CodexAuth::BedrockAccessKeys(_))
|
||||
)
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"Codex-managed Bedrock credentials are already configured and take priority over AWS environment credentials. Run `codex logout` and try again.",
|
||||
));
|
||||
}
|
||||
|
||||
if !is_supported_amazon_bedrock_region(region) {
|
||||
return Err(invalid_request(format!(
|
||||
"Amazon Bedrock does not support region `{region}`"
|
||||
)));
|
||||
}
|
||||
|
||||
if let Some(profile) = profile {
|
||||
if profile.is_empty() {
|
||||
return Err(invalid_request("AWS profile name must not be empty."));
|
||||
}
|
||||
codex_aws_auth::validate_aws_profile(
|
||||
profile,
|
||||
region,
|
||||
self.config.http_client_factory(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
invalid_request(format!(
|
||||
"failed to load credentials for AWS profile `{profile}`: {err}"
|
||||
))
|
||||
})?;
|
||||
} else {
|
||||
let has_bedrock_api_key = non_empty_env_var(AWS_BEARER_TOKEN_BEDROCK).is_some();
|
||||
let has_access_keys = non_empty_env_var(AWS_ACCESS_KEY_ID).is_some()
|
||||
&& non_empty_env_var(AWS_SECRET_ACCESS_KEY).is_some();
|
||||
if !has_bedrock_api_key && !has_access_keys {
|
||||
return Err(invalid_request(
|
||||
"No AWS credentials found. Please Configure AWS credentials or complete AWS sign-in, then try again.",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Validate the selected credentials against Bedrock ListModels once supported.
|
||||
self.cancel_active_login().await;
|
||||
self.config_manager
|
||||
.commit_provider_config(write)
|
||||
.await
|
||||
.map_err(map_config_error)?;
|
||||
self.model_catalog.invalidate().await;
|
||||
|
||||
Ok(Some(BedrockSetupResponse {}.into()))
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty_env_var(name: &str) -> Option<String> {
|
||||
std::env::var(name)
|
||||
.ok()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
@@ -1,207 +0,0 @@
|
||||
//! Validates and persists GCP setup without changing saved login credentials or existing threads.
|
||||
|
||||
use super::super::config_processor::map_error as map_config_error;
|
||||
use super::AccountRequestProcessor;
|
||||
use super::CloudLoginProvider;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use codex_app_server_protocol::ClientResponsePayload;
|
||||
use codex_app_server_protocol::GcpSetupParams;
|
||||
use codex_app_server_protocol::GcpSetupResponse;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_config::apply_default_gcp_auth;
|
||||
use codex_login::RefreshTokenError;
|
||||
use codex_model_provider::create_model_provider;
|
||||
use codex_model_provider_info::GCP_PROVIDER_ID;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::merge_gcp_provider_overrides;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::Serialize;
|
||||
use serde::de::MapAccess;
|
||||
use serde::de::Visitor;
|
||||
use serde::de::value::MapAccessDeserializer;
|
||||
use serde_json::json;
|
||||
use std::fmt;
|
||||
use std::io::BufReader;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tokio::fs::File;
|
||||
|
||||
pub(crate) async fn handle_gcp_setup(
|
||||
processor: &AccountRequestProcessor,
|
||||
params: GcpSetupParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
processor.ensure_provider_login_allowed(CloudLoginProvider::Gcp)?;
|
||||
let network_policy = processor
|
||||
.auth_manager
|
||||
.application_network_policy()
|
||||
.for_current_account();
|
||||
let layers = processor
|
||||
.model_catalog
|
||||
.load_startup_config_layers()
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to load configuration layers: {err}")))?;
|
||||
let (write, provider) = processor
|
||||
.config_manager
|
||||
.prepare_provider_config(
|
||||
&layers,
|
||||
GCP_PROVIDER_ID,
|
||||
[
|
||||
("project_id", Some(params.project_id.trim())),
|
||||
(
|
||||
"location",
|
||||
Some(params.location.as_deref().unwrap_or("global").trim()),
|
||||
),
|
||||
("credential_file", params.credential_file.as_deref()),
|
||||
],
|
||||
)
|
||||
.map_err(map_config_error)?;
|
||||
if provider.base_url.is_some() {
|
||||
return Err(invalid_request(
|
||||
"Google Cloud has a custom `base_url`. Clear `model_providers.gcp.base_url` before configuring a project and location.",
|
||||
));
|
||||
}
|
||||
// Even checking a Windows UNC credential path can contact the remote host.
|
||||
let permit = network_policy
|
||||
.acquire_for_unsupported_sdk()
|
||||
.map_err(|err| invalid_request(err.to_string()))?;
|
||||
permit
|
||||
.run(verify_credentials(provider, &processor.config.cwd))
|
||||
.await
|
||||
.map_err(|err| invalid_request(err.to_string()))??;
|
||||
|
||||
processor
|
||||
.config_manager
|
||||
.commit_provider_config(write)
|
||||
.await
|
||||
.map_err(map_config_error)?;
|
||||
processor.cancel_active_login().await;
|
||||
processor.model_catalog.invalidate().await;
|
||||
Ok(Some(GcpSetupResponse {}.into()))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
enum AuthErrorReason {
|
||||
GcloudNotInstalled,
|
||||
CredentialFileInvalid,
|
||||
AuthCommandFailed,
|
||||
}
|
||||
|
||||
impl AuthErrorReason {
|
||||
fn error(self, message: impl Into<String>) -> JSONRPCErrorError {
|
||||
let mut error = invalid_request(message);
|
||||
error.data = Some(json!({ "reason": self }));
|
||||
error
|
||||
}
|
||||
}
|
||||
|
||||
async fn open_credential_file(path: &Path) -> std::io::Result<File> {
|
||||
if !tokio::fs::metadata(path).await?.is_file() {
|
||||
return Err(std::io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"expected a regular file",
|
||||
));
|
||||
}
|
||||
File::open(path).await
|
||||
}
|
||||
|
||||
// Require a JSON object. Serde also accepts positional arrays when deserializing a struct.
|
||||
struct AdcObject;
|
||||
|
||||
impl<'de> Visitor<'de> for AdcObject {
|
||||
type Value = ();
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("a Google Cloud credential object")
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<(), A::Error> {
|
||||
#[derive(Deserialize)]
|
||||
struct Adc {
|
||||
#[serde(rename = "type")]
|
||||
kind: String,
|
||||
}
|
||||
let adc = Adc::deserialize(MapAccessDeserializer::new(map))?;
|
||||
if adc.kind.trim().is_empty() {
|
||||
return Err(serde::de::Error::custom(
|
||||
"expected a nonempty credential type",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn validate_adc_file(file: File) -> std::io::Result<()> {
|
||||
let file = file.into_std().await;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
// Stream past type-specific fields without retaining the credential contents.
|
||||
let mut json = serde_json::Deserializer::from_reader(BufReader::new(file));
|
||||
json.deserialize_map(AdcObject)?;
|
||||
json.end()?;
|
||||
Ok(())
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
async fn verify_credentials(
|
||||
configured: ModelProviderInfo,
|
||||
cwd: &AbsolutePathBuf,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
configured
|
||||
.validate_gcp_credential_file()
|
||||
.map_err(|err| AuthErrorReason::CredentialFileInvalid.error(err))?;
|
||||
let default_gcloud = configured.auth.is_none();
|
||||
let mut candidate = ModelProviderInfo::create_gcp_provider();
|
||||
merge_gcp_provider_overrides(Some(&mut candidate), configured).map_err(invalid_request)?;
|
||||
apply_default_gcp_auth(&mut candidate, cwd);
|
||||
candidate.validate().map_err(invalid_request)?;
|
||||
let auth_file = candidate.credential_file.clone().or_else(|| {
|
||||
if default_gcloud {
|
||||
std::env::var_os("GOOGLE_APPLICATION_CREDENTIALS").map(PathBuf::from)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
if let Some(path) = auth_file {
|
||||
let path = cwd.as_path().join(path);
|
||||
let file = open_credential_file(&path).await.map_err(|err| {
|
||||
AuthErrorReason::CredentialFileInvalid.error(format!(
|
||||
"Cannot read the Google Cloud credential file: {err}"
|
||||
))
|
||||
})?;
|
||||
if default_gcloud {
|
||||
validate_adc_file(file).await.map_err(|_| AuthErrorReason::CredentialFileInvalid.error(
|
||||
"Expected a Google Cloud credential file containing a JSON object with a nonempty string type.",
|
||||
))?;
|
||||
}
|
||||
}
|
||||
let provider = create_model_provider(candidate, /*auth_manager*/ None);
|
||||
provider
|
||||
.runtime_base_url()
|
||||
.await
|
||||
.map_err(|err| invalid_request(err.to_string()))?;
|
||||
// This fresh provider owns a command-backed manager. A refresh runs that command
|
||||
// once and preserves errors that the inference auth path reduces to missing auth.
|
||||
let auth_manager = provider
|
||||
.auth_manager()
|
||||
.ok_or_else(|| internal_error("Missing GCP auth manager."))?;
|
||||
if let Err(err) = auth_manager.refresh_token().await {
|
||||
if default_gcloud
|
||||
&& let RefreshTokenError::Transient(err) = err
|
||||
&& err.kind() == ErrorKind::NotFound
|
||||
&& cwd.as_path().is_dir()
|
||||
{
|
||||
return Err(AuthErrorReason::GcloudNotInstalled.error(
|
||||
"Cannot find gcloud on the app-server host. Check its installation and PATH.",
|
||||
));
|
||||
}
|
||||
return Err(AuthErrorReason::AuthCommandFailed
|
||||
.error("The Google Cloud auth command could not obtain an access token."));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
use super::config_processor::map_error as map_config_error;
|
||||
use crate::config_manager::ConfigManager;
|
||||
use crate::config_manager_service::PreparedProviderWrite;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use codex_app_server_protocol::ConfigBatchWriteParams;
|
||||
use codex_app_server_protocol::ConfigEdit;
|
||||
use codex_app_server_protocol::ConfigWriteErrorCode;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::MergeStrategy;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::config::edit::ConfigEditsBuilder;
|
||||
use codex_model_provider::AMAZON_BEDROCK_PROVIDER_ID;
|
||||
|
||||
pub(super) struct BedrockProviderConfig<'a> {
|
||||
pub(super) region: Option<&'a str>,
|
||||
pub(super) profile: Option<&'a str>,
|
||||
}
|
||||
|
||||
pub(super) async fn prepare_bedrock_provider(
|
||||
config_manager: &ConfigManager,
|
||||
config: BedrockProviderConfig<'_>,
|
||||
) -> Result<PreparedProviderWrite, JSONRPCErrorError> {
|
||||
let layers = config_manager
|
||||
.load_config_layers(/*cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to load configuration layers: {err}")))?;
|
||||
let mut settings = vec![("aws.profile", config.profile)];
|
||||
if let Some(region) = config.region {
|
||||
settings.push(("aws.region", Some(region)));
|
||||
}
|
||||
let (write, provider) = config_manager
|
||||
.prepare_provider_config(&layers, AMAZON_BEDROCK_PROVIDER_ID, settings)
|
||||
.map_err(map_config_error)?;
|
||||
if provider
|
||||
.aws
|
||||
.is_some_and(|aws| aws.credential_export.is_some())
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"Amazon Bedrock is configured to use `aws.credential_export`. Please clear this setting to use another sign-in method.",
|
||||
));
|
||||
}
|
||||
Ok(write)
|
||||
}
|
||||
|
||||
pub(super) async fn clear_user_model_provider_if_bedrock(
|
||||
config_manager: &ConfigManager,
|
||||
config: &Config,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let mut latest_config = None;
|
||||
loop {
|
||||
let config = latest_config.as_ref().unwrap_or(config);
|
||||
let Some(key_paths) = ConfigEditsBuilder::bedrock_provider_config_paths_to_clear(config)
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let expected_version = config
|
||||
.config_layer_stack
|
||||
.get_active_user_layer()
|
||||
.map(|layer| layer.version.clone());
|
||||
|
||||
let result = config_manager
|
||||
.batch_write(ConfigBatchWriteParams {
|
||||
edits: key_paths
|
||||
.into_iter()
|
||||
.map(|segments| ConfigEdit {
|
||||
key_path: segments.join("."),
|
||||
value: serde_json::Value::Null,
|
||||
merge_strategy: MergeStrategy::Replace,
|
||||
})
|
||||
.collect(),
|
||||
file_path: None,
|
||||
expected_version,
|
||||
reload_user_config: false,
|
||||
})
|
||||
.await;
|
||||
if let Err(err) = &result
|
||||
&& latest_config.is_none()
|
||||
&& err.write_error_code() == Some(ConfigWriteErrorCode::ConfigVersionConflict)
|
||||
{
|
||||
tracing::warn!(
|
||||
"configuration changed while clearing Amazon Bedrock settings; retrying once"
|
||||
);
|
||||
latest_config = Some(
|
||||
config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to reload Amazon Bedrock configuration: {err}"
|
||||
))
|
||||
})?,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
return result.map(|_| ()).map_err(map_config_error);
|
||||
}
|
||||
}
|
||||
@@ -576,7 +576,7 @@ mod thread_processor_behavior_tests {
|
||||
experimental_bearer_token: None,
|
||||
auth: None,
|
||||
gateway_oauth: None,
|
||||
aws: None,
|
||||
api_key: None,
|
||||
wire_api: WireApi::Responses,
|
||||
query_params: None,
|
||||
http_headers: None,
|
||||
@@ -589,9 +589,8 @@ mod thread_processor_behavior_tests {
|
||||
supports_websockets: true,
|
||||
supports_standalone_web_search: false,
|
||||
capabilities: None,
|
||||
project_id: None,
|
||||
location: None,
|
||||
credential_file: None,
|
||||
merge_system_messages: None,
|
||||
keyring_account: None,
|
||||
include_internal_metadata: false,
|
||||
};
|
||||
let config_manager = ConfigManager::new(
|
||||
@@ -631,6 +630,12 @@ mod thread_processor_behavior_tests {
|
||||
.await?;
|
||||
|
||||
assert_eq!(config.model_provider_id, "session");
|
||||
// aKode: configured providers learn their runtime-only keyring account from
|
||||
// their id when merged.
|
||||
let session_provider = ModelProviderInfo {
|
||||
keyring_account: Some("model-provider:session".to_string()),
|
||||
..session_provider
|
||||
};
|
||||
assert_eq!(config.model_provider, session_provider);
|
||||
assert!(!config.features.enabled(Feature::Plugins));
|
||||
assert!(config.bypass_hook_trust);
|
||||
@@ -1170,9 +1175,7 @@ mod thread_processor_behavior_tests {
|
||||
let connection = ConnectionId(1);
|
||||
let (cancel_tx, cancel_rx) = oneshot::channel();
|
||||
|
||||
manager
|
||||
.connection_initialized(connection)
|
||||
.await;
|
||||
manager.connection_initialized(connection).await;
|
||||
assert!(
|
||||
manager
|
||||
.try_add_connection_to_thread(thread_id, connection)
|
||||
@@ -1218,12 +1221,8 @@ mod thread_processor_behavior_tests {
|
||||
let connection_b = ConnectionId(2);
|
||||
let (cancel_tx, mut cancel_rx) = oneshot::channel();
|
||||
|
||||
manager
|
||||
.connection_initialized(connection_a)
|
||||
.await;
|
||||
manager
|
||||
.connection_initialized(connection_b)
|
||||
.await;
|
||||
manager.connection_initialized(connection_a).await;
|
||||
manager.connection_initialized(connection_b).await;
|
||||
assert!(
|
||||
manager
|
||||
.try_add_connection_to_thread(thread_id, connection_a)
|
||||
@@ -1263,12 +1262,8 @@ mod thread_processor_behavior_tests {
|
||||
let connection_a = ConnectionId(1);
|
||||
let connection_b = ConnectionId(2);
|
||||
|
||||
manager
|
||||
.connection_initialized(connection_a)
|
||||
.await;
|
||||
manager
|
||||
.connection_initialized(connection_b)
|
||||
.await;
|
||||
manager.connection_initialized(connection_a).await;
|
||||
manager.connection_initialized(connection_b).await;
|
||||
assert!(
|
||||
manager
|
||||
.try_add_connection_to_thread(thread_id, connection_a)
|
||||
@@ -1310,9 +1305,7 @@ mod thread_processor_behavior_tests {
|
||||
let manager = ThreadStateManager::new();
|
||||
let thread_id = ThreadId::from_string("ba62fd70-2ec2-4b1b-9d94-355694332dd2")?;
|
||||
let connection = ConnectionId(1);
|
||||
manager
|
||||
.connection_initialized(connection)
|
||||
.await;
|
||||
manager.connection_initialized(connection).await;
|
||||
|
||||
let wait_for_subscriber = manager.wait_for_thread_subscriber(thread_id);
|
||||
let attach_connection = async {
|
||||
@@ -1336,9 +1329,7 @@ mod thread_processor_behavior_tests {
|
||||
let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?;
|
||||
let connection = ConnectionId(1);
|
||||
|
||||
manager
|
||||
.connection_initialized(connection)
|
||||
.await;
|
||||
manager.connection_initialized(connection).await;
|
||||
let threads_to_unload = manager.remove_connection(connection).await;
|
||||
assert_eq!(threads_to_unload, Vec::<ThreadId>::new());
|
||||
|
||||
@@ -1350,5 +1341,4 @@ mod thread_processor_behavior_tests {
|
||||
assert!(!manager.has_subscribers(thread_id).await);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -216,9 +216,9 @@ impl SampleTask {
|
||||
.insert(codex_core::McpServersDisabled);
|
||||
}
|
||||
options.thread_extension_init.insert(SampleThread);
|
||||
let effort = params.effort.filter(|_| {
|
||||
model.supports_reasoning_effort_updates && options.config.model_provider.is_openai()
|
||||
});
|
||||
let effort = params
|
||||
.effort
|
||||
.filter(|_| model.supports_reasoning_effort_updates);
|
||||
options.session_source = Some(SessionSource::Custom("thread_sample".to_string()));
|
||||
options.thread_source = Some(
|
||||
params
|
||||
|
||||
@@ -161,76 +161,6 @@ async fn to_connection_notifications_are_preserved_for_non_opted_out_clients() {
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn experimental_notifications_are_dropped_without_capability() {
|
||||
let connection_id = ConnectionId(12);
|
||||
let (writer_tx, mut writer_rx) = mpsc::channel(1);
|
||||
|
||||
let mut connections = HashMap::new();
|
||||
connections.insert(
|
||||
connection_id,
|
||||
OutboundConnectionState::new(
|
||||
writer_tx,
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(RwLock::new(HashSet::new())),
|
||||
/*disconnect_sender*/ None,
|
||||
),
|
||||
);
|
||||
|
||||
route_outgoing_envelope(
|
||||
&mut connections,
|
||||
OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message: app_server_notification(thread_realtime_started_notification()),
|
||||
write_complete_tx: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
writer_rx.try_recv().is_err(),
|
||||
"experimental notifications should not reach clients without capability"
|
||||
);
|
||||
|
||||
let recovery = AuthRecoveryNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn_id: "turn-1".to_string(),
|
||||
provider: "Amazon Bedrock".to_string(),
|
||||
message: "Refreshing AWS authentication.".to_string(),
|
||||
};
|
||||
|
||||
for (method, notification) in [
|
||||
(
|
||||
"modelProvider/authRecoveryStarted",
|
||||
ServerNotification::AuthRecoveryStarted(recovery.clone()),
|
||||
),
|
||||
(
|
||||
"modelProvider/authRecoveryCompleted",
|
||||
ServerNotification::AuthRecoveryCompleted(recovery),
|
||||
),
|
||||
] {
|
||||
route_outgoing_envelope(
|
||||
&mut connections,
|
||||
OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message: app_server_notification(notification),
|
||||
write_complete_tx: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
let message = writer_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("stable auth recovery notification should reach clients without capability");
|
||||
let OutgoingMessage::AppServerNotification(envelope) = message.message else {
|
||||
panic!("stable auth recovery notification should be delivered");
|
||||
};
|
||||
assert_eq!(envelope.notification.to_string(), method);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn experimental_notifications_are_preserved_with_capability() {
|
||||
let connection_id = ConnectionId(13);
|
||||
@@ -628,3 +558,73 @@ async fn to_connection_stdio_waits_instead_of_disconnecting_when_writer_queue_is
|
||||
}) if summary == "second"
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn experimental_notifications_are_dropped_without_capability() {
|
||||
let connection_id = ConnectionId(12);
|
||||
let (writer_tx, mut writer_rx) = mpsc::channel(1);
|
||||
|
||||
let mut connections = HashMap::new();
|
||||
connections.insert(
|
||||
connection_id,
|
||||
OutboundConnectionState::new(
|
||||
writer_tx,
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(RwLock::new(HashSet::new())),
|
||||
/*disconnect_sender*/ None,
|
||||
),
|
||||
);
|
||||
|
||||
route_outgoing_envelope(
|
||||
&mut connections,
|
||||
OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message: app_server_notification(thread_realtime_started_notification()),
|
||||
write_complete_tx: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
writer_rx.try_recv().is_err(),
|
||||
"experimental notifications should not reach clients without capability"
|
||||
);
|
||||
|
||||
let recovery = AuthRecoveryNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn_id: "turn-1".to_string(),
|
||||
provider: "Local".to_string(),
|
||||
message: "Refreshing AWS authentication.".to_string(),
|
||||
};
|
||||
|
||||
for (method, notification) in [
|
||||
(
|
||||
"modelProvider/authRecoveryStarted",
|
||||
ServerNotification::AuthRecoveryStarted(recovery.clone()),
|
||||
),
|
||||
(
|
||||
"modelProvider/authRecoveryCompleted",
|
||||
ServerNotification::AuthRecoveryCompleted(recovery),
|
||||
),
|
||||
] {
|
||||
route_outgoing_envelope(
|
||||
&mut connections,
|
||||
OutgoingEnvelope::ToConnection {
|
||||
connection_id,
|
||||
message: app_server_notification(notification),
|
||||
write_complete_tx: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
let message = writer_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("stable auth recovery notification should reach clients without capability");
|
||||
let OutgoingMessage::AppServerNotification(envelope) = message.message else {
|
||||
panic!("stable auth recovery notification should be delivered");
|
||||
};
|
||||
assert_eq!(envelope.notification.to_string(), method);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,9 +110,35 @@ impl MockResponsesConfig {
|
||||
provider_config,
|
||||
extra_config,
|
||||
} = self;
|
||||
let root_config = root_config.join("\n");
|
||||
let provider_config = provider_config.join("\n");
|
||||
let mut root_config = root_config.join("\n");
|
||||
let mut provider_config = provider_config.join("\n");
|
||||
let extra_config = extra_config.join("\n");
|
||||
// aKode providers without a catalog URL synthesize local metadata; tests keep the
|
||||
// bundled catalog the removed built-in defaults provided (unless they configure one).
|
||||
if !root_config.contains("model_catalog_json")
|
||||
&& !extra_config.contains("model_catalog_json")
|
||||
&& !provider_config.contains("model_catalog_url")
|
||||
{
|
||||
root_config.push('\n');
|
||||
root_config.push_str(&bundled_model_catalog_config(codex_home)?);
|
||||
}
|
||||
// Upstream custom providers offered hosted web search by default; aKode makes it an
|
||||
// explicit provider capability, so the mock provider opts in to keep request shapes.
|
||||
// Upstream also gave providers named "OpenAI" remote compaction V2 by name; aKode
|
||||
// requires the explicit capability.
|
||||
if !provider_config.contains("capabilities") && !extra_config.contains("capabilities") {
|
||||
if provider_name == "OpenAI" {
|
||||
provider_config.push_str(
|
||||
"\ncapabilities = { hosted_web_search = true, remote_compaction = \"v2\" }",
|
||||
);
|
||||
} else {
|
||||
provider_config.push_str("\ncapabilities = { hosted_web_search = true }");
|
||||
}
|
||||
}
|
||||
// Request-shape tests keep the upstream instruction layout; merging has its own tests.
|
||||
if !provider_config.contains("merge_system_messages") {
|
||||
provider_config.push_str("\nmerge_system_messages = false");
|
||||
}
|
||||
let feature_entries = features
|
||||
.into_iter()
|
||||
.map(|(feature, enabled)| {
|
||||
@@ -156,6 +182,23 @@ stream_max_retries = 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy the bundled model catalog into `codex_home` and return the root-level
|
||||
/// `model_catalog_json = ...` line that selects it.
|
||||
///
|
||||
/// aKode has no default provider and no bundled catalog seed, so tests that start threads
|
||||
/// from a hand-written config (and relied on the removed defaults) opt in explicitly.
|
||||
pub fn bundled_model_catalog_config(codex_home: &Path) -> std::io::Result<String> {
|
||||
let catalog = codex_home.join(crate::models_cache::HARNESS_CATALOG_FILE);
|
||||
std::fs::write(
|
||||
&catalog,
|
||||
include_str!("../../../models-manager/models.json"),
|
||||
)?;
|
||||
Ok(format!(
|
||||
"model_catalog_json = {}\n",
|
||||
serde_json::to_string(&catalog.display().to_string())?
|
||||
))
|
||||
}
|
||||
|
||||
pub fn write_mock_responses_config_toml(
|
||||
codex_home: &Path,
|
||||
server_uri: &str,
|
||||
|
||||
@@ -12,6 +12,7 @@ mod test_app_server;
|
||||
|
||||
use codex_app_server_protocol::JSONRPCResponse;
|
||||
pub use config::MockResponsesConfig;
|
||||
pub use config::bundled_model_catalog_config;
|
||||
pub use config::write_mock_responses_config_toml;
|
||||
pub use config::write_mock_responses_config_toml_with_chatgpt_base_url;
|
||||
pub use core_test_support::PathBufExt;
|
||||
|
||||
@@ -125,12 +125,50 @@ pub async fn write_models_cache_with_models(
|
||||
let cache = codex_model_provider::test_support::models_cache_entry(
|
||||
&config.model_provider,
|
||||
auth.as_ref(),
|
||||
models,
|
||||
models.clone(),
|
||||
);
|
||||
let cache_path = codex_home.join("models_cache.json");
|
||||
std::fs::write(cache_path, serde_json::to_string_pretty(&cache)?)
|
||||
std::fs::write(cache_path, serde_json::to_string_pretty(&cache)?)?;
|
||||
// aKode: providers without `model_catalog_url` never read `models_cache.json` (they
|
||||
// use an explicit catalog or the provider's `/models` listing). Keep the cached
|
||||
// models authoritative, as they were upstream, by serving them as the explicit
|
||||
// catalog — replacing the bundled one `MockResponsesConfig` installs by default.
|
||||
if config.model_provider.model_catalog_url.is_none() {
|
||||
let config_path = codex_home.join("config.toml");
|
||||
let config_text = std::fs::read_to_string(&config_path).unwrap_or_default();
|
||||
let harness_catalog = codex_home.join(HARNESS_CATALOG_FILE);
|
||||
// Upstream merged cached models over the bundled catalog by slug.
|
||||
let mut catalog = serde_json::from_str::<codex_protocol::openai_models::ModelsResponse>(
|
||||
include_str!("../../../models-manager/models.json"),
|
||||
)?
|
||||
.models;
|
||||
for model in models {
|
||||
match catalog
|
||||
.iter()
|
||||
.position(|existing| existing.slug == model.slug)
|
||||
{
|
||||
Some(index) => catalog[index] = model,
|
||||
None => catalog.push(model),
|
||||
}
|
||||
}
|
||||
if config_text.contains(HARNESS_CATALOG_FILE) && harness_catalog.exists() {
|
||||
std::fs::write(
|
||||
harness_catalog,
|
||||
serde_json::to_string_pretty(&serde_json::json!({ "models": catalog }))?,
|
||||
)?;
|
||||
} else if !config_text.contains("model_catalog_json") {
|
||||
if !config_path.exists() {
|
||||
std::fs::write(&config_path, "")?;
|
||||
}
|
||||
write_model_catalog_json(codex_home, catalog)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Catalog file `MockResponsesConfig::write` installs unless a test configures one.
|
||||
pub(crate) const HARNESS_CATALOG_FILE: &str = "test-models.json";
|
||||
|
||||
/// Write `models` as a `model_catalog_json` catalog and point `config.toml` at it.
|
||||
///
|
||||
/// API-key sessions without a provider model catalog URL never read `models_cache.json`, so
|
||||
@@ -142,7 +180,12 @@ pub fn write_model_catalog_json(codex_home: &Path, models: Vec<ModelInfo>) -> st
|
||||
serde_json::to_string_pretty(&serde_json::json!({ "models": models }))?,
|
||||
)?;
|
||||
let config_path = codex_home.join("config.toml");
|
||||
let config = std::fs::read_to_string(&config_path)?;
|
||||
// Replace the default catalog `MockResponsesConfig::write` may have installed.
|
||||
let config = std::fs::read_to_string(&config_path)?
|
||||
.lines()
|
||||
.filter(|line| !line.trim_start().starts_with("model_catalog_json"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
std::fs::write(
|
||||
&config_path,
|
||||
format!(
|
||||
|
||||
@@ -1401,20 +1401,6 @@ impl TestAppServer {
|
||||
self.send_login_account_request(params).await
|
||||
}
|
||||
|
||||
/// Send an `account/login/start` JSON-RPC request for managed Amazon Bedrock login.
|
||||
pub async fn send_login_account_amazon_bedrock_request(
|
||||
&mut self,
|
||||
api_key: &str,
|
||||
region: &str,
|
||||
) -> anyhow::Result<i64> {
|
||||
let params = serde_json::json!({
|
||||
"type": "amazonBedrock",
|
||||
"apiKey": api_key,
|
||||
"region": region,
|
||||
});
|
||||
self.send_request("account/login/start", Some(params)).await
|
||||
}
|
||||
|
||||
/// Send an `account/login/cancel` JSON-RPC request.
|
||||
pub async fn send_cancel_login_account_request(
|
||||
&mut self,
|
||||
|
||||
@@ -99,7 +99,8 @@ async fn get_auth_status_no_auth() -> Result<()> {
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn get_auth_status_with_api_key() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
create_config_toml(codex_home.path())?;
|
||||
// aKode: no built-in OpenAI default provider requires auth; configure one that does.
|
||||
create_config_toml_custom_provider(codex_home.path(), /*requires_openai_auth*/ true)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
@@ -158,7 +159,8 @@ async fn get_auth_status_with_api_key_when_auth_not_required() -> Result<()> {
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn get_auth_status_with_api_key_no_include_token() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
create_config_toml(codex_home.path())?;
|
||||
// aKode: no built-in OpenAI default provider requires auth; configure one that does.
|
||||
create_config_toml_custom_provider(codex_home.path(), /*requires_openai_auth*/ true)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
@@ -185,7 +187,8 @@ async fn get_auth_status_with_api_key_no_include_token() -> Result<()> {
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn get_auth_status_with_api_key_refresh_requested() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
create_config_toml(codex_home.path())?;
|
||||
// aKode: no built-in OpenAI default provider requires auth; configure one that does.
|
||||
create_config_toml_custom_provider(codex_home.path(), /*requires_openai_auth*/ true)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
|
||||
@@ -15,9 +15,13 @@ use tokio::time::timeout;
|
||||
#[tokio::test]
|
||||
async fn ignored_config_fields_emit_startup_and_project_warnings() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
// aKode: no default provider/catalog, so threads need an explicit model catalog.
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"network_proxy = { nested = 'private_value' }",
|
||||
format!(
|
||||
"{}network_proxy = {{ nested = 'private_value' }}",
|
||||
app_test_support::bundled_model_catalog_config(home.path())?
|
||||
),
|
||||
)?;
|
||||
std::fs::write(
|
||||
home.path().join("requirements.toml"),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,88 +0,0 @@
|
||||
//! GCP account reporting follows the selected provider without resolving its credentials.
|
||||
|
||||
use anyhow::Result;
|
||||
use app_test_support::TestAppServer;
|
||||
use app_test_support::write_api_key_auth;
|
||||
use codex_app_server_protocol::GetAccountParams;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use test_case::test_case;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(/*secs*/ 30);
|
||||
|
||||
#[test_case(""; "application_default_credentials")]
|
||||
#[test_case(
|
||||
r#"
|
||||
[model_providers.gcp]
|
||||
base_url = "https://vertex.example.com/v1"
|
||||
[model_providers.gcp.auth]
|
||||
command = "codex-test-gcp-command-that-does-not-exist"
|
||||
"#;
|
||||
"external_command_and_endpoint"
|
||||
)]
|
||||
#[tokio::test]
|
||||
async fn gcp_account_is_reported_without_resolving_credentials(overrides: &str) -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
format!("model_provider = \"gcp\"\n{overrides}"),
|
||||
)?;
|
||||
let mut app_server = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
.build_initialized()
|
||||
.await?;
|
||||
|
||||
let request_id = app_server
|
||||
.send_get_account_request(GetAccountParams {})
|
||||
.await?;
|
||||
let received: Value = timeout(READ_TIMEOUT, app_server.read_response(request_id)).await??;
|
||||
assert_eq!(
|
||||
received,
|
||||
json!({"account": {"type": "gcp"}, "requiresOpenaiAuth": false})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gcp_account_tracks_provider_changes_with_saved_api_key() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let config_path = codex_home.path().join("config.toml");
|
||||
std::fs::write(&config_path, "model_provider = \"gcp\"\n")?;
|
||||
write_api_key_auth(codex_home.path())?;
|
||||
let mut app_server = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
.build_initialized()
|
||||
.await?;
|
||||
|
||||
for (provider, expected) in [
|
||||
(
|
||||
"gcp",
|
||||
json!({"account": {"type": "gcp"}, "requiresOpenaiAuth": false}),
|
||||
),
|
||||
(
|
||||
"amazon-bedrock",
|
||||
json!({"account": {"type": "amazonBedrock", "usesCodexManagedCredentials": false}, "requiresOpenaiAuth": false}),
|
||||
),
|
||||
(
|
||||
"openai",
|
||||
json!({"account": {"type": "apiKey"}, "requiresOpenaiAuth": true}),
|
||||
),
|
||||
(
|
||||
"gcp",
|
||||
json!({"account": {"type": "gcp"}, "requiresOpenaiAuth": false}),
|
||||
),
|
||||
] {
|
||||
std::fs::write(&config_path, format!("model_provider = \"{provider}\"\n"))?;
|
||||
let request_id = app_server
|
||||
.send_get_account_request(GetAccountParams {})
|
||||
.await?;
|
||||
let received: Value = timeout(READ_TIMEOUT, app_server.read_response(request_id)).await??;
|
||||
assert_eq!(received, expected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -27,6 +27,11 @@ async fn builder_interposes_fixed_delay_for_auto_env() -> Result<()> {
|
||||
skip_if_remote!(Ok(()), "the fixed-delay fixture is local-only");
|
||||
|
||||
let codex_home = TempDir::new()?;
|
||||
// aKode: no default provider or bundled catalog; threads need an explicit catalog.
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
app_test_support::bundled_model_catalog_config(codex_home.path())?,
|
||||
)?;
|
||||
let requested_delay = Duration::from_secs(1);
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
|
||||
@@ -1,223 +0,0 @@
|
||||
//! GovCloud checks use current login state and refresh managed requirements without a restart.
|
||||
|
||||
use anyhow::Result;
|
||||
use app_test_support::TestAppServer;
|
||||
use codex_app_server_protocol::BedrockCheckGovCloudRequirementsParams;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::LoginAccountParams;
|
||||
use codex_app_server_protocol::LoginAccountResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::login_with_bedrock_api_key;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use test_case::test_case;
|
||||
|
||||
const BASELINE: &str = r#"
|
||||
allowed_login_methods = ["api"]
|
||||
[application.network]
|
||||
enabled = true
|
||||
[application.network.domains]
|
||||
"bedrock-mantle.us-gov-west-1.api.aws" = "allow"
|
||||
"#;
|
||||
|
||||
async fn check(server: &mut TestAppServer) -> Result<Value> {
|
||||
server
|
||||
.request(
|
||||
|request_id| ClientRequest::BedrockCheckGovCloudRequirements {
|
||||
request_id,
|
||||
params: BedrockCheckGovCloudRequirementsParams {},
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn checks_current_provider_after_login_without_restart() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(home.path().join("config.toml"), "")?;
|
||||
login_with_bedrock_api_key(
|
||||
home.path(),
|
||||
"test-key",
|
||||
"us-gov-west-1",
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)?;
|
||||
let mut server = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
assert_eq!(
|
||||
check(&mut server).await?,
|
||||
json!({"isGovCloud": false, "shouldWarn": false})
|
||||
);
|
||||
// GovCloud onboarding is enabled separately. Select the provider using the
|
||||
// existing login so stale startup configuration produces a different result.
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"model_provider = 'amazon-bedrock'\n",
|
||||
)?;
|
||||
assert_eq!(
|
||||
check(&mut server).await?,
|
||||
json!({"isGovCloud": true, "shouldWarn": true})
|
||||
);
|
||||
let _: LoginAccountResponse = server
|
||||
.request(|request_id| ClientRequest::LoginAccount {
|
||||
request_id,
|
||||
params: LoginAccountParams::AmazonBedrock {
|
||||
api_key: "test-key".to_string(),
|
||||
region: "us-west-2".to_string(),
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(
|
||||
check(&mut server).await?,
|
||||
json!({"isGovCloud": false, "shouldWarn": false})
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case("amazon-bedrock", "", "bedrock-mantle.us-gov-west-1.api.aws"; "mantle")]
|
||||
#[test_case("amazon-bedrock-runtime", "", "bedrock-runtime.us-gov-west-1.amazonaws.com"; "runtime")]
|
||||
#[test_case("amazon-bedrock", "[model_providers.amazon-bedrock]\nbase_url = 'https://bedrock.example.com/openai/v1'", "bedrock.example.com"; "custom_endpoint")]
|
||||
#[tokio::test]
|
||||
async fn checks_required_policy_fields_and_endpoint(
|
||||
provider: &str,
|
||||
provider_config: &str,
|
||||
domain: &str,
|
||||
) -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!("model_provider = '{provider}'\n{provider_config}\n"),
|
||||
)?;
|
||||
login_with_bedrock_api_key(
|
||||
home.path(),
|
||||
"test-key",
|
||||
"us-gov-west-1",
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)?;
|
||||
let mut server = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
let baseline = BASELINE.replace("bedrock-mantle.us-gov-west-1.api.aws", domain);
|
||||
for (requirements, should_warn) in [
|
||||
(
|
||||
baseline.replace("[\"api\"]", "[\"api\", \"chatgpt\"]"),
|
||||
true,
|
||||
),
|
||||
(baseline.replace("enabled = true", "enabled = false"), true),
|
||||
(baseline.replace("\"allow\"", "\"deny\""), true),
|
||||
(baseline, false),
|
||||
] {
|
||||
std::fs::write(home.path().join("requirements.toml"), &requirements)?;
|
||||
assert_eq!(
|
||||
check(&mut server).await?,
|
||||
json!({"isGovCloud": true, "shouldWarn": should_warn}),
|
||||
"{requirements}"
|
||||
);
|
||||
}
|
||||
std::fs::write(home.path().join("requirements.toml"), "[invalid toml")?;
|
||||
let request_id = server
|
||||
.send_request("account/bedrock/checkGovCloudRequirements", Some(json!({})))
|
||||
.await?;
|
||||
let error = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(/*secs*/ 10),
|
||||
server.read_stream_until_error_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!((error.error.code, error.error.data), (-32603, None));
|
||||
assert!(
|
||||
error
|
||||
.error
|
||||
.message
|
||||
.starts_with("failed to load configuration:")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn check_preserves_current_login_when_saved_credentials_are_unreadable() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"model_provider = 'amazon-bedrock'\ncli_auth_credentials_store = 'file'\n",
|
||||
)?;
|
||||
login_with_bedrock_api_key(
|
||||
home.path(),
|
||||
"test-key",
|
||||
"us-gov-west-1",
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)?;
|
||||
let mut server = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
|
||||
// The advisory must keep using the running session's credentials even when
|
||||
// its persistent credential store becomes unreadable.
|
||||
std::fs::write(home.path().join("auth.json"), "invalid json")?;
|
||||
assert_eq!(
|
||||
check(&mut server).await?,
|
||||
json!({"isGovCloud": true, "shouldWarn": true})
|
||||
);
|
||||
std::fs::write(home.path().join("requirements.toml"), BASELINE)?;
|
||||
assert_eq!(
|
||||
check(&mut server).await?,
|
||||
json!({"isGovCloud": true, "shouldWarn": false})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case("bedrock-mantle.us-gov-west-1.api.aws", "us-west-2", true; "mantle_url_overrides_commercial_region")]
|
||||
#[test_case("bedrock-runtime.us-gov-east-1.amazonaws.com", "us-west-2", true; "runtime_url_overrides_commercial_region")]
|
||||
#[test_case("bedrock-runtime-fips.us-gov-west-1.amazonaws.com", "us-west-2", true; "fips_url_overrides_commercial_region")]
|
||||
#[test_case("bedrock-mantle.us-west-2.api.aws", "us-gov-west-1", false; "commercial_url_overrides_govcloud_region")]
|
||||
#[test_case("bedrock-mantle.us-gov-west-1.api.aws.example.com", "us-west-2", false; "lookalike_proxy_uses_region")]
|
||||
#[tokio::test]
|
||||
async fn official_endpoint_takes_precedence_over_auth_region(
|
||||
domain: &str,
|
||||
auth_region: &str,
|
||||
is_gov_cloud: bool,
|
||||
) -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
"model_provider = 'amazon-bedrock'\n\
|
||||
[model_providers.amazon-bedrock]\n\
|
||||
base_url = 'https://{domain}/openai/v1'\n"
|
||||
),
|
||||
)?;
|
||||
login_with_bedrock_api_key(
|
||||
home.path(),
|
||||
"test-key",
|
||||
auth_region,
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)?;
|
||||
let mut server = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
assert_eq!(
|
||||
check(&mut server).await?,
|
||||
json!({"isGovCloud": is_gov_cloud, "shouldWarn": is_gov_cloud})
|
||||
);
|
||||
std::fs::write(
|
||||
home.path().join("requirements.toml"),
|
||||
BASELINE.replace("bedrock-mantle.us-gov-west-1.api.aws", domain),
|
||||
)?;
|
||||
assert_eq!(
|
||||
check(&mut server).await?,
|
||||
json!({"isGovCloud": is_gov_cloud, "shouldWarn": false})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
//! Verifies Bedrock service-tier discovery through the public model/list API.
|
||||
|
||||
use app_test_support::TestAppServer;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::ModelListParams;
|
||||
use codex_app_server_protocol::ModelListResponse;
|
||||
use codex_app_server_protocol::ModelServiceTier;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test_case::test_case("amazon-bedrock", vec!["openai.gpt-6.1-sol", "openai.gpt-6-astra"]; "mantle")]
|
||||
#[test_case::test_case("amazon-bedrock-runtime", vec!["global.openai.gpt-6.1-sol", "global.openai.gpt-6-astra", "us.openai.gpt-6.1-sol", "us.openai.gpt-6-astra"]; "runtime")]
|
||||
#[tokio::test]
|
||||
async fn bedrock_model_list_advertises_ultrafast_without_changing_default(
|
||||
provider_id: &str,
|
||||
expected_models: Vec<&str>,
|
||||
) -> anyhow::Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
r#"model_provider = "{provider_id}"
|
||||
[model_providers.{provider_id}.aws]
|
||||
region = "us-west-2"
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
let mut app_server = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
let response: ModelListResponse = app_server
|
||||
.request(|request_id| ClientRequest::ModelList {
|
||||
request_id,
|
||||
params: ModelListParams {
|
||||
cursor: None,
|
||||
limit: Some(100),
|
||||
include_hidden: Some(true),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
|
||||
assert_eq!(
|
||||
response
|
||||
.data
|
||||
.iter()
|
||||
.filter(|model| !model.service_tiers.is_empty())
|
||||
.map(|model| (
|
||||
model.model.as_str(),
|
||||
model.service_tiers.clone(),
|
||||
model.default_service_tier.clone()
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
expected_models
|
||||
.into_iter()
|
||||
.map(|model| (
|
||||
model,
|
||||
vec![ModelServiceTier {
|
||||
id: "ultrafast".to_string(),
|
||||
name: "Ultrafast".to_string(),
|
||||
description: "The fastest available responses for latency-sensitive work."
|
||||
.to_string(),
|
||||
}],
|
||||
None
|
||||
))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case::test_case("amazon-bedrock", "openai.gpt-6-astra"; "mantle")]
|
||||
#[test_case::test_case("amazon-bedrock-runtime", "global.openai.gpt-6-astra"; "runtime")]
|
||||
#[tokio::test]
|
||||
async fn bedrock_model_list_preserves_custom_service_tiers(
|
||||
provider_id: &str,
|
||||
model_id: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let mut model = codex_models_manager::bundled_models_response()?
|
||||
.models
|
||||
.into_iter()
|
||||
.find(|model| model.slug == "gpt-6-astra")
|
||||
.expect("bundled Astra model");
|
||||
model.slug = model_id.to_string();
|
||||
model.additional_speed_tiers = vec!["fast".to_string()];
|
||||
model.service_tiers = vec![codex_protocol::openai_models::ModelServiceTier {
|
||||
id: "ultrafast".to_string(),
|
||||
name: "Express".to_string(),
|
||||
description: "My custom Bedrock tier.".to_string(),
|
||||
}];
|
||||
model.default_service_tier = Some("ultrafast".to_string());
|
||||
let catalog_path = home.path().join("models.json");
|
||||
std::fs::write(
|
||||
&catalog_path,
|
||||
serde_json::to_vec(&codex_protocol::openai_models::ModelsResponse {
|
||||
models: vec![model],
|
||||
})?,
|
||||
)?;
|
||||
let catalog_path = serde_json::to_string(&catalog_path)?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
r#"model_provider = "{provider_id}"
|
||||
model_catalog_json = {catalog_path}
|
||||
[model_providers.{provider_id}.aws]
|
||||
region = "us-west-2"
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
let mut app_server = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
let response: ModelListResponse = app_server
|
||||
.request(|request_id| ClientRequest::ModelList {
|
||||
request_id,
|
||||
params: ModelListParams {
|
||||
cursor: None,
|
||||
limit: Some(100),
|
||||
include_hidden: Some(true),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
|
||||
assert_eq!(
|
||||
response
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|model| (
|
||||
model.model,
|
||||
model.additional_speed_tiers,
|
||||
model.service_tiers,
|
||||
model.default_service_tier,
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(
|
||||
model_id.to_string(),
|
||||
vec!["fast".to_string()],
|
||||
vec![ModelServiceTier {
|
||||
id: "ultrafast".to_string(),
|
||||
name: "Express".to_string(),
|
||||
description: "My custom Bedrock tier.".to_string(),
|
||||
}],
|
||||
Some("ultrafast".to_string()),
|
||||
)]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,412 +0,0 @@
|
||||
use anyhow::Result;
|
||||
use app_test_support::TestAppServer;
|
||||
use codex_app_server_protocol::BedrockDiscoverParams;
|
||||
use codex_app_server_protocol::BedrockDiscoverResponse;
|
||||
use codex_app_server_protocol::BedrockSetupParams;
|
||||
use codex_app_server_protocol::BedrockSetupResponse;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::ModelListParams;
|
||||
use codex_app_server_protocol::ModelListResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::login_with_bedrock_api_key;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const READ_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 60);
|
||||
|
||||
async fn bedrock_app_server(
|
||||
codex_home: &Path,
|
||||
environment: &[(&str, Option<&str>)],
|
||||
) -> Result<TestAppServer> {
|
||||
let aws_config = codex_home.join("aws-config");
|
||||
let aws_credentials = codex_home.join("aws-credentials");
|
||||
std::fs::write(&aws_config, "[profile engineering]\nregion = us-west-2\n")?;
|
||||
std::fs::write(
|
||||
&aws_credentials,
|
||||
"[engineering]\naws_access_key_id = engineering-id\naws_secret_access_key = engineering-secret\n\
|
||||
[finance]\naws_access_key_id = finance-id\naws_secret_access_key = finance-secret\n",
|
||||
)?;
|
||||
let aws_config_path = aws_config.to_string_lossy();
|
||||
let aws_credentials_path = aws_credentials.to_string_lossy();
|
||||
TestAppServer::builder()
|
||||
.with_codex_home(codex_home)
|
||||
.with_env_overrides(&[
|
||||
("AWS_CONFIG_FILE", Some(aws_config_path.as_ref())),
|
||||
(
|
||||
"AWS_SHARED_CREDENTIALS_FILE",
|
||||
Some(aws_credentials_path.as_ref()),
|
||||
),
|
||||
("AWS_PROFILE", None),
|
||||
("AWS_ACCESS_KEY_ID", None),
|
||||
("AWS_SECRET_ACCESS_KEY", None),
|
||||
("AWS_SESSION_TOKEN", None),
|
||||
("AWS_BEARER_TOKEN_BEDROCK", None),
|
||||
("AWS_REGION", None),
|
||||
("AWS_DEFAULT_REGION", None),
|
||||
("AWS_EC2_METADATA_DISABLED", Some("true")),
|
||||
])
|
||||
.with_env_overrides(environment)
|
||||
.build_initialized_with_timeout(READ_TIMEOUT)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discover_bedrock_profiles_and_environment_credentials() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut app_server = bedrock_app_server(
|
||||
codex_home.path(),
|
||||
&[
|
||||
("AWS_PROFILE", Some("engineering")),
|
||||
("AWS_ACCESS_KEY_ID", Some("environment-id")),
|
||||
("AWS_SECRET_ACCESS_KEY", Some("environment-secret")),
|
||||
("AWS_SESSION_TOKEN", Some("environment-token")),
|
||||
("AWS_BEARER_TOKEN_BEDROCK", Some("environment-bedrock-key")),
|
||||
("AWS_DEFAULT_REGION", Some("us-west-2")),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
|
||||
let response: BedrockDiscoverResponse = app_server
|
||||
.request(|request_id| ClientRequest::BedrockDiscover {
|
||||
request_id,
|
||||
params: BedrockDiscoverParams {},
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(
|
||||
serde_json::to_value(response)?,
|
||||
json!({
|
||||
"profiles": [
|
||||
{"name": "engineering", "region": "us-west-2"},
|
||||
{"name": "finance", "region": null}
|
||||
],
|
||||
"environmentCredentials": [
|
||||
{"type": "accessKeys", "region": null},
|
||||
{"type": "bedrockApiKey", "region": null}
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
let response: BedrockSetupResponse = app_server
|
||||
.request(|request_id| ClientRequest::BedrockSetup {
|
||||
request_id,
|
||||
params: BedrockSetupParams::Environment {
|
||||
region: " us-east-2 ".to_string(),
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(response, BedrockSetupResponse {});
|
||||
|
||||
let config: toml::Value = toml::from_str(&std::fs::read_to_string(
|
||||
codex_home.path().join("config.toml"),
|
||||
)?)?;
|
||||
assert_eq!(
|
||||
config,
|
||||
toml::toml! {
|
||||
model_provider = "amazon-bedrock"
|
||||
[model_providers.amazon-bedrock.aws]
|
||||
region = "us-east-2"
|
||||
}
|
||||
.into()
|
||||
);
|
||||
assert!(!codex_home.path().join(".env").exists());
|
||||
|
||||
// The same server must route both the picker and the first thread to Bedrock.
|
||||
let models: ModelListResponse = app_server
|
||||
.request(|request_id| ClientRequest::ModelList {
|
||||
request_id,
|
||||
params: ModelListParams::default(),
|
||||
})
|
||||
.await?;
|
||||
let default_model = models.data.iter().find(|model| model.is_default).unwrap();
|
||||
assert!(default_model.model.starts_with("openai."));
|
||||
let thread = app_server
|
||||
.start_thread(ThreadStartParams::default())
|
||||
.await?;
|
||||
assert_eq!(thread.model_provider, "amazon-bedrock");
|
||||
assert_eq!(thread.model, default_model.model);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn setup_bedrock_profile_and_environment() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let config_path = codex_home.path().join("config.toml");
|
||||
let dotenv_path = codex_home.path().join(".env");
|
||||
let existing_config = "[model_providers.amazon-bedrock]\nhttp_headers = { X-Existing = \"preserved\" }\n\
|
||||
[model_providers.amazon-bedrock.aws]\nprofile = \"old\"\nregion = \"us-east-1\"\n\
|
||||
auth_refresh = { command = \"aws\", args = [\"login\"] }\n";
|
||||
std::fs::write(&config_path, existing_config)?;
|
||||
let existing_dotenv = "# existing configuration\nUNRELATED=value\nAWS_ACCESS_KEY_ID=old-id\n\
|
||||
export AWS_SECRET_ACCESS_KEY=old-secret\nAWS_SESSION_TOKEN=stale-token\n";
|
||||
std::fs::write(&dotenv_path, existing_dotenv)?;
|
||||
let mut app_server = bedrock_app_server(
|
||||
codex_home.path(),
|
||||
&[
|
||||
("AWS_ACCESS_KEY_ID", Some("environment-id")),
|
||||
("AWS_SECRET_ACCESS_KEY", Some("environment-secret")),
|
||||
("AWS_DEFAULT_REGION", Some("us-east-1")),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
|
||||
let response: BedrockSetupResponse = app_server
|
||||
.request(|request_id| ClientRequest::BedrockSetup {
|
||||
request_id,
|
||||
params: BedrockSetupParams::Profile {
|
||||
profile: " engineering ".to_string(),
|
||||
region: " us-west-2 ".to_string(),
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(response, BedrockSetupResponse {});
|
||||
let config: toml::Value = toml::from_str(&std::fs::read_to_string(&config_path)?)?;
|
||||
assert_eq!(
|
||||
serde_json::to_value(&config["model_providers"]["amazon-bedrock"]["aws"])?,
|
||||
json!({
|
||||
"profile": "engineering",
|
||||
"region": "us-west-2",
|
||||
"auth_refresh": {"command": "aws", "args": ["login"]}
|
||||
})
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(&dotenv_path)?, existing_dotenv);
|
||||
|
||||
std::fs::write(&config_path, existing_config)?;
|
||||
let response: BedrockSetupResponse = app_server
|
||||
.request(|request_id| ClientRequest::BedrockSetup {
|
||||
request_id,
|
||||
params: BedrockSetupParams::Environment {
|
||||
region: "us-east-1".to_string(),
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(response, BedrockSetupResponse {});
|
||||
assert_eq!(std::fs::read_to_string(&dotenv_path)?, existing_dotenv);
|
||||
let config: toml::Value = toml::from_str(&std::fs::read_to_string(&config_path)?)?;
|
||||
assert_eq!(
|
||||
serde_json::to_value(&config["model_providers"]["amazon-bedrock"]["aws"])?,
|
||||
json!({
|
||||
"region": "us-east-1",
|
||||
"auth_refresh": {"command": "aws", "args": ["login"]}
|
||||
})
|
||||
);
|
||||
|
||||
let config: toml::Value = toml::from_str(&std::fs::read_to_string(&config_path)?)?;
|
||||
assert_eq!(
|
||||
config,
|
||||
toml::toml! {
|
||||
model_provider = "amazon-bedrock"
|
||||
|
||||
[model_providers.amazon-bedrock]
|
||||
http_headers = { X-Existing = "preserved" }
|
||||
|
||||
[model_providers.amazon-bedrock.aws]
|
||||
region = "us-east-1"
|
||||
auth_refresh = { command = "aws", args = ["login"] }
|
||||
}
|
||||
.into()
|
||||
);
|
||||
|
||||
let managed_home = TempDir::new()?;
|
||||
let managed_config_path = managed_home.path().join("config.toml");
|
||||
std::fs::write(&managed_config_path, "model_provider = 'openai'")?;
|
||||
std::fs::write(
|
||||
managed_home.path().join("requirements.toml"),
|
||||
"model_provider = 'amazon-bedrock'",
|
||||
)?;
|
||||
login_with_bedrock_api_key(
|
||||
managed_home.path(),
|
||||
"managed-bedrock-api-key",
|
||||
"us-east-1",
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)?;
|
||||
let auth_path = managed_home.path().join("auth.json");
|
||||
let expected_auth = std::fs::read_to_string(&auth_path)?;
|
||||
let mut app_server = bedrock_app_server(
|
||||
managed_home.path(),
|
||||
&[(
|
||||
"AWS_BEARER_TOKEN_BEDROCK",
|
||||
Some("environment-bedrock-api-key"),
|
||||
)],
|
||||
)
|
||||
.await?;
|
||||
let mut expected_config: toml::Value =
|
||||
toml::from_str(&std::fs::read_to_string(&managed_config_path)?)?;
|
||||
expected_config
|
||||
.as_table_mut()
|
||||
.expect("config should be a table")
|
||||
.extend(toml::toml! {
|
||||
[model_providers.amazon-bedrock.aws]
|
||||
profile = "engineering"
|
||||
region = "us-west-2"
|
||||
});
|
||||
let response: BedrockSetupResponse = app_server
|
||||
.request(|request_id| ClientRequest::BedrockSetup {
|
||||
request_id,
|
||||
params: BedrockSetupParams::Profile {
|
||||
profile: "engineering".to_string(),
|
||||
region: "us-west-2".to_string(),
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(response, BedrockSetupResponse {});
|
||||
assert_eq!(
|
||||
toml::from_str::<toml::Value>(&std::fs::read_to_string(&managed_config_path)?)?,
|
||||
expected_config
|
||||
);
|
||||
|
||||
let request_id = app_server
|
||||
.send_raw_request(
|
||||
"account/bedrock/setup",
|
||||
Some(json!({"type": "environment", "region": "us-east-1"})),
|
||||
)
|
||||
.await?;
|
||||
let error = timeout(
|
||||
READ_TIMEOUT,
|
||||
app_server.read_stream_until_error_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(
|
||||
error.error.message,
|
||||
"Codex-managed Bedrock credentials are already configured and take priority over AWS environment credentials. Run `codex logout` and try again."
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(&auth_path)?, expected_auth);
|
||||
assert_eq!(
|
||||
toml::from_str::<toml::Value>(&std::fs::read_to_string(&managed_config_path)?)?,
|
||||
expected_config
|
||||
);
|
||||
assert!(!managed_home.path().join(".env").exists());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn setup_bedrock_rejects_invalid_or_conflicting_credentials() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut app_server = bedrock_app_server(codex_home.path(), &[]).await?;
|
||||
|
||||
for (params, expected_error) in [
|
||||
(
|
||||
json!({"type": "profile", "profile": "engineering", "region": "us-west-1"}),
|
||||
"Amazon Bedrock does not support region `us-west-1`",
|
||||
),
|
||||
(
|
||||
json!({"type": "profile", "profile": " ", "region": "us-west-2"}),
|
||||
"AWS profile name must not be empty.",
|
||||
),
|
||||
(
|
||||
json!({"type": "profile", "profile": "missing", "region": "us-west-2"}),
|
||||
"failed to load credentials for AWS profile `missing`:",
|
||||
),
|
||||
(
|
||||
json!({"type": "environment", "region": "us-west-2"}),
|
||||
"No AWS credentials found. Please Configure AWS credentials or complete AWS sign-in, then try again.",
|
||||
),
|
||||
] {
|
||||
let request_id = app_server
|
||||
.send_raw_request("account/bedrock/setup", Some(params))
|
||||
.await?;
|
||||
let error = timeout(
|
||||
READ_TIMEOUT,
|
||||
app_server.read_stream_until_error_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await??;
|
||||
assert!(
|
||||
error.error.message.contains(expected_error),
|
||||
"expected {expected_error:?}, got {:?}",
|
||||
error.error.message
|
||||
);
|
||||
}
|
||||
assert!(!codex_home.path().join(".env").exists());
|
||||
assert!(!codex_home.path().join("config.toml").exists());
|
||||
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"forced_login_method = \"chatgpt\"\n",
|
||||
)?;
|
||||
let mut app_server = bedrock_app_server(home.path(), &[]).await?;
|
||||
let request_id = app_server
|
||||
.send_raw_request("account/bedrock/discover", Some(json!({})))
|
||||
.await?;
|
||||
let error = timeout(
|
||||
READ_TIMEOUT,
|
||||
app_server.read_stream_until_error_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(
|
||||
error.error.message,
|
||||
"Amazon Bedrock login is disabled by the configured login policy."
|
||||
);
|
||||
assert!(!home.path().join(".env").exists());
|
||||
|
||||
for source_file in ["selected.config.toml", "config.toml", "managed_config.toml"] {
|
||||
let layered_home = TempDir::new()?;
|
||||
let layered_home_path =
|
||||
AbsolutePathBuf::from_absolute_path(layered_home.path().canonicalize()?)?
|
||||
.into_path_buf();
|
||||
let config_path = layered_home_path.join("config.toml");
|
||||
let source_path = layered_home_path.join(source_file);
|
||||
let active_path = layered_home_path.join("selected.config.toml");
|
||||
let exporter_config = "[model_providers.amazon-bedrock.aws.credential_export]\n\
|
||||
command = \"secret-command\"\nargs = [\"secret-argument\"]\n";
|
||||
std::fs::write(&config_path, "")?;
|
||||
std::fs::write(&active_path, "")?;
|
||||
std::fs::write(&source_path, exporter_config)?;
|
||||
let active_config_path = active_path.to_string_lossy();
|
||||
let mut app_server = bedrock_app_server(
|
||||
&layered_home_path,
|
||||
&[(
|
||||
"CODEX_APP_SERVER_TEST_USER_CONFIG_FILE",
|
||||
Some(active_config_path.as_ref()),
|
||||
)],
|
||||
)
|
||||
.await?;
|
||||
let expected_config = std::fs::read_to_string(&config_path)?;
|
||||
let expected_active = std::fs::read_to_string(&active_path)?;
|
||||
let expected_error = "Amazon Bedrock is configured to use `aws.credential_export`. Please clear this setting to use another sign-in method.";
|
||||
|
||||
for (method, params) in [
|
||||
(
|
||||
"account/bedrock/setup",
|
||||
json!({"type": "profile", "profile": "engineering", "region": "us-west-2"}),
|
||||
),
|
||||
(
|
||||
"account/bedrock/setup",
|
||||
json!({"type": "environment", "region": "us-west-2"}),
|
||||
),
|
||||
(
|
||||
"account/login/start",
|
||||
json!({"type": "amazonBedrock", "apiKey": "new-key", "region": "us-west-2"}),
|
||||
),
|
||||
(
|
||||
"account/login/start",
|
||||
json!({"type": "amazonBedrockAccessKeys", "accessKeyId": "new-id", "secretAccessKey": "new-secret", "region": "us-west-2"}),
|
||||
),
|
||||
] {
|
||||
let request_id = app_server.send_raw_request(method, Some(params)).await?;
|
||||
let error = timeout(
|
||||
READ_TIMEOUT,
|
||||
app_server.read_stream_until_error_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(error.error.message, expected_error);
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(&config_path)?, expected_config);
|
||||
assert_eq!(std::fs::read_to_string(&source_path)?, exporter_config);
|
||||
assert_eq!(std::fs::read_to_string(&active_path)?, expected_active);
|
||||
assert!(!layered_home.path().join("auth.json").exists());
|
||||
assert!(!layered_home.path().join(".env").exists());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -306,9 +306,14 @@ async fn auto_compaction_emits_started_and_completed_items(route: CompactionRout
|
||||
let codex_home = TempDir::new()?;
|
||||
let mut config = compaction_config(&server.uri(), /*auto_compact_limit*/ 200_000);
|
||||
if let CompactionRoute::Remote = route {
|
||||
// aKode: remote compaction is an explicit provider capability, not implied by
|
||||
// the provider name "OpenAI".
|
||||
config = config
|
||||
.with_provider_name("OpenAI")
|
||||
.with_provider_config("requires_openai_auth = true");
|
||||
.with_provider_config("requires_openai_auth = true")
|
||||
.with_provider_config(
|
||||
"capabilities = { hosted_web_search = true, remote_compaction = \"v2\" }",
|
||||
);
|
||||
write_api_key_auth(codex_home.path())?;
|
||||
}
|
||||
config.write(codex_home.path())?;
|
||||
|
||||
@@ -29,9 +29,11 @@ base_url = "https://gateway.example.test/v1"
|
||||
requires_openai_auth = true
|
||||
"#;
|
||||
std::fs::write(home.path().join("requirements.toml"), requirements)?;
|
||||
// aKode: an explicit catalog keeps thread/start offline (no default bundled catalog).
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
r#"
|
||||
format!(
|
||||
r#"{}
|
||||
model_provider = "openai"
|
||||
[model_providers.gateway]
|
||||
name = "Local override"
|
||||
@@ -40,6 +42,8 @@ env_key = "LOCAL_KEY"
|
||||
[model_providers.gateway.http_headers]
|
||||
X-Local = "no"
|
||||
"#,
|
||||
app_test_support::bundled_model_catalog_config(home.path())?
|
||||
),
|
||||
)?;
|
||||
let expected: ConfigToml = toml::from_str(requirements)?;
|
||||
let expected_providers = json!(expected.model_providers);
|
||||
|
||||
@@ -2,9 +2,6 @@
|
||||
|
||||
use anyhow::Result;
|
||||
use app_test_support::TestAppServer;
|
||||
use codex_app_server_protocol::Account;
|
||||
use codex_app_server_protocol::GetAccountParams;
|
||||
use codex_app_server_protocol::GetAccountResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_protocol::config_types::ForcedLoginMethod;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -14,7 +11,6 @@ use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
use test_case::test_case;
|
||||
use tokio::time::timeout;
|
||||
use wiremock::MockServer;
|
||||
|
||||
const READ_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 60);
|
||||
|
||||
@@ -116,48 +112,3 @@ async fn config_requirements_read_rejects_invalid_login_method() -> Result<()> {
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn config_requirements_read_preserves_api_only_bedrock_without_chatgpt_requests() -> Result<()>
|
||||
{
|
||||
let backend = MockServer::start().await;
|
||||
let (_home, mut server) = start_server(
|
||||
&format!(
|
||||
r#"
|
||||
forced_login_method = "api"
|
||||
chatgpt_base_url = "{}/backend-api"
|
||||
model_provider = "amazon-bedrock"
|
||||
[model_providers.amazon-bedrock]
|
||||
base_url = "https://bedrock.example.com/v1"
|
||||
[model_providers.amazon-bedrock.auth]
|
||||
command = "print-token"
|
||||
"#,
|
||||
backend.uri()
|
||||
),
|
||||
/*requirements*/ None,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
read_requirements(&mut server).await?["requirements"]["allowedLoginMethods"],
|
||||
json!(["api"])
|
||||
);
|
||||
let id = server.send_get_account_request(GetAccountParams {}).await?;
|
||||
let account: GetAccountResponse = timeout(READ_TIMEOUT, server.read_response(id)).await??;
|
||||
assert_eq!(
|
||||
account,
|
||||
GetAccountResponse {
|
||||
account: Some(Account::AmazonBedrock {
|
||||
uses_codex_managed_credentials: false
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
}
|
||||
);
|
||||
assert!(
|
||||
backend
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("recorded requests")
|
||||
.is_empty()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -74,9 +74,13 @@ async fn selected_environment_emits_connection_lifecycle_notifications() -> Resu
|
||||
let exec_server_url = format!("ws://{}", listener.local_addr()?);
|
||||
|
||||
let codex_home = TempDir::new()?;
|
||||
// aKode: no default provider or bundled catalog; threads need an explicit catalog.
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
"[features]\ndeferred_executor = true\n",
|
||||
format!(
|
||||
"{}[features]\ndeferred_executor = true\n",
|
||||
app_test_support::bundled_model_catalog_config(codex_home.path())?
|
||||
),
|
||||
)?;
|
||||
let mut app_server = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
|
||||
@@ -118,7 +118,7 @@ model = "mock-model"
|
||||
approval_policy = "{approval_policy}"
|
||||
{sandbox_config}
|
||||
model_provider = "mock_provider"
|
||||
|
||||
{catalog}
|
||||
[skills]
|
||||
include_instructions = true
|
||||
|
||||
@@ -128,10 +128,13 @@ base_url = "{}/v1"
|
||||
wire_api = "responses"
|
||||
request_max_retries = 0
|
||||
stream_max_retries = 0
|
||||
merge_system_messages = false
|
||||
{permission_profile}
|
||||
{requested_permission_feature}
|
||||
"#,
|
||||
server.uri()
|
||||
server.uri(),
|
||||
// aKode: explicit catalog (no bundled default) and upstream message layout.
|
||||
catalog = app_test_support::bundled_model_catalog_config(codex_home.path())?
|
||||
),
|
||||
)?;
|
||||
let local_skill_dir = codex_home.path().join("skills/local-deploy");
|
||||
|
||||
@@ -155,6 +155,9 @@ async fn experimental_feature_list_resolves_thread_project_config() -> Result<()
|
||||
.write(codex_home.path())?;
|
||||
#[cfg(unix)]
|
||||
let config_toml = std::fs::read(codex_home.path().join("config.toml"))?;
|
||||
// aKode: config.toml references the harness's explicit model catalog file.
|
||||
#[cfg(unix)]
|
||||
let model_catalog = std::fs::read(codex_home.path().join("test-models.json"))?;
|
||||
let project_config_dir = workspace.path().join(".codex");
|
||||
std::fs::create_dir_all(&project_config_dir)?;
|
||||
std::fs::write(
|
||||
@@ -182,6 +185,7 @@ memories = true
|
||||
std::fs::rename(codex_home.path(), &deleted_launch_dir)?;
|
||||
std::fs::create_dir(codex_home.path())?;
|
||||
std::fs::write(codex_home.path().join("config.toml"), config_toml)?;
|
||||
std::fs::write(codex_home.path().join("test-models.json"), model_catalog)?;
|
||||
std::fs::create_dir(&launch_project_config_dir)?;
|
||||
std::fs::copy(
|
||||
project_config_dir.join("config.toml"),
|
||||
|
||||
@@ -55,6 +55,12 @@ struct ImportFixture {
|
||||
impl ImportFixture {
|
||||
async fn new() -> Result<Self> {
|
||||
let codex_home = TempDir::new()?;
|
||||
// aKode: there is no bundled catalog, so threads need an explicit one. No provider is
|
||||
// configured on purpose: imported sessions must stay appendable without one.
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
app_test_support::bundled_model_catalog_config(codex_home.path())?,
|
||||
)?;
|
||||
let project_root = codex_home.path().join("repo");
|
||||
std::fs::create_dir_all(&project_root)?;
|
||||
let session_path = codex_home
|
||||
|
||||
@@ -209,10 +209,15 @@ async fn model_list_leaves_oauth_gateway_after_account_change() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(home.path().join("config.toml"), gateway_config(&oauth))?;
|
||||
let mut server = gateway_server(home.path()).await?;
|
||||
std::fs::write(home.path().join("config.toml"), "")?;
|
||||
// aKode: there is no built-in `openai` provider or bundled catalog; route to a plain
|
||||
// provider with an explicit catalog instead.
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
app_test_support::bundled_model_catalog_config(home.path())?,
|
||||
)?;
|
||||
std::fs::write(
|
||||
home.path().join("requirements.toml"),
|
||||
"model_provider = 'openai'",
|
||||
"model_provider = 'plain'\n[model_providers.plain]\nname = 'Plain'\nbase_url = 'http://127.0.0.1:9/v1'\n",
|
||||
)?;
|
||||
let id = server
|
||||
.send_login_account_api_key_request("sk-catalog-test")
|
||||
@@ -629,9 +634,15 @@ async fn initialization_selects_legacy_or_explicit_gateway_login() -> Result<()>
|
||||
// Force automatic authorization to fail before launching a real browser.
|
||||
let callback = std::net::TcpListener::bind("127.0.0.1:0")?;
|
||||
let port = callback.local_addr()?.port();
|
||||
// aKode: an explicit catalog keeps the gateway's `/models` listing (and the OAuth
|
||||
// mock) out of thread startup; there is no bundled default catalog anymore.
|
||||
let catalog = app_test_support::bundled_model_catalog_config(home.path())?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!("{}\nredirect_port = {port}\n", gateway_config(&oauth)),
|
||||
format!(
|
||||
"{catalog}{}\nredirect_port = {port}\n",
|
||||
gateway_config(&oauth)
|
||||
),
|
||||
)?;
|
||||
let mut server = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
@@ -653,8 +664,11 @@ async fn initialization_selects_legacy_or_explicit_gateway_login() -> Result<()>
|
||||
.await?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!("{}\nredirect_port = {port}\n", gateway_config(&oauth))
|
||||
.replace("app-server-explicit-test", "gateway-after-initialize"),
|
||||
format!(
|
||||
"{catalog}{}\nredirect_port = {port}\n",
|
||||
gateway_config(&oauth)
|
||||
)
|
||||
.replace("app-server-explicit-test", "gateway-after-initialize"),
|
||||
)?;
|
||||
let thread = server
|
||||
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
|
||||
@@ -692,15 +706,18 @@ async fn initialization_selects_legacy_or_explicit_gateway_login() -> Result<()>
|
||||
async fn selected_gateway_read_notifies_matching_providers() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let oauth = MockServer::start().await;
|
||||
let config = gateway_config(&oauth).replace(
|
||||
"model_provider = \"gateway\"",
|
||||
"model_provider = \"openai\"",
|
||||
);
|
||||
// aKode: the non-gateway default is a plain custom provider (no built-in `openai`)
|
||||
// with an explicit catalog.
|
||||
let config = gateway_config(&oauth)
|
||||
.replace("model_provider = \"gateway\"", "model_provider = \"plain\"");
|
||||
let alias = config[config.find("[model_providers.gateway]").unwrap()..]
|
||||
.replace("model_providers.gateway", "model_providers.alias");
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!("{config}\n{alias}"),
|
||||
format!(
|
||||
"{}{config}\n{alias}\n[model_providers.plain]\nname = \"Plain\"\nbase_url = \"http://127.0.0.1:9/v1\"\n",
|
||||
app_test_support::bundled_model_catalog_config(home.path())?
|
||||
),
|
||||
)?;
|
||||
let mut server = gateway_server(home.path()).await?;
|
||||
assert!(!read_gateway(&mut server).await?.required);
|
||||
|
||||
@@ -1,357 +0,0 @@
|
||||
//! GCP setup validates before saving and shares provider configuration with subsequent requests.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use app_test_support::TestAppServer;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::GcpSetupParams;
|
||||
use codex_app_server_protocol::GcpSetupResponse;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::ModelListParams;
|
||||
use codex_app_server_protocol::ModelListResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_protocol::openai_models::ModelVisibility;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const CLEARED_AUTH_ENV: &[(&str, Option<&str>)] = &[
|
||||
("OPENAI_API_KEY", None),
|
||||
("CODEX_API_KEY", None),
|
||||
("OPENAI_FEDERATION_RULE_ID", None),
|
||||
("OPENAI_IDENTITY_TOKEN_FILE", None),
|
||||
("OPENAI_WORKLOAD_IDENTITY_CONTEXT", None),
|
||||
];
|
||||
|
||||
const READ_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 60);
|
||||
|
||||
fn write_fake_gcloud(home: &Path) -> Result<PathBuf> {
|
||||
#[cfg(unix)]
|
||||
let script = home.join("gcloud");
|
||||
#[cfg(unix)]
|
||||
codex_utils_cargo_bin::write_executable(
|
||||
&script,
|
||||
r#"#!/bin/sh
|
||||
if [ -f fail ]; then exit 1; fi
|
||||
printf '%s\n' "$GOOGLE_APPLICATION_CREDENTIALS" >> credential-log
|
||||
printf '%s\n' setup-token
|
||||
"#,
|
||||
)?;
|
||||
#[cfg(windows)]
|
||||
let script = home.join("gcloud.cmd");
|
||||
#[cfg(windows)]
|
||||
std::fs::write(
|
||||
&script,
|
||||
"@echo off\r\nif exist fail exit /b 1\r\nsetlocal EnableDelayedExpansion\r\necho(!GOOGLE_APPLICATION_CREDENTIALS!>>credential-log\r\nendlocal\r\necho setup-token\r\n",
|
||||
)?;
|
||||
Ok(script)
|
||||
}
|
||||
|
||||
async fn gcp_app_server(
|
||||
home: &Path,
|
||||
env_overrides: &[(&str, Option<&str>)],
|
||||
) -> Result<TestAppServer> {
|
||||
let existing_path = std::env::var_os("PATH").unwrap_or_default();
|
||||
let child_path = std::env::join_paths(
|
||||
std::iter::once(home.to_path_buf()).chain(std::env::split_paths(&existing_path)),
|
||||
)?;
|
||||
TestAppServer::builder()
|
||||
.with_codex_home(home)
|
||||
.with_env_overrides(&[
|
||||
(
|
||||
"PATH",
|
||||
Some(child_path.to_str().context("child PATH must be UTF-8")?),
|
||||
),
|
||||
("GOOGLE_APPLICATION_CREDENTIALS", None),
|
||||
("GOOGLE_CLOUD_PROJECT", Some("ambient-project")),
|
||||
("GOOGLE_CLOUD_LOCATION", Some("ambient-location")),
|
||||
])
|
||||
.with_env_overrides(CLEARED_AUTH_ENV)
|
||||
.with_env_overrides(env_overrides)
|
||||
.build_initialized_with_timeout(READ_TIMEOUT)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn setup_error(app_server: &mut TestAppServer, params: Value) -> Result<JSONRPCErrorError> {
|
||||
let id = app_server
|
||||
.send_raw_request("account/gcp/setup", Some(params))
|
||||
.await?;
|
||||
let error = timeout(
|
||||
READ_TIMEOUT,
|
||||
app_server.read_stream_until_error_message(RequestId::Integer(id)),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(error.error.code, -32600);
|
||||
Ok(error.error)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn setup_gcp_saves_overrides_restores_adc_and_refreshes_catalog() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let home = home.path();
|
||||
write_fake_gcloud(home)?;
|
||||
let mut catalog = codex_models_manager::bundled_models_response()?;
|
||||
catalog.models.retain(|model| model.slug == "gpt-6.1-sol");
|
||||
let model = catalog
|
||||
.models
|
||||
.first_mut()
|
||||
.context("bundled catalog must include a supported Vertex model")?;
|
||||
model.visibility = ModelVisibility::List;
|
||||
model.supported_in_api = true;
|
||||
let mut unsupported_model = model.clone();
|
||||
unsupported_model.slug = "test-non-vertex-model".to_string();
|
||||
// Make the startup catalog's default distinguishable from the GCP default.
|
||||
unsupported_model.priority = model.priority - 1;
|
||||
catalog.models.push(unsupported_model);
|
||||
let catalog_path = home.join("models.json");
|
||||
std::fs::write(&catalog_path, serde_json::to_vec(&catalog)?)?;
|
||||
let config_path = home.join("config.toml");
|
||||
let mut expected_config = json!({
|
||||
"model_catalog_json": catalog_path,
|
||||
"model_providers": {"gcp": {"http_headers": {"X-Existing": "preserved"}}}
|
||||
});
|
||||
std::fs::write(&config_path, toml::to_string(&expected_config)?)?;
|
||||
let selected = home.join("selected.json");
|
||||
let ambient = home.join("ambient.json");
|
||||
for file in [&selected, &ambient] {
|
||||
std::fs::write(file, r#"{"type":"external_account"}"#)?;
|
||||
}
|
||||
let mut app_server = gcp_app_server(
|
||||
home,
|
||||
&[(
|
||||
"GOOGLE_APPLICATION_CREDENTIALS",
|
||||
Some(ambient.to_str().context("non-UTF-8 ADC path")?),
|
||||
)],
|
||||
)
|
||||
.await?;
|
||||
let before: ModelListResponse = app_server
|
||||
.request(|request_id| ClientRequest::ModelList {
|
||||
request_id,
|
||||
params: ModelListParams::default(),
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(before.data.len(), 2);
|
||||
|
||||
let _: GcpSetupResponse = app_server
|
||||
.request(|request_id| ClientRequest::GcpSetup {
|
||||
request_id,
|
||||
params: GcpSetupParams {
|
||||
project_id: " selected-project ".to_string(),
|
||||
location: Some(" us-central1 ".to_string()),
|
||||
credential_file: Some(selected.to_string_lossy().into_owned()),
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
expected_config["model_provider"] = json!("gcp");
|
||||
expected_config["model_providers"]["gcp"]["project_id"] = json!("selected-project");
|
||||
expected_config["model_providers"]["gcp"]["location"] = json!("us-central1");
|
||||
expected_config["model_providers"]["gcp"]["credential_file"] = json!(selected);
|
||||
assert_eq!(
|
||||
toml::from_str::<Value>(&std::fs::read_to_string(&config_path)?)?,
|
||||
expected_config
|
||||
);
|
||||
|
||||
let after: ModelListResponse = app_server
|
||||
.request(|request_id| ClientRequest::ModelList {
|
||||
request_id,
|
||||
params: ModelListParams::default(),
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(after.data.len(), 1);
|
||||
assert_eq!(after.data[0].model, "gpt-6.1-sol");
|
||||
|
||||
// A managed GCP selection takes precedence without replacing the user's preference.
|
||||
expected_config["model_provider"] = json!("openai");
|
||||
std::fs::write(&config_path, toml::to_string(&expected_config)?)?;
|
||||
std::fs::write(home.join("requirements.toml"), "model_provider = 'gcp'")?;
|
||||
let request_id = app_server
|
||||
.send_raw_request(
|
||||
"account/gcp/setup",
|
||||
Some(json!({"projectId": "other-project"})),
|
||||
)
|
||||
.await?;
|
||||
let _: GcpSetupResponse = app_server.read_response(request_id).await?;
|
||||
expected_config["model_providers"]["gcp"]["project_id"] = json!("other-project");
|
||||
expected_config["model_providers"]["gcp"]["location"] = json!("global");
|
||||
expected_config["model_providers"]["gcp"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("credential_file");
|
||||
assert_eq!(
|
||||
toml::from_str::<Value>(&std::fs::read_to_string(&config_path)?)?,
|
||||
expected_config
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(home.join("credential-log"))?
|
||||
.lines()
|
||||
.map(Path::new)
|
||||
.collect::<Vec<_>>(),
|
||||
[selected.as_path(), ambient.as_path()]
|
||||
);
|
||||
let thread = app_server
|
||||
.start_thread(ThreadStartParams::default())
|
||||
.await?;
|
||||
assert_eq!(thread.model, after.data[0].model);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn setup_gcp_rejects_invalid_inputs_and_credentials_before_saving() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let home = home.path();
|
||||
let config_path = home.join("config.toml");
|
||||
std::fs::write(&config_path, "")?;
|
||||
let invalid = home.join("invalid.json");
|
||||
std::fs::write(&invalid, r#"["authorized_user"]"#)?;
|
||||
let mut server = gcp_app_server(
|
||||
home,
|
||||
&[("PATH", Some(home.to_str().context("non-UTF-8 PATH")?))],
|
||||
)
|
||||
.await?;
|
||||
let params = json!({"projectId": "project"});
|
||||
for (request, reason) in [
|
||||
(json!({"projectId": " "}), None),
|
||||
(params.clone(), Some("gcloudNotInstalled")),
|
||||
(
|
||||
json!({"projectId": "project", "credentialFile": invalid}),
|
||||
Some("credentialFileInvalid"),
|
||||
),
|
||||
] {
|
||||
let error = setup_error(&mut server, request).await?;
|
||||
assert_eq!(error.data, reason.map(|reason| json!({ "reason": reason })));
|
||||
}
|
||||
|
||||
write_fake_gcloud(home)?;
|
||||
std::fs::write(home.join("fail"), "")?;
|
||||
let error = setup_error(&mut server, params).await?;
|
||||
assert_eq!(error.data, Some(json!({"reason": "authCommandFailed"})));
|
||||
assert_eq!(std::fs::read_to_string(config_path)?, "");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn setup_gcp_validates_the_auth_override_relative_to_the_startup_directory() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let startup = TempDir::new()?;
|
||||
let script = write_fake_gcloud(home.path())?;
|
||||
let auth = toml::Value::try_from(json!({"command": script, "cwd": "."}))?;
|
||||
let config_path = home.path().join("config.toml");
|
||||
std::fs::write(&config_path, "")?;
|
||||
// The same command succeeds in CODEX_HOME but fails in the catalog's startup context.
|
||||
std::fs::write(startup.path().join("fail"), "")?;
|
||||
let mut server = TestAppServer::builder()
|
||||
.with_codex_home(startup.path())
|
||||
.with_env_overrides(CLEARED_AUTH_ENV)
|
||||
.with_env_overrides(&[(
|
||||
"CODEX_HOME",
|
||||
Some(home.path().to_str().context("non-UTF-8 CODEX_HOME")?),
|
||||
)])
|
||||
.with_args(&["-c", &format!("model_providers.gcp.auth={auth}")])
|
||||
.build_initialized_with_timeout(READ_TIMEOUT)
|
||||
.await?;
|
||||
|
||||
let error = setup_error(&mut server, json!({"projectId": "project"})).await?;
|
||||
assert_eq!(error.data, Some(json!({"reason": "authCommandFailed"})));
|
||||
assert_eq!(std::fs::read_to_string(config_path)?, "");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn setup_gcp_rejects_policy_and_endpoint_conflicts_before_saving() -> Result<()> {
|
||||
for (file, policy, expected_message) in [
|
||||
(
|
||||
"managed_config.toml",
|
||||
"forced_login_method = 'chatgpt'",
|
||||
"Google Cloud setup is disabled by the configured login policy.",
|
||||
),
|
||||
(
|
||||
"managed_config.toml",
|
||||
"[model_providers.gcp]\nproject_id = 'managed-project'",
|
||||
"Cannot configure `model_providers.gcp.project_id`: Overridden by legacy managed_config.toml",
|
||||
),
|
||||
(
|
||||
"managed_config.toml",
|
||||
"[model_providers.gcp]\nbase_url = 'https://vertex.example.com/v1'",
|
||||
"Google Cloud has a custom `base_url`",
|
||||
),
|
||||
(
|
||||
"requirements.toml",
|
||||
"model_provider = 'openai'",
|
||||
"requirements set `model_provider` to `openai`",
|
||||
),
|
||||
(
|
||||
"requirements.toml",
|
||||
"[application.network.domains]\n'oauth2.googleapis.com' = 'allow'",
|
||||
"disabled by application network restrictions",
|
||||
),
|
||||
] {
|
||||
let home = TempDir::new()?;
|
||||
let home = home.path();
|
||||
write_fake_gcloud(home)?;
|
||||
std::fs::write(home.join(file), policy)?;
|
||||
let config_path = home.join("config.toml");
|
||||
std::fs::write(&config_path, "")?;
|
||||
let mut app_server = gcp_app_server(home, &[]).await?;
|
||||
let error = setup_error(
|
||||
&mut app_server,
|
||||
json!({"projectId": "project", "credentialFile": home.join("missing.json")}),
|
||||
)
|
||||
.await?;
|
||||
assert!(
|
||||
error.message.contains(expected_message),
|
||||
"expected {expected_message:?}, got {:?}",
|
||||
error.message
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(config_path)?, "");
|
||||
assert!(!home.join("credential-log").exists());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn setup_gcp_stops_the_credential_command_when_network_permission_is_revoked() -> Result<()> {
|
||||
use core_test_support::process::wait_for_pid_file;
|
||||
use core_test_support::process::wait_for_process_exit;
|
||||
|
||||
let home = TempDir::new()?;
|
||||
let config_path = home.path().join("config.toml");
|
||||
let initial_config = r#"
|
||||
[model_providers.gcp.auth]
|
||||
command = "sh"
|
||||
args = ["-c", "echo $$ > refresh.pid; exec sleep 120"]
|
||||
timeout_ms = 120000
|
||||
"#;
|
||||
std::fs::write(&config_path, initial_config)?;
|
||||
let mut app_server = gcp_app_server(home.path(), &[]).await?;
|
||||
let request_id = app_server
|
||||
.send_raw_request("account/gcp/setup", Some(json!({"projectId": "project"})))
|
||||
.await?;
|
||||
let pid = wait_for_pid_file(&home.path().join("refresh.pid")).await?;
|
||||
|
||||
std::fs::write(
|
||||
home.path().join("requirements.toml"),
|
||||
"[application.network]",
|
||||
)?;
|
||||
app_server
|
||||
.send_raw_request("config/read", Some(json!({})))
|
||||
.await?;
|
||||
let error = timeout(
|
||||
READ_TIMEOUT,
|
||||
app_server.read_stream_until_error_message(RequestId::Integer(request_id)),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(
|
||||
error.error.message,
|
||||
"application network permission was revoked"
|
||||
);
|
||||
wait_for_process_exit(&pid).await?;
|
||||
assert_eq!(std::fs::read_to_string(config_path)?, initial_config);
|
||||
Ok(())
|
||||
}
|
||||
@@ -260,9 +260,12 @@ async fn managed_reviewer_refreshes_global_instructions_before_reuse() -> Result
|
||||
.iter()
|
||||
.find(|replayed| replayed["content"] == item["content"])
|
||||
.expect("previous Guardian reply is replayed");
|
||||
// aKode: internal metadata passthrough is stripped from model requests unless
|
||||
// the provider holds the runtime-only `include_internal_metadata` grant.
|
||||
assert!(item["internal_chat_message_metadata_passthrough"].is_object());
|
||||
assert_eq!(
|
||||
replayed["internal_chat_message_metadata_passthrough"],
|
||||
item["internal_chat_message_metadata_passthrough"],
|
||||
replayed.get("internal_chat_message_metadata_passthrough"),
|
||||
None
|
||||
);
|
||||
}
|
||||
// Private reviewer events arrive on the parent's subscription with the
|
||||
|
||||
@@ -217,7 +217,7 @@ approval_policy = "on-request"
|
||||
approvals_reviewer = "auto_review"
|
||||
sandbox_mode = "read-only"
|
||||
cli_auth_credentials_store = "file"
|
||||
openai_base_url = "{responses_url}/backend-api/codex"
|
||||
model_provider = "openai"
|
||||
chatgpt_base_url = "{responses_url}/backend-api"
|
||||
|
||||
[features]
|
||||
@@ -233,6 +233,17 @@ enabled = true
|
||||
|
||||
[features.guardianv2.review_scope]
|
||||
computer_use_only = false
|
||||
|
||||
# aKode: `openai_base_url` no longer configures a built-in provider; declare the
|
||||
# equivalent of the removed built-in `openai` provider explicitly.
|
||||
[model_providers.openai]
|
||||
name = "OpenAI"
|
||||
base_url = "{responses_url}/backend-api/codex"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = true
|
||||
supports_websockets = true
|
||||
merge_system_messages = false
|
||||
capabilities = {{ hosted_web_search = true, remote_compaction = "v2" }}
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
|
||||
@@ -105,15 +105,19 @@ fn write_plugin_hook_config(codex_home: &std::path::Path, hooks_json: &str) -> R
|
||||
r#"{"name":"demo"}"#,
|
||||
)?;
|
||||
std::fs::write(plugin_root.join("hooks/hooks.json"), hooks_json)?;
|
||||
// aKode: no default provider or bundled catalog; threads need an explicit catalog.
|
||||
std::fs::write(
|
||||
codex_home.join("config.toml"),
|
||||
r#"[features]
|
||||
format!(
|
||||
r#"{}[features]
|
||||
plugins = true
|
||||
hooks = true
|
||||
|
||||
[plugins."demo@test"]
|
||||
enabled = true
|
||||
"#,
|
||||
app_test_support::bundled_model_catalog_config(codex_home)?
|
||||
),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ model = "mock-model"
|
||||
approval_policy = "never"
|
||||
sandbox_mode = "read-only"
|
||||
model_provider = "mock_provider"
|
||||
|
||||
{catalog}
|
||||
[skills]
|
||||
include_instructions = true
|
||||
|
||||
@@ -75,8 +75,11 @@ base_url = "{}/v1"
|
||||
wire_api = "responses"
|
||||
request_max_retries = 0
|
||||
stream_max_retries = 0
|
||||
merge_system_messages = false
|
||||
"#,
|
||||
server.uri()
|
||||
server.uri(),
|
||||
// aKode: explicit catalog (no bundled default) and upstream message layout.
|
||||
catalog = app_test_support::bundled_model_catalog_config(codex_home.path())?
|
||||
),
|
||||
)?;
|
||||
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
mod account;
|
||||
|
||||
mod account_gcp;
|
||||
mod agent_message_board;
|
||||
mod application_network;
|
||||
#[path = "attached_thread_tests.rs"]
|
||||
mod attached_thread;
|
||||
mod auto_env;
|
||||
#[path = "bedrock_gov_cloud_tests.rs"]
|
||||
mod bedrock_gov_cloud;
|
||||
#[path = "bedrock_service_tier_tests.rs"]
|
||||
mod bedrock_service_tier;
|
||||
mod bedrock_setup;
|
||||
mod client_metadata;
|
||||
mod code_mode_host;
|
||||
mod collaboration_mode_list;
|
||||
@@ -58,8 +52,6 @@ mod feedback;
|
||||
mod fs;
|
||||
#[path = "gateway_oauth_tests.rs"]
|
||||
mod gateway_oauth;
|
||||
#[path = "gcp_setup_tests.rs"]
|
||||
mod gcp_setup;
|
||||
mod guardian_v2;
|
||||
mod hooks_list;
|
||||
mod host_skills;
|
||||
|
||||
@@ -3,7 +3,6 @@ use std::time::Duration;
|
||||
use anyhow::Error;
|
||||
use anyhow::Result;
|
||||
use app_test_support::TestAppServer;
|
||||
use app_test_support::write_models_cache;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::ExperimentalFeatureEnablementSetParams;
|
||||
use codex_app_server_protocol::ExperimentalFeatureEnablementSetResponse;
|
||||
@@ -165,7 +164,9 @@ requires_openai_auth = true
|
||||
// prevents bundled models from being advertised for this provider.
|
||||
&[]
|
||||
} else {
|
||||
&bundled
|
||||
// aKode: without `model_catalog_url` the provider's OpenAI-format `GET /models`
|
||||
// listing is the source (no bundled catalog); this codex-format body lists nothing.
|
||||
&[]
|
||||
};
|
||||
assert_eq!(
|
||||
response,
|
||||
@@ -174,8 +175,20 @@ requires_openai_auth = true
|
||||
next_cursor: None,
|
||||
}
|
||||
);
|
||||
let _ = bundled;
|
||||
if !catalog_opt_in {
|
||||
// aKode: providers without a catalog URL list their models from `GET /models`.
|
||||
assert!(
|
||||
server
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("request recording is enabled")
|
||||
.iter()
|
||||
.any(|request| request.url.path() == "/v1/models")
|
||||
);
|
||||
}
|
||||
// Only startup opt-outs prevent fetches before the app sends its enablement.
|
||||
if user_enablement == Some(false) || !catalog_opt_in {
|
||||
if user_enablement == Some(false) {
|
||||
assert!(
|
||||
server
|
||||
.received_requests()
|
||||
@@ -235,6 +248,15 @@ fn model_from_preset(preset: &ModelPreset) -> Model {
|
||||
}
|
||||
}
|
||||
|
||||
/// aKode: providers without `model_catalog_url` no longer fall back to the bundled
|
||||
/// catalog (or read `models_cache.json`), so the listing tests configure it explicitly.
|
||||
fn write_bundled_model_catalog_config(codex_home: &std::path::Path) -> std::io::Result<()> {
|
||||
std::fs::write(
|
||||
codex_home.join("config.toml"),
|
||||
app_test_support::bundled_model_catalog_config(codex_home)?,
|
||||
)
|
||||
}
|
||||
|
||||
fn expected_visible_models() -> Vec<Model> {
|
||||
// Filter by supported_in_api to support testing with both ChatGPT and non-ChatGPT auth modes.
|
||||
let mut presets = ModelPreset::filter_by_auth(
|
||||
@@ -255,7 +277,7 @@ fn expected_visible_models() -> Vec<Model> {
|
||||
#[tokio::test]
|
||||
async fn list_models_returns_all_models_with_large_limit() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
write_models_cache(codex_home.path()).await?;
|
||||
write_bundled_model_catalog_config(codex_home.path())?;
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
@@ -286,7 +308,7 @@ async fn list_models_returns_all_models_with_large_limit() -> Result<()> {
|
||||
#[tokio::test]
|
||||
async fn list_models_includes_hidden_models() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
write_models_cache(codex_home.path()).await?;
|
||||
write_bundled_model_catalog_config(codex_home.path())?;
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
@@ -471,7 +493,7 @@ model_catalog_url = "{server_uri}/v1/models"
|
||||
#[tokio::test]
|
||||
async fn list_models_pagination_works() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
write_models_cache(codex_home.path()).await?;
|
||||
write_bundled_model_catalog_config(codex_home.path())?;
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
@@ -518,7 +540,7 @@ async fn list_models_pagination_works() -> Result<()> {
|
||||
#[tokio::test]
|
||||
async fn list_models_rejects_invalid_cursor() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
write_models_cache(codex_home.path()).await?;
|
||||
write_bundled_model_catalog_config(codex_home.path())?;
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
|
||||
@@ -51,32 +51,6 @@ async fn list_models(server: &mut TestAppServer) -> Result<ModelListResponse> {
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn model_list_accepts_unchanged_gcp_requirements() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(home.path().join("config.toml"), "")?;
|
||||
std::fs::write(
|
||||
home.path().join("requirements.toml"),
|
||||
r#"
|
||||
model_provider = "gcp"
|
||||
[model_providers.gcp]
|
||||
project_id = "managed-project"
|
||||
location = "us-central1"
|
||||
"#,
|
||||
)?;
|
||||
let mut server = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(home.path())
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
.build_initialized()
|
||||
.await?;
|
||||
|
||||
let initial = list_models(&mut server).await?;
|
||||
assert!(!initial.data.is_empty());
|
||||
assert_eq!(list_models(&mut server).await?, initial);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn sign_in(server: &mut TestAppServer) -> Result<()> {
|
||||
let id = server
|
||||
.send_login_account_api_key_request("sk-catalog-test")
|
||||
@@ -378,8 +352,20 @@ async fn model_list_reuses_catalog_until_account_change() -> Result<()> {
|
||||
async fn model_list_preserves_invalid_startup_config_fallback() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(home.path().join("config.toml"), "model = [")?;
|
||||
// aKode: there is no bundled default catalog; supply one through a CLI override,
|
||||
// which the invalid-config fallback still honors.
|
||||
let catalog_path = home.path().join("bundled-models.json");
|
||||
std::fs::write(
|
||||
&catalog_path,
|
||||
include_str!("../../../../models-manager/models.json"),
|
||||
)?;
|
||||
let catalog_override = format!(
|
||||
"model_catalog_json={}",
|
||||
serde_json::to_string(&catalog_path.display().to_string())?
|
||||
);
|
||||
let mut server = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_args(&["-c", &catalog_override])
|
||||
.with_codex_home(home.path())
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
.build_initialized_with_timeout(Duration::from_secs(/*secs*/ 60))
|
||||
|
||||
@@ -25,19 +25,26 @@ async fn read_default_provider_capabilities() -> Result<()> {
|
||||
let received: ModelProviderCapabilitiesReadResponse =
|
||||
timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??;
|
||||
|
||||
let expected = ModelProviderCapabilitiesReadResponse {
|
||||
web_search: true,
|
||||
};
|
||||
// aKode: hosted web search is provider-opt-in, and there is no default provider.
|
||||
let expected = ModelProviderCapabilitiesReadResponse { web_search: false };
|
||||
assert_eq!(received, expected);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_amazon_bedrock_provider_capabilities() -> Result<()> {
|
||||
async fn read_opted_in_provider_capabilities() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"model_provider = "amazon-bedrock"
|
||||
r#"model_provider = "mock"
|
||||
|
||||
[model_providers.mock]
|
||||
name = "mock"
|
||||
base_url = "http://127.0.0.1:0/v1"
|
||||
wire_api = "responses"
|
||||
|
||||
[model_providers.mock.capabilities]
|
||||
hosted_web_search = true
|
||||
"#,
|
||||
)?;
|
||||
let mut mcp = TestAppServer::builder()
|
||||
@@ -52,37 +59,9 @@ async fn read_amazon_bedrock_provider_capabilities() -> Result<()> {
|
||||
let received: ModelProviderCapabilitiesReadResponse =
|
||||
timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??;
|
||||
|
||||
let expected = ModelProviderCapabilitiesReadResponse {
|
||||
web_search: true,
|
||||
};
|
||||
assert_eq!(received, expected);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_amazon_bedrock_runtime_provider_capabilities() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"model_provider = "amazon-bedrock-runtime"
|
||||
"#,
|
||||
)?;
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
|
||||
.await?;
|
||||
|
||||
let request_id = mcp
|
||||
.send_model_provider_capabilities_read_request(ModelProviderCapabilitiesReadParams {})
|
||||
.await?;
|
||||
let received: ModelProviderCapabilitiesReadResponse =
|
||||
timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??;
|
||||
|
||||
assert_eq!(
|
||||
received,
|
||||
ModelProviderCapabilitiesReadResponse {
|
||||
web_search: false,
|
||||
}
|
||||
ModelProviderCapabilitiesReadResponse { web_search: true }
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -93,7 +93,8 @@ async fn create_and_patch_gateway_providers_without_changing_the_default() -> Re
|
||||
.find(|p| p["id"] == "team-gateway"),
|
||||
Some(&expected)
|
||||
);
|
||||
assert_eq!(after["defaultProviderId"], "openai");
|
||||
// aKode: there is no default (`openai`) provider when none is configured.
|
||||
assert_eq!(after["defaultProviderId"], "");
|
||||
let persisted: Value = toml::from_str(&before)?;
|
||||
assert_eq!(
|
||||
persisted["model_providers"]["team-gateway"],
|
||||
@@ -145,11 +146,8 @@ async fn custom_provider_edits_preserve_other_fields_and_respect_policy() -> Res
|
||||
json!({"name": "Changed"}),
|
||||
"configLayerReadonly",
|
||||
),
|
||||
(
|
||||
"openai",
|
||||
json!({"name": "Changed"}),
|
||||
"configValidationError",
|
||||
),
|
||||
// aKode: `openai` is no longer a built-in provider, so it is an unknown id here.
|
||||
("openai", json!({"name": "Changed"}), "configPathNotFound"),
|
||||
("external", json!({"envKey": null}), "configValidationError"),
|
||||
(
|
||||
"basic",
|
||||
@@ -163,7 +161,6 @@ async fn custom_provider_edits_preserve_other_fields_and_respect_policy() -> Res
|
||||
"configValidationError",
|
||||
),
|
||||
("ollama", json!({}), "configValidationError"),
|
||||
("gcp", json!({}), "configValidationError"),
|
||||
] {
|
||||
patch["type"] = json!("customGateway");
|
||||
patch["providerId"] = json!(id);
|
||||
@@ -191,177 +188,3 @@ async fn custom_provider_edits_preserve_other_fields_and_respect_policy() -> Res
|
||||
assert_eq!(persisted, expected);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn custom_provider_writes_reject_builtin_auth_names_and_preserve_existing_ids() -> Result<()>
|
||||
{
|
||||
let home = TempDir::new()?;
|
||||
let config_path = home.path().join("config.toml");
|
||||
let ids = [r"team\gpu", "corp.gateway", r#"team"gpu"#];
|
||||
let mut providers = json!({});
|
||||
for id in ids {
|
||||
providers[id] = json!({"name":"Amazon Bedrock", "base_url":"https://old.example.test"});
|
||||
}
|
||||
std::fs::write(
|
||||
&config_path,
|
||||
toml::to_string(&json!({"model_providers":providers}))?,
|
||||
)?;
|
||||
let mut server = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.with_env_overrides(CLEARED_AUTH_ENV)
|
||||
.build_initialized()
|
||||
.await?;
|
||||
|
||||
let new_url = "https://new.example.test";
|
||||
for (provider_id, mut settings) in [
|
||||
(None, json!({"name": "OpenAI", "baseUrl": new_url})),
|
||||
(
|
||||
None,
|
||||
json!({"name": " Amazon Bedrock ", "baseUrl": new_url}),
|
||||
),
|
||||
(Some(ids[0]), json!({"name": "Amazon Bedrock Runtime"})),
|
||||
(Some(ids[0]), json!({"name": "Google Cloud Vertex AI"})),
|
||||
(Some(ids[0]), json!({"baseUrl": new_url})),
|
||||
(Some(ids[0]), json!({"name":"Renamed", "envKey":null})),
|
||||
] {
|
||||
settings["type"] = json!("customGateway");
|
||||
settings["providerId"] = json!(provider_id);
|
||||
let request = server
|
||||
.send_request(
|
||||
"modelProvider/config/write",
|
||||
Some(json!({"settings":settings})),
|
||||
)
|
||||
.await?;
|
||||
let error = server
|
||||
.read_stream_until_error_message(RequestId::Integer(request))
|
||||
.await?;
|
||||
assert_eq!(
|
||||
error.error.data,
|
||||
Some(json!({"config_write_error_code":"configValidationError"}))
|
||||
);
|
||||
}
|
||||
|
||||
for id in ids {
|
||||
let request = server
|
||||
.send_request(
|
||||
"modelProvider/config/write",
|
||||
Some(json!({"settings":{"type":"customGateway","providerId":id,"name":"Amazon Bedrock Mantle","baseUrl":new_url}})),
|
||||
)
|
||||
.await?;
|
||||
let saved: Value = server.read_response(request).await?;
|
||||
assert_eq!(saved["provider"]["id"], id);
|
||||
providers[id] = json!({"name": "Amazon Bedrock Mantle", "base_url": new_url});
|
||||
}
|
||||
let saved: Value = toml::from_str(&std::fs::read_to_string(config_path)?)?;
|
||||
assert_eq!(saved["model_providers"], providers);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn builtin_provider_patches_preserve_auth_and_do_not_select_or_authenticate() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
let config_path = home.path().join("config.toml");
|
||||
std::fs::write(
|
||||
home.path().join("requirements.toml"),
|
||||
"model_provider = 'openai'\n",
|
||||
)?;
|
||||
let mut server = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.with_env_overrides(CLEARED_AUTH_ENV)
|
||||
.build_initialized()
|
||||
.await?;
|
||||
let credential_file = home.path().join("missing-credentials.json");
|
||||
for mut settings in [
|
||||
json!({"type":"bedrock", "providerId":"amazon-bedrock", "profile":"work", "region":"us-east-1"}),
|
||||
json!({"type":"bedrock", "providerId":"amazon-bedrock-runtime", "profile":null, "region":"us-west-2"}),
|
||||
json!({"type":"gcp", "providerId":"gcp", "projectId":"test-project", "location":"global", "credentialFile":credential_file}),
|
||||
] {
|
||||
let params = serde_json::from_value(json!({"settings":settings}))?;
|
||||
let saved: Value = server
|
||||
.request(|request_id| ClientRequest::ModelProviderConfigWrite { request_id, params })
|
||||
.await?;
|
||||
let id = settings
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("providerId")
|
||||
.unwrap();
|
||||
assert_eq!(saved["provider"]["id"], id);
|
||||
assert_eq!(saved["provider"]["settings"], settings);
|
||||
}
|
||||
let refresh = json!({"command":"aws", "args":["sso", "login"]});
|
||||
let export = json!({"command":"unused-credential-command", "args":["test-only"]});
|
||||
let mut configured: Value = toml::from_str(&std::fs::read_to_string(&config_path)?)?;
|
||||
configured["model_providers"]["amazon-bedrock"]["aws"]["auth_refresh"] = refresh.clone();
|
||||
configured["model_providers"]["amazon-bedrock-runtime"]["aws"]["credential_export"] =
|
||||
export.clone();
|
||||
std::fs::write(&config_path, toml::to_string(&configured)?)?;
|
||||
for settings in [
|
||||
json!({"type":"bedrock", "providerId":"amazon-bedrock", "region":null}),
|
||||
json!({"type":"bedrock", "providerId":"amazon-bedrock-runtime", "region":"eu-west-1"}),
|
||||
json!({"type":"gcp", "providerId":"gcp", "location":"us-central1", "credentialFile":null}),
|
||||
json!({"type":"gcp", "providerId":"gcp"}),
|
||||
] {
|
||||
let params = serde_json::from_value(json!({"settings":settings}))?;
|
||||
let saved: Value = server
|
||||
.request(|request_id| ClientRequest::ModelProviderConfigWrite { request_id, params })
|
||||
.await?;
|
||||
assert_eq!(saved["provider"]["id"], settings["providerId"]);
|
||||
}
|
||||
let list: Value = server
|
||||
.request(|request_id| ClientRequest::ModelProviderList {
|
||||
request_id,
|
||||
params: Default::default(),
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(list["defaultProviderId"], "openai");
|
||||
assert_eq!(list["canChangeDefault"], false);
|
||||
let before_rejections = std::fs::read_to_string(&config_path)?;
|
||||
let actual: Value = toml::from_str(&before_rejections)?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
json!({"model_providers": {
|
||||
"amazon-bedrock": {"aws":{"profile":"work", "auth_refresh":refresh}},
|
||||
"amazon-bedrock-runtime": {"aws":{"region":"eu-west-1", "credential_export":export}},
|
||||
"gcp":{"project_id":"test-project", "location":"us-central1"}
|
||||
}})
|
||||
);
|
||||
for settings in [
|
||||
json!({"type":"bedrock", "providerId":"amazon-bedrock-runtime", "profile":"conflicts-with-command", "region":"must-not-save"}),
|
||||
json!({"type":"gcp", "providerId":"gcp", "credentialFile":"relative/path", "location":"must-not-save"}),
|
||||
] {
|
||||
let write = server
|
||||
.send_request(
|
||||
"modelProvider/config/write",
|
||||
Some(json!({"settings":settings})),
|
||||
)
|
||||
.await?;
|
||||
let error = server
|
||||
.read_stream_until_error_message(RequestId::Integer(write))
|
||||
.await?;
|
||||
assert_eq!(
|
||||
error.error.data,
|
||||
Some(json!({"config_write_error_code":"configValidationError"}))
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(&config_path)?, before_rejections);
|
||||
}
|
||||
for settings in [
|
||||
json!({"type":"bedrock", "providerId":"gcp", "region":"must-not-save"}),
|
||||
json!({"type":"gcp", "providerId":"amazon-bedrock", "location":"must-not-save"}),
|
||||
json!({"type":"bedrock", "providerId":"amazon-bedrock", "envKey":"UNSUPPORTED"}),
|
||||
json!({"type":"gcp", "providerId":"gcp", "profile":"wrong-provider-field"}),
|
||||
json!({"type":"gcp", "location":"missing-id"}),
|
||||
] {
|
||||
let write = server
|
||||
.send_request(
|
||||
"modelProvider/config/write",
|
||||
Some(json!({"settings":settings})),
|
||||
)
|
||||
.await?;
|
||||
let error = server
|
||||
.read_stream_until_error_message(RequestId::Integer(write))
|
||||
.await?;
|
||||
assert_eq!(error.error.code, -32600);
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(&config_path)?, before_rejections);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -17,20 +17,12 @@ const CLEARED_AUTH_ENV: &[(&str, Option<&str>)] = &[
|
||||
];
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_without_provider_definitions_only_returns_openai() -> Result<()> {
|
||||
for (config, default_id, base_url) in [
|
||||
("", "openai", None),
|
||||
("model_provider = 'ollama'", "ollama", None),
|
||||
(
|
||||
"openai_base_url = 'https://proxy.example.test/v1'",
|
||||
"openai",
|
||||
Some("https://proxy.example.test/v1"),
|
||||
),
|
||||
(
|
||||
"openai_base_url = 'https://proxy.example.test/v1?token=test-only'",
|
||||
"openai",
|
||||
None,
|
||||
),
|
||||
async fn list_without_provider_definitions_is_empty_and_has_no_openai_default() -> Result<()> {
|
||||
// aKode has no built-in OpenAI provider; `openai_base_url` no longer creates one.
|
||||
for (config, default_id) in [
|
||||
("", ""),
|
||||
("model_provider = 'ollama'", "ollama"),
|
||||
("openai_base_url = 'https://proxy.example.test/v1'", ""),
|
||||
] {
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(home.path().join("config.toml"), config)?;
|
||||
@@ -46,8 +38,7 @@ async fn list_without_provider_definitions_only_returns_openai() -> Result<()> {
|
||||
assert_eq!(
|
||||
list,
|
||||
json!({
|
||||
"data": [{"id":"openai", "name":"OpenAI", "canEdit":false,
|
||||
"baseUrl":base_url, "settings":{"type":"openai"}}],
|
||||
"data": [],
|
||||
"defaultProviderId":default_id, "canChangeDefault":true,
|
||||
})
|
||||
);
|
||||
@@ -56,19 +47,15 @@ async fn list_without_provider_definitions_only_returns_openai() -> Result<()> {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_builtin_and_custom_providers_with_editable_settings() -> Result<()> {
|
||||
async fn list_custom_providers_with_editable_settings() -> Result<()> {
|
||||
let home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
r#"
|
||||
[model_providers.amazon-bedrock]
|
||||
base_url = "https://bedrock.example.test/v1"
|
||||
[model_providers.amazon-bedrock.aws]
|
||||
profile = "work"
|
||||
region = "us-east-1"
|
||||
[model_providers.amazon-bedrock-runtime.aws]
|
||||
region = "us-east-1"
|
||||
[model_providers.gcp]
|
||||
[model_providers.local]
|
||||
name = "Local server"
|
||||
base_url = "http://192.0.2.10:8080/v1"
|
||||
api_key = "keyring"
|
||||
[model_providers.basic]
|
||||
name = "Basic auth gateway"
|
||||
base_url = "https://user:password@basic.example.test/v1"
|
||||
@@ -110,14 +97,6 @@ base_url = "https://managed.example.test"
|
||||
json!({
|
||||
"defaultProviderId":"corp.gateway", "canChangeDefault":false,
|
||||
"data": [
|
||||
{
|
||||
"id":"amazon-bedrock", "name":"Amazon Bedrock Mantle", "canEdit":true,
|
||||
"baseUrl":"https://bedrock.example.test/v1", "settings":{"type":"bedrock", "profile":"work", "region":"us-east-1"},
|
||||
},
|
||||
{
|
||||
"id":"amazon-bedrock-runtime", "name":"Amazon Bedrock Runtime", "canEdit":true,
|
||||
"baseUrl":null, "settings":{"type":"bedrock", "profile":null, "region":"us-east-1"},
|
||||
},
|
||||
{
|
||||
"id":"basic", "name":"Basic auth gateway", "canEdit":true, "baseUrl":null,
|
||||
"settings":{"type":"customGateway", "auth":{"mode":"externallyConfigured", "envKey":null}},
|
||||
@@ -131,12 +110,8 @@ base_url = "https://managed.example.test"
|
||||
"baseUrl":null, "settings":{"type":"customGateway", "auth":{"mode":"externallyConfigured", "envKey":"EXTERNAL_KEY"}},
|
||||
},
|
||||
{
|
||||
"id":"gcp", "name":"Google Cloud Vertex AI", "canEdit":true,
|
||||
"baseUrl":null, "settings":{"type":"gcp", "projectId":null, "location":null, "credentialFile":null},
|
||||
},
|
||||
{
|
||||
"id":"openai", "name":"OpenAI", "canEdit":false,
|
||||
"baseUrl":null, "settings":{"type":"openai"},
|
||||
"id":"local", "name":"Local server", "canEdit":true,
|
||||
"baseUrl":"http://192.0.2.10:8080/v1", "settings":{"type":"customGateway", "auth":{"mode":"externallyConfigured", "envKey":null}},
|
||||
},
|
||||
{
|
||||
"id":"query", "name":"Query gateway", "canEdit":true,
|
||||
|
||||
@@ -1593,60 +1593,6 @@ async fn plugin_list_includes_api_curated_marketplace_for_api_auth() -> Result<(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_list_includes_api_curated_marketplace_for_bedrock_without_codex_auth() -> Result<()>
|
||||
{
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"model_provider = "amazon-bedrock"
|
||||
|
||||
[model_providers.amazon-bedrock.aws]
|
||||
region = "us-east-2"
|
||||
profile = "default"
|
||||
|
||||
[features]
|
||||
plugins = true
|
||||
"#,
|
||||
)?;
|
||||
write_openai_curated_marketplace(codex_home.path(), &["chatgpt-plugin"])?;
|
||||
write_openai_api_curated_marketplace(codex_home.path(), &["api-plugin"])?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
|
||||
.await?;
|
||||
|
||||
let request_id = mcp
|
||||
.send_plugin_list_request(PluginListParams {
|
||||
cwds: None,
|
||||
force_refetch: false,
|
||||
})
|
||||
.await?;
|
||||
let response: PluginListResponse =
|
||||
timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??;
|
||||
|
||||
assert!(!codex_home.path().join("auth.json").exists());
|
||||
let api_curated_marketplace = response
|
||||
.marketplaces
|
||||
.iter()
|
||||
.find(|marketplace| marketplace.name == "openai-api-curated")
|
||||
.expect("expected API curated marketplace");
|
||||
assert_eq!(api_curated_marketplace.plugins.len(), 1);
|
||||
assert_eq!(
|
||||
api_curated_marketplace.plugins[0].id,
|
||||
"api-plugin@openai-api-curated"
|
||||
);
|
||||
assert!(
|
||||
response
|
||||
.marketplaces
|
||||
.iter()
|
||||
.all(|marketplace| marketplace.name != "openai-curated")
|
||||
);
|
||||
assert!(response.marketplace_load_errors.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case(false; "no project override")]
|
||||
#[test_case(true; "project enables local plugins only")]
|
||||
#[tokio::test]
|
||||
@@ -1776,19 +1722,6 @@ fn write_installed_plugin_with_version(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_openai_curated_marketplace(
|
||||
codex_home: &std::path::Path,
|
||||
plugin_names: &[&str],
|
||||
) -> std::io::Result<()> {
|
||||
write_curated_marketplace(
|
||||
codex_home,
|
||||
"marketplace.json",
|
||||
"openai-curated",
|
||||
/*display_name*/ None,
|
||||
plugin_names,
|
||||
)
|
||||
}
|
||||
|
||||
fn write_openai_api_curated_marketplace(
|
||||
codex_home: &std::path::Path,
|
||||
plugin_names: &[&str],
|
||||
|
||||
@@ -982,7 +982,11 @@ async fn projects_validate_filters_cursors_and_sqlite_less_assignment() -> Resul
|
||||
let store_id = Uuid::now_v7();
|
||||
std::fs::write(
|
||||
unsupported_projects_home.path().join("config.toml"),
|
||||
format!("experimental_thread_store = {{ type = \"in_memory\", id = \"{store_id}\" }}"),
|
||||
// aKode: this overwrites the mock config; keep an explicit catalog (no default one).
|
||||
format!(
|
||||
"{}experimental_thread_store = {{ type = \"in_memory\", id = \"{store_id}\" }}",
|
||||
app_test_support::bundled_model_catalog_config(unsupported_projects_home.path())?
|
||||
),
|
||||
)?;
|
||||
let mut unsupported_projects = TestAppServer::builder()
|
||||
.with_codex_home(unsupported_projects_home.path())
|
||||
|
||||
@@ -786,6 +786,8 @@ fn assert_no_local_persistence_artifacts(codex_home: &Path) -> Result<()> {
|
||||
#[cfg(windows)]
|
||||
entries.remove(".sandbox");
|
||||
entries.remove("shell_snapshots");
|
||||
// aKode: the explicit model catalog the test harness writes is configuration input.
|
||||
entries.remove("test-models.json");
|
||||
assert_eq!(
|
||||
entries,
|
||||
BTreeSet::from([
|
||||
|
||||
@@ -116,6 +116,11 @@ async fn legacy_permission_profile_requests_fail_closed() -> Result<()> {
|
||||
#[tokio::test]
|
||||
async fn thread_start_keeps_unknown_field_compatibility_with_named_permissions() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
// aKode: no default provider or bundled catalog; threads need an explicit catalog.
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
app_test_support::bundled_model_catalog_config(codex_home.path())?,
|
||||
)?;
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
|
||||
@@ -17,7 +17,7 @@ Settings:
|
||||
stream: true
|
||||
tool_choice: "auto"
|
||||
-- request 1 (turn) --
|
||||
00:additional_tools/developer (3; hash=bf13940dee826ebd):
|
||||
00:additional_tools/developer (2; hash=439dcadc72baaea1):
|
||||
- namespace/functions; hash=028af59ad835936d
|
||||
- function/exec_command
|
||||
- function/write_stdin
|
||||
@@ -34,8 +34,6 @@ Settings:
|
||||
- function/send_input
|
||||
- function/spawn_agent
|
||||
- function/wait_agent
|
||||
- namespace/web: Tools in the web namespace.; hash=0037b1ed8d50fab5
|
||||
- function/run
|
||||
01:message/developer:
|
||||
Retain these base instructions.
|
||||
02:message/developer[4]:
|
||||
@@ -47,9 +45,8 @@ Settings:
|
||||
- `r0` = `<SKILLS_ROOT>`
|
||||
- `r1` = `<SKILLS_ROOT>/.system`
|
||||
### Available skills
|
||||
- openai-docs: API first-timers, Codex/Work Q&A. If the user already has an OpenAI API integration, skip...upplied text or data. (file: r1/openai-docs/SKILL.md) [hash=8ba7f79795ddc1cb]
|
||||
- skill-creator: Create or update a Codex skill with appropriately scoped instructions and any needed supporting resources. (file: r1/skill-creator/SKILL.md)
|
||||
- skill-installer: Install Codex skills into $CODEX_HOME/skills from a curated list or a GitHub repo pat...g private repos). (file: r1/skill-installer/SKILL.md) [hash=80e87da510d34d88]
|
||||
- skill-installer: Install aKode skills into $CODEX_HOME/skills from the default skills repository (the ...g private repos). (file: r1/skill-installer/SKILL.md) [hash=50f61366dff05eec]
|
||||
- app-store-screenshots: App Store and Google Play screenshot creation with exact platform specs. Covers...ore listing (file: r0/app-store-screenshots/SKILL.md) [hash=3f178aa58b5c4f8e]
|
||||
- assistant-ui: Overview and router for assistant-ui, the React library for building AI chat interfaces ...d by those siblings. (file: r0/assistant-ui/SKILL.md) [hash=61291772e6f2139c]
|
||||
- find-skills: Helps users discover and install agent skills when they ask questions like "how do I do X...an installable skill. (file: r0/find-skills/SKILL.md) [hash=48b9e99d9200af8d]
|
||||
@@ -82,7 +79,7 @@ Settings:
|
||||
## Window 2 (after request 2: input repeated)
|
||||
Settings: same as window 1
|
||||
-- request 3 (turn) --
|
||||
00:additional_tools/developer (3; hash=bf13940dee826ebd):
|
||||
00:additional_tools/developer (2; hash=439dcadc72baaea1):
|
||||
- namespace/functions; hash=028af59ad835936d
|
||||
- function/exec_command
|
||||
- function/write_stdin
|
||||
@@ -99,8 +96,6 @@ Settings: same as window 1
|
||||
- function/send_input
|
||||
- function/spawn_agent
|
||||
- function/wait_agent
|
||||
- namespace/web: Tools in the web namespace.; hash=0037b1ed8d50fab5
|
||||
- function/run
|
||||
01:message/developer:
|
||||
Retain these base instructions.
|
||||
02:message/developer[4]:
|
||||
@@ -112,9 +107,8 @@ Settings: same as window 1
|
||||
- `r0` = `<SKILLS_ROOT>`
|
||||
- `r1` = `<SKILLS_ROOT>/.system`
|
||||
### Available skills
|
||||
- openai-docs: API first-timers, Codex/Work Q&A. If the user already has an OpenAI API integration, skip...upplied text or data. (file: r1/openai-docs/SKILL.md) [hash=8ba7f79795ddc1cb]
|
||||
- skill-creator: Create or update a Codex skill with appropriately scoped instructions and any needed supporting resources. (file: r1/skill-creator/SKILL.md)
|
||||
- skill-installer: Install Codex skills into $CODEX_HOME/skills from a curated list or a GitHub repo pat...g private repos). (file: r1/skill-installer/SKILL.md) [hash=80e87da510d34d88]
|
||||
- skill-installer: Install aKode skills into $CODEX_HOME/skills from the default skills repository (the ...g private repos). (file: r1/skill-installer/SKILL.md) [hash=50f61366dff05eec]
|
||||
- app-store-screenshots: App Store and Google Play screenshot creation with exact platform specs. Covers...ore listing (file: r0/app-store-screenshots/SKILL.md) [hash=3f178aa58b5c4f8e]
|
||||
- assistant-ui: Overview and router for assistant-ui, the React library for building AI chat interfaces ...d by those siblings. (file: r0/assistant-ui/SKILL.md) [hash=61291772e6f2139c]
|
||||
- find-skills: Helps users discover and install agent skills when they ask questions like "how do I do X...an installable skill. (file: r0/find-skills/SKILL.md) [hash=48b9e99d9200af8d]
|
||||
@@ -146,7 +140,7 @@ Settings: same as window 1
|
||||
## Window 3 (after request 3: input repeated)
|
||||
Settings: same as window 1
|
||||
-- request 4 (turn) --
|
||||
00:additional_tools/developer (3; hash=bf13940dee826ebd):
|
||||
00:additional_tools/developer (2; hash=439dcadc72baaea1):
|
||||
- namespace/functions; hash=028af59ad835936d
|
||||
- function/exec_command
|
||||
- function/write_stdin
|
||||
@@ -163,8 +157,6 @@ Settings: same as window 1
|
||||
- function/send_input
|
||||
- function/spawn_agent
|
||||
- function/wait_agent
|
||||
- namespace/web: Tools in the web namespace.; hash=0037b1ed8d50fab5
|
||||
- function/run
|
||||
01:message/developer:
|
||||
Retain these base instructions.
|
||||
02:message/developer[4]:
|
||||
@@ -176,9 +168,8 @@ Settings: same as window 1
|
||||
- `r0` = `<SKILLS_ROOT>`
|
||||
- `r1` = `<SKILLS_ROOT>/.system`
|
||||
### Available skills
|
||||
- openai-docs: API first-timers, Codex/Work Q&A. If the user already has an OpenAI API integration, skip...upplied text or data. (file: r1/openai-docs/SKILL.md) [hash=8ba7f79795ddc1cb]
|
||||
- skill-creator: Create or update a Codex skill with appropriately scoped instructions and any needed supporting resources. (file: r1/skill-creator/SKILL.md)
|
||||
- skill-installer: Install Codex skills into $CODEX_HOME/skills from a curated list or a GitHub repo pat...g private repos). (file: r1/skill-installer/SKILL.md) [hash=80e87da510d34d88]
|
||||
- skill-installer: Install aKode skills into $CODEX_HOME/skills from the default skills repository (the ...g private repos). (file: r1/skill-installer/SKILL.md) [hash=50f61366dff05eec]
|
||||
- app-store-screenshots: App Store and Google Play screenshot creation with exact platform specs. Covers...ore listing (file: r0/app-store-screenshots/SKILL.md) [hash=3f178aa58b5c4f8e]
|
||||
- assistant-ui: Overview and router for assistant-ui, the React library for building AI chat interfaces ...d by those siblings. (file: r0/assistant-ui/SKILL.md) [hash=61291772e6f2139c]
|
||||
- find-skills: Helps users discover and install agent skills when they ask questions like "how do I do X...an installable skill. (file: r0/find-skills/SKILL.md) [hash=48b9e99d9200af8d]
|
||||
|
||||
@@ -16,12 +16,12 @@ use tokio::time::timeout;
|
||||
async fn startup_reports_shared_and_fallback_recovery() -> Result<()> {
|
||||
for log_dir_is_configured in [false, true] {
|
||||
let home = TempDir::new()?;
|
||||
// aKode: no default provider or bundled catalog; threads need an explicit catalog.
|
||||
let mut config = app_test_support::bundled_model_catalog_config(home.path())?;
|
||||
if log_dir_is_configured {
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!("log_dir = {:?}\n", home.path().join("log")),
|
||||
)?;
|
||||
config.push_str(&format!("log_dir = {:?}\n", home.path().join("log")));
|
||||
}
|
||||
std::fs::write(home.path().join("config.toml"), config)?;
|
||||
let sqlite = core_test_support::load_default_config_for_test(&home)
|
||||
.await
|
||||
.sqlite;
|
||||
|
||||
@@ -298,6 +298,11 @@ fn create_delete_test_rollout(codex_home: &Path, minute: u8, preview: &str) -> R
|
||||
#[tokio::test]
|
||||
async fn thread_delete_handles_live_threads_before_rollout_exists() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
// aKode: no default provider or bundled catalog; threads need an explicit catalog.
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
app_test_support::bundled_model_catalog_config(codex_home.path())?,
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
|
||||
@@ -1013,7 +1013,8 @@ async fn sample_rejects_invalid_sources_and_prompts() -> Result<()> {
|
||||
}
|
||||
|
||||
#[test_case(false; "unsupported model")]
|
||||
#[test_case(true; "unsupported provider")]
|
||||
// aKode: the "unsupported provider" case was removed with the name-based `is_openai()`
|
||||
// gate on reasoning-effort updates; provider names no longer matter.
|
||||
#[tokio::test]
|
||||
async fn unsupported_effort_updates_keep_inherited_effort(
|
||||
unsupported_provider: bool,
|
||||
|
||||
@@ -79,34 +79,14 @@ async fn start_thread_with_model(
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_provider_model_fallback_applies_to_configured_model() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"model_provider = "amazon-bedrock"
|
||||
model = "gpt-5.4-mini"
|
||||
"#,
|
||||
)?;
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
|
||||
let response = mcp
|
||||
.start_thread(ThreadStartParams {
|
||||
allow_provider_model_fallback: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
|
||||
assert_eq!(response.model, "openai.gpt-6.1-sol");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_warns_for_exec_policy_parse_failure_after_initialize() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
// aKode: no default provider or bundled catalog; threads need an explicit catalog.
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
app_test_support::bundled_model_catalog_config(codex_home.path())?,
|
||||
)?;
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.build_initialized()
|
||||
@@ -175,6 +155,11 @@ async fn thread_start_warns_for_exec_policy_parse_failure_after_initialize() ->
|
||||
#[tokio::test]
|
||||
async fn thread_start_does_not_repeat_initialize_exec_policy_warning() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
// aKode: no default provider or bundled catalog; threads need an explicit catalog.
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
app_test_support::bundled_model_catalog_config(codex_home.path())?,
|
||||
)?;
|
||||
let rules_dir = codex_home.path().join("rules");
|
||||
std::fs::create_dir_all(&rules_dir)?;
|
||||
std::fs::write(rules_dir.join("broken.rules"), "prefix_rule(")?;
|
||||
@@ -210,103 +195,6 @@ async fn thread_start_does_not_repeat_initialize_exec_policy_warning() -> Result
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_provider_model_fallback_uses_bedrock_static_catalog() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"model_provider = "amazon-bedrock"
|
||||
"#,
|
||||
)?;
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
|
||||
let unsupported_with_fallback = start_thread_with_model(
|
||||
&mut mcp,
|
||||
"gpt-5.4-mini",
|
||||
/*allow_provider_model_fallback*/ true,
|
||||
)
|
||||
.await?;
|
||||
for model in [
|
||||
"openai.gpt-6.1-sol",
|
||||
"openai.gpt-6.1-terra",
|
||||
"openai.gpt-6-sol",
|
||||
"openai.gpt-6-luna",
|
||||
"openai.gpt-5.6-sol",
|
||||
] {
|
||||
let response =
|
||||
start_thread_with_model(&mut mcp, model, /*allow_provider_model_fallback*/ true)
|
||||
.await?;
|
||||
assert_eq!(response.model, model);
|
||||
}
|
||||
let supported_with_fallback = start_thread_with_model(
|
||||
&mut mcp,
|
||||
"openai.gpt-5.5",
|
||||
/*allow_provider_model_fallback*/ true,
|
||||
)
|
||||
.await?;
|
||||
let unsupported_without_fallback = start_thread_with_model(
|
||||
&mut mcp,
|
||||
"gpt-5.4-mini",
|
||||
/*allow_provider_model_fallback*/ false,
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert_eq!(
|
||||
vec![
|
||||
unsupported_with_fallback.model,
|
||||
supported_with_fallback.model,
|
||||
unsupported_without_fallback.model,
|
||||
],
|
||||
vec!["openai.gpt-6.1-sol", "openai.gpt-5.5", "gpt-5.4-mini"]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_bedrock_runtime_prefers_global_cross_region_models() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"model_provider = "amazon-bedrock-runtime"
|
||||
"#,
|
||||
)?;
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
|
||||
for model in [
|
||||
"global.openai.gpt-6.1-sol",
|
||||
"us.openai.gpt-6.1-sol",
|
||||
"global.openai.gpt-6.1-terra",
|
||||
"us.openai.gpt-6.1-terra",
|
||||
"global.openai.gpt-6-sol",
|
||||
"us.openai.gpt-6-sol",
|
||||
"global.openai.gpt-6-luna",
|
||||
"us.openai.gpt-6-luna",
|
||||
"global.openai.gpt-5.6-sol",
|
||||
"us.openai.gpt-5.6-sol",
|
||||
] {
|
||||
let response =
|
||||
start_thread_with_model(&mut mcp, model, /*allow_provider_model_fallback*/ true)
|
||||
.await?;
|
||||
assert_eq!(response.model, model);
|
||||
}
|
||||
|
||||
let response = start_thread_with_model(
|
||||
&mut mcp,
|
||||
"openai.gpt-5.6-sol",
|
||||
/*allow_provider_model_fallback*/ true,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(response.model, "global.openai.gpt-6.1-sol");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_provider_model_fallback_ignores_dynamic_catalog() -> Result<()> {
|
||||
let server = create_mock_responses_server_repeating_assistant("Done").await;
|
||||
|
||||
@@ -473,13 +473,11 @@ async fn tool_call_metadata_stays_out_of_raw_response_item_notifications() -> Re
|
||||
.find(|item| item["type"] == "function_call_output" && item["call_id"] == "mcp-call")
|
||||
.context("follow-up tool output")?;
|
||||
assert!(serde_json::to_string(&output["output"])?.contains("Calendar result"));
|
||||
// aKode: internal metadata passthrough is stripped from model requests unless the
|
||||
// provider holds the runtime-only `include_internal_metadata` grant.
|
||||
assert_eq!(
|
||||
output["internal_chat_message_metadata_passthrough"]["executed_tool_calls"],
|
||||
json!([{"name": DIRECT_CALENDAR_LIST_EVENTS_TOOL, "arguments": arguments}]),
|
||||
);
|
||||
assert_eq!(
|
||||
output["internal_chat_message_metadata_passthrough"]["tool_calls_complete"],
|
||||
true,
|
||||
output.get("internal_chat_message_metadata_passthrough"),
|
||||
None
|
||||
);
|
||||
|
||||
let raw_output = &raw_params["item"];
|
||||
@@ -488,10 +486,10 @@ async fn tool_call_metadata_stays_out_of_raw_response_item_notifications() -> Re
|
||||
let public_metadata = raw_output["internal_chat_message_metadata_passthrough"]
|
||||
.as_object()
|
||||
.context("public passthrough metadata")?;
|
||||
assert_eq!(
|
||||
public_metadata.get("turn_id").context("public turn id")?,
|
||||
&output["internal_chat_message_metadata_passthrough"]["turn_id"],
|
||||
);
|
||||
let public_turn_id = public_metadata
|
||||
.get("turn_id")
|
||||
.context("public turn id")?
|
||||
.clone();
|
||||
for field in ["executed_tool_calls", "tool_calls_complete", "cell_id"] {
|
||||
assert!(
|
||||
public_metadata.get(field).is_none(),
|
||||
@@ -514,6 +512,14 @@ async fn tool_call_metadata_stays_out_of_raw_response_item_notifications() -> Re
|
||||
.find(|item| item["type"] == "function_call_output" && item["call_id"] == "mcp-call")
|
||||
.context("persisted MCP output")?;
|
||||
assert_eq!(captured["output"], raw_output["output"]);
|
||||
assert_eq!(
|
||||
captured["internal_chat_message_metadata_passthrough"]["turn_id"],
|
||||
public_turn_id
|
||||
);
|
||||
assert_eq!(
|
||||
captured["internal_chat_message_metadata_passthrough"]["executed_tool_calls"][0]["name"],
|
||||
json!(DIRECT_CALENDAR_LIST_EVENTS_TOOL),
|
||||
);
|
||||
// Raw MCP result metadata is never recorded, not even in the local rollout.
|
||||
assert_eq!(
|
||||
captured["internal_chat_message_metadata_passthrough"]["executed_tool_calls"][0]
|
||||
@@ -644,7 +650,10 @@ async fn turn_start_steers_active_turn_and_returns_active_turn_id() -> Result<()
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
format!(
|
||||
"model = \"gpt-5.5\"\napproval_policy = \"never\"\nopenai_base_url = \"{}/v1\"\ncli_auth_credentials_store = \"file\"\n[features]\nenable_request_compression = false\n",
|
||||
// aKode: `openai_base_url` no longer configures a built-in provider; declare an
|
||||
// equivalent `openai` provider explicitly, with an explicit model catalog.
|
||||
"{}model = \"gpt-5.5\"\napproval_policy = \"never\"\nmodel_provider = \"openai\"\ncli_auth_credentials_store = \"file\"\n[features]\nenable_request_compression = false\n[model_providers.openai]\nname = \"OpenAI\"\nbase_url = \"{}/v1\"\nwire_api = \"responses\"\nrequires_openai_auth = true\nsupports_websockets = false\nmerge_system_messages = false\n",
|
||||
app_test_support::bundled_model_catalog_config(codex_home.path())?,
|
||||
server.uri()
|
||||
),
|
||||
)?;
|
||||
@@ -1085,7 +1094,12 @@ async fn turn_start_emits_thread_scoped_warning_notification_for_trimmed_skills(
|
||||
.expect("model slug should be present")
|
||||
.to_string();
|
||||
entry["context_window"] = serde_json::Value::from(100);
|
||||
std::fs::write(&cache_path, serde_json::to_string_pretty(&cache)?)?;
|
||||
// aKode: cached models are served through the explicit test catalog.
|
||||
write_models_cache_with_models(
|
||||
codex_home.path(),
|
||||
serde_json::from_value(cache["models"].clone())?,
|
||||
)
|
||||
.await?;
|
||||
let config_path = codex_home.path().join("config.toml");
|
||||
let config = std::fs::read_to_string(&config_path)?;
|
||||
std::fs::write(
|
||||
@@ -1125,9 +1139,10 @@ async fn turn_start_emits_thread_scoped_warning_notification_for_trimmed_skills(
|
||||
let warning: WarningNotification =
|
||||
timeout(DEFAULT_READ_TIMEOUT, mcp.read_notification("warning")).await??;
|
||||
assert_eq!(warning.thread_id.as_deref(), Some(thread.id.as_str()));
|
||||
// aKode: the bundled `openai-docs` system skill was removed, so one fewer skill is trimmed.
|
||||
assert_eq!(
|
||||
warning.message,
|
||||
"Exceeded skills context budget. All skill descriptions were removed and 5 additional skills were not included in the model-visible skills list."
|
||||
"Exceeded skills context budget. All skill descriptions were removed and 4 additional skills were not included in the model-visible skills list."
|
||||
);
|
||||
|
||||
timeout(
|
||||
@@ -3270,13 +3285,14 @@ model = "mock-model"
|
||||
approval_policy = "never"
|
||||
default_permissions = "dev"
|
||||
model_provider = "mock_provider"
|
||||
|
||||
{catalog}
|
||||
[model_providers.mock_provider]
|
||||
name = "Mock provider for test"
|
||||
base_url = "{server_uri}/v1"
|
||||
wire_api = "responses"
|
||||
request_max_retries = 0
|
||||
stream_max_retries = 0
|
||||
merge_system_messages = false
|
||||
|
||||
# This test only exercises writable workspace roots; the Windows restricted-token
|
||||
# sandbox cannot enforce a filesystem policy without root read access.
|
||||
@@ -3285,7 +3301,9 @@ stream_max_retries = 0
|
||||
|
||||
[permissions.dev.filesystem.":workspace_roots"]
|
||||
"." = "write"
|
||||
"#
|
||||
"#,
|
||||
// aKode: explicit catalog (no bundled default) and upstream message layout.
|
||||
catalog = app_test_support::bundled_model_catalog_config(&codex_home)?
|
||||
),
|
||||
)?;
|
||||
|
||||
@@ -3868,7 +3886,12 @@ async fn turn_start_streams_apply_patch_change_updates_v2() -> Result<()> {
|
||||
model["slug"] = serde_json::Value::from("mock-model");
|
||||
model["display_name"] = serde_json::Value::from("mock-model");
|
||||
model["apply_patch_tool_type"] = serde_json::Value::from("freeform");
|
||||
std::fs::write(&cache_path, serde_json::to_string_pretty(&cache)?)?;
|
||||
// aKode: cached models are served through the explicit test catalog.
|
||||
write_models_cache_with_models(
|
||||
&codex_home,
|
||||
serde_json::from_value(cache["models"].clone())?,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_codex_home(&codex_home)
|
||||
|
||||
@@ -300,7 +300,9 @@ async fn assert_standalone_web_search_round_trips_output(
|
||||
.with_model_provider("openai-custom")
|
||||
.with_provider_name("OpenAI")
|
||||
.with_provider_base_url(&format!("{}/api/codex", server.uri()))
|
||||
.with_provider_config("requires_openai_auth = true"),
|
||||
.with_provider_config("requires_openai_auth = true")
|
||||
// aKode: standalone search is provider opt-in; the name "OpenAI" no longer implies it.
|
||||
.with_provider_config("supports_standalone_web_search = true"),
|
||||
WebSearchProvider::CustomResponses => config
|
||||
.with_model_provider("custom-responses")
|
||||
.with_provider_name("Custom Responses")
|
||||
|
||||
Reference in New Issue
Block a user