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:
andrea.difonzo
2026-11-11 02:11:45 +01:00
parent 9e33707b8e
commit e39aae0085
545 changed files with 9742 additions and 24503 deletions

View File

@@ -57,6 +57,7 @@ codex-git-attribution = { workspace = true }
codex-git-utils = { workspace = true }
codex-install-context = { workspace = true }
codex-login = { workspace = true }
codex-model-provider-info = { workspace = true }
codex-memories-write = { workspace = true }
codex-mcp = { workspace = true }
codex-model-provider = { workspace = true }

View File

@@ -1124,8 +1124,7 @@ enabled = true
}
#[tokio::test]
async fn debug_sandbox_honors_explicit_managed_permission_profile() -> anyhow::Result<()>
{
async fn debug_sandbox_honors_explicit_managed_permission_profile() -> anyhow::Result<()> {
let codex_home = TempDir::new()?;
let config = load_debug_sandbox_config_with_codex_home(
@@ -1159,17 +1158,14 @@ enabled = true
);
assert_eq!(
config.config_layer_stack.requirements_toml(),
&toml::from_str::<ConfigRequirementsToml>(
MANAGED_PERMISSION_PROFILE_REQUIREMENTS,
)?,
&toml::from_str::<ConfigRequirementsToml>(MANAGED_PERMISSION_PROFILE_REQUIREMENTS,)?,
);
Ok(())
}
#[tokio::test]
async fn debug_sandbox_ignores_managed_permission_profiles_by_default()
-> anyhow::Result<()> {
async fn debug_sandbox_ignores_managed_permission_profiles_by_default() -> anyhow::Result<()> {
let codex_home = TempDir::new()?;
let config = load_debug_sandbox_config_with_codex_home(

View File

@@ -1116,8 +1116,7 @@ fn codex_path_entries() -> Vec<String> {
fn config_check(config: &Config) -> DoctorCheck {
let mut details = Vec::new();
details
.push("configuration scope: invocation config, including managed policy".to_string());
details.push("configuration scope: invocation config, including managed policy".to_string());
details.push("active thread overrides: not inspected".to_string());
details.push(format!("CODEX_HOME: {}", config.codex_home.display()));
details.push(format!("cwd: {}", config.cwd.display()));
@@ -1240,6 +1239,9 @@ fn auth_check(config: &Config) -> DoctorCheck {
env_auth_vars.join(", ")
));
}
if let Some(check) = provider_keyring_auth_check(config, details.clone()) {
return check;
}
if let Some(check) = provider_specific_auth_check(
config.model_provider.requires_openai_auth,
config.model_provider.env_key.as_deref(),
@@ -1319,6 +1321,55 @@ fn auth_check(config: &Config) -> DoctorCheck {
}
}
/// Reports where an `api_key = "keyring"` provider key is stored, never the key itself.
fn provider_keyring_auth_check(config: &Config, mut details: Vec<String>) -> Option<DoctorCheck> {
if config.model_provider.api_key
!= Some(codex_model_provider_info::ProviderApiKeySource::Keyring)
{
return None;
}
let id = config.model_provider_id.as_str();
details.push(format!(
"provider API key store: {:?}",
config.provider_api_key_store_mode
));
Some(
match codex_model_provider_info::locate_provider_api_key(id) {
Ok(Some(location)) => {
details.push(format!("provider API key: stored in {location}"));
DoctorCheck::new(
"auth.credentials",
"auth",
CheckStatus::Ok,
"the active model provider's API key is stored",
)
.details(details)
}
Ok(None) => DoctorCheck::new(
"auth.credentials",
"auth",
CheckStatus::Fail,
"no API key is stored for the active model provider",
)
.details(details)
.remediation(format!(
"Run: codex login --provider {id} --with-api-key (reads the key from stdin)."
)),
Err(error) => DoctorCheck::new(
"auth.credentials",
"auth",
CheckStatus::Fail,
"the provider API key store cannot be read",
)
.details({
details.push(format!("error: {error}"));
details
})
.remediation("Unlock the system keyring or set provider_api_key_store = \"file\"."),
},
)
}
fn provider_specific_auth_check(
requires_openai_auth: bool,
provider_env_key: Option<&str>,
@@ -1327,7 +1378,7 @@ fn provider_specific_auth_check(
env_var_present: impl Fn(&str) -> bool,
) -> Option<DoctorCheck> {
details.push(format!(
"model provider requires OpenAI auth: {requires_openai_auth}"
"model provider uses the stored API key: {requires_openai_auth}"
));
if requires_openai_auth {
return None;
@@ -1367,7 +1418,7 @@ fn provider_specific_auth_check(
"auth.credentials",
"auth",
CheckStatus::Ok,
"OpenAI auth is not required for the active model provider",
"the stored API key is not used by the active model provider",
)
.details(details),
),
@@ -1378,8 +1429,6 @@ fn stored_auth_mode(auth: &codex_login::AuthDotJson) -> &'static str {
match stored_auth_mode_value(auth) {
Some(AuthMode::ApiKey) => "api_key",
Some(AuthMode::Headers) => "headers",
Some(AuthMode::BedrockApiKey) => "bedrock_api_key",
Some(AuthMode::BedrockAccessKeys) => "bedrock_access_keys",
None => "unsupported",
}
}
@@ -1389,11 +1438,7 @@ fn stored_auth_mode_value(auth: &AuthDotJson) -> Option<AuthMode> {
if let Some(mode) = auth.auth_mode {
return Some(mode);
}
if auth.bedrock_api_key.is_some() {
Some(AuthMode::BedrockApiKey)
} else if auth.bedrock_access_keys.is_some() {
Some(AuthMode::BedrockAccessKeys)
} else if auth.openai_api_key.is_some() {
if auth.openai_api_key.is_some() {
Some(AuthMode::ApiKey)
} else {
None
@@ -1426,22 +1471,6 @@ fn stored_auth_issues(
AuthMode::Headers => {
issues.push("header auth cannot be loaded from auth storage");
}
AuthMode::BedrockApiKey => {
if auth.bedrock_api_key.is_none() {
issues.push("Bedrock API key auth is missing a Bedrock API key");
}
}
AuthMode::BedrockAccessKeys => match auth.bedrock_access_keys.as_ref() {
Some(access_keys) => {
if access_keys.access_key_id.trim().is_empty() {
issues.push("Bedrock access key auth is missing an access key ID");
}
if access_keys.secret_access_key.trim().is_empty() {
issues.push("Bedrock access key auth is missing a secret access key");
}
}
None => issues.push("Bedrock access key auth is missing AWS access keys"),
},
}
issues
}
@@ -2493,8 +2522,6 @@ fn auth_mode_name(auth: &CodexAuth) -> &'static str {
match auth.auth_mode() {
AuthMode::ApiKey => "api_key",
AuthMode::Headers => "headers",
AuthMode::BedrockApiKey => "bedrock_api_key",
AuthMode::BedrockAccessKeys => "bedrock_access_keys",
}
}
@@ -2602,7 +2629,6 @@ fn provider_reachability_plan(config: &Config) -> ReachabilityPlan {
&config.model_provider.name,
config.model_provider.base_url.as_deref(),
query_params.as_ref(),
config.model_provider.is_amazon_bedrock(),
);
plan.http_client_factory = config.http_client_factory();
plan
@@ -2616,7 +2642,6 @@ fn default_reachability_plan() -> ReachabilityPlan {
"unknown",
/*provider_base_url*/ None,
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
)
}
@@ -2638,9 +2663,7 @@ fn provider_auth_reachability_mode_from_auth(
return ProviderAuthReachabilityMode::ApiKey;
}
match stored_auth.and_then(stored_auth_mode_value) {
Some(AuthMode::ApiKey | AuthMode::BedrockApiKey | AuthMode::BedrockAccessKeys) => {
ProviderAuthReachabilityMode::ApiKey
}
Some(AuthMode::ApiKey) => ProviderAuthReachabilityMode::ApiKey,
Some(AuthMode::Headers) | None => ProviderAuthReachabilityMode::NotRequired,
}
}
@@ -2651,7 +2674,6 @@ fn provider_reachability_plan_from_parts(
provider_name: &str,
provider_base_url: Option<&str>,
provider_query_params: Option<&HashMap<String, String>>,
is_amazon_bedrock: bool,
) -> ReachabilityPlan {
// aKode: only an explicitly configured base URL outside OpenAI/ChatGPT is probed. The
// implicit chatgpt.com and api.openai.com endpoints are never contacted.
@@ -2661,7 +2683,7 @@ fn provider_reachability_plan_from_parts(
label: format!("{provider_id} API"),
url: provider_url_for_path(base_url, "responses", provider_query_params),
required: true,
route_probe_url: should_probe_models_route(provider_name, base_url, is_amazon_bedrock)
route_probe_url: should_probe_models_route(provider_name, base_url)
.then(|| provider_url_for_path(base_url, "models", provider_query_params)),
})
.into_iter()
@@ -2673,8 +2695,8 @@ fn provider_reachability_plan_from_parts(
}
}
fn should_probe_models_route(provider_name: &str, base_url: &str, is_amazon_bedrock: bool) -> bool {
!is_amazon_bedrock && !is_azure_responses_provider(provider_name, Some(base_url))
fn should_probe_models_route(provider_name: &str, base_url: &str) -> bool {
!is_azure_responses_provider(provider_name, Some(base_url))
}
fn provider_url_for_path(
@@ -3656,7 +3678,7 @@ mod tests {
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(
check.summary,
"OpenAI auth is not required for the active model provider"
"the stored API key is not used by the active model provider"
);
}
@@ -3687,8 +3709,6 @@ mod tests {
let auth = AuthDotJson {
auth_mode: Some(AuthMode::ApiKey),
openai_api_key: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
assert_eq!(
@@ -3721,8 +3741,6 @@ mod tests {
let api_key_auth = AuthDotJson {
auth_mode: Some(AuthMode::ApiKey),
openai_api_key: Some("sk-test".to_string()),
bedrock_api_key: None,
bedrock_access_keys: None,
};
assert_eq!(
@@ -3792,7 +3810,6 @@ mod tests {
"azure",
Some("https://example.openai.azure.com/openai/v1"),
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
),
ReachabilityPlan {
description: "provider auth".to_string(),
@@ -3822,7 +3839,6 @@ mod tests {
"Custom",
Some("https://example.com/openai/v1/"),
Some(&query_params),
/*is_amazon_bedrock*/ false,
),
ReachabilityPlan {
description: description.to_string(),
@@ -3844,20 +3860,6 @@ mod tests {
}
}
#[test]
fn provider_reachability_skips_route_probe_for_bedrock() {
let plan = provider_reachability_plan_from_parts(
ProviderAuthReachabilityMode::NotRequired,
"amazon-bedrock",
"Amazon Bedrock",
Some("https://bedrock-runtime.us-east-1.amazonaws.com/openai/v1"),
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ true,
);
assert_eq!(plan.endpoints[0].route_probe_url, None);
}
#[test]
fn provider_reachability_never_infers_openai_endpoints() {
let plan = provider_reachability_plan_from_parts(
@@ -3866,7 +3868,6 @@ mod tests {
"OpenAI",
/*provider_base_url*/ None,
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
);
assert_eq!(plan.endpoints, Vec::new());
@@ -3880,7 +3881,6 @@ mod tests {
"OpenAI",
Some(base_url),
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
);
assert_eq!(plan.endpoints, Vec::new(), "{base_url}");
}
@@ -3929,7 +3929,6 @@ mod tests {
"OpenAI",
Some(&format!("http://{addr}/xxxx")),
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
);
let check = provider_reachability_check(plan).await;
@@ -3969,7 +3968,6 @@ mod tests {
"OpenAI",
Some(&format!("http://{addr}/v1")),
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
);
let check = provider_reachability_check(plan).await;

View File

@@ -85,8 +85,7 @@ pub(super) fn check(config: Option<&Config>) -> DoctorCheck {
{
let request_url = config
.and_then(|config| config.model_provider.base_url.as_deref())
.or_else(|| config.map(|config| config.chatgpt_base_url.as_str()))
.unwrap_or("https://chatgpt.com/backend-api/");
.unwrap_or("http://localhost/");
let configuration = match macos_system_proxy_configuration(request_url) {
MacosSystemProxyConfiguration::Automatic => "automatic (PAC)",
MacosSystemProxyConfiguration::Manual => "manual",

View File

@@ -22,7 +22,6 @@ async fn provider_reachability_rejects_proxy_authentication_challenges() {
"Local",
Some(&format!("{}/v1", proxy.uri())),
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
);
let check = provider_reachability_check(plan).await;

View File

@@ -1,6 +1,6 @@
pub mod local_config;
pub(crate) mod debug_sandbox;
mod exit_status;
pub mod local_config;
pub(crate) mod login;
use clap::Args;
@@ -14,9 +14,11 @@ pub use debug_sandbox::run_command_under_landlock;
pub use debug_sandbox::run_command_under_seatbelt;
pub use debug_sandbox::run_command_under_windows_sandbox;
pub use login::read_api_key_from_stdin;
pub use login::run_login_provider_api_key;
pub use login::run_login_status;
pub use login::run_login_with_api_key;
pub use login::run_logout;
pub use login::run_logout_provider;
#[derive(Debug, Default, Args)]
pub struct SandboxStateArgs {

View File

@@ -8,8 +8,6 @@
//! support can request from users.
use codex_core::config::Config;
use codex_core::config::edit::ConfigEdit;
use codex_core::config::edit::ConfigEditsBuilder;
use codex_login::login_with_api_key;
use codex_protocol::auth::AuthMode;
use codex_protocol::config_types::ForcedLoginMethod;
@@ -186,6 +184,89 @@ fn read_stdin_secret(terminal_message: &str, reading_message: &str, empty_messag
secret
}
/// Stores the API key of one model provider (`api_key = "keyring"`) in the configured
/// provider key store (system keyring, or the private fallback file).
pub async fn run_login_provider_api_key(
cli_config_overrides: CliConfigOverrides,
provider_id: String,
api_key: String,
) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
let _login_log_guard = init_login_file_logging(&config);
tracing::info!("storing a provider API key");
match config.model_providers.get(&provider_id) {
Some(provider)
if provider.api_key
== Some(codex_model_provider_info::ProviderApiKeySource::Keyring) => {}
Some(_) => eprintln!(
"Warning: model_providers.{provider_id} does not set api_key = \"keyring\"; the stored key is used only after you add it."
),
None => eprintln!(
"Warning: model provider `{provider_id}` is not defined in config.toml yet; add [model_providers.{provider_id}] with api_key = \"keyring\"."
),
}
match codex_model_provider_info::save_provider_api_key(&provider_id, &api_key) {
Ok(location) => {
eprintln!(
"API key for `{provider_id}` saved in {location}. {API_KEY_AUTHENTICATION_NOTICE}"
);
std::process::exit(0);
}
Err(error) => {
eprintln!("Error saving the API key: {error}");
std::process::exit(1);
}
}
}
/// Removes the stored API key of one model provider.
pub async fn run_logout_provider(
cli_config_overrides: CliConfigOverrides,
provider_id: String,
) -> ! {
let _config = load_config_or_exit(cli_config_overrides).await;
match codex_model_provider_info::delete_provider_api_key(&provider_id) {
Ok(true) => eprintln!("Removed the stored API key for `{provider_id}`"),
Ok(false) => eprintln!("No API key is stored for `{provider_id}`"),
Err(error) => {
eprintln!("Error removing the API key: {error}");
std::process::exit(1);
}
}
std::process::exit(0);
}
/// Prints where each `api_key = "keyring"` provider key is stored (never the key itself).
/// Returns whether any provider key is available.
fn print_provider_key_status(config: &Config) -> bool {
let mut any = false;
let mut ids = config.model_providers.keys().collect::<Vec<_>>();
ids.sort();
for id in ids {
let provider = &config.model_providers[id];
if provider.api_key == Some(codex_model_provider_info::ProviderApiKeySource::Keyring) {
match codex_model_provider_info::locate_provider_api_key(id) {
Ok(Some(location)) => {
any = true;
eprintln!("Provider `{id}`: API key stored in {location}");
}
Ok(None) => eprintln!(
"Provider `{id}`: no API key stored (codex login --provider {id} --with-api-key)"
),
Err(error) => eprintln!("Provider `{id}`: cannot read the key store: {error}"),
}
} else if let Some(env_key) = &provider.env_key {
let present = std::env::var(env_key).is_ok_and(|value| !value.trim().is_empty());
any |= present;
eprintln!(
"Provider `{id}`: API key from ${env_key} ({})",
if present { "set" } else { "not set" }
);
}
}
any
}
/// Login using the OAuth device code flow.
pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
@@ -199,6 +280,7 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
AuthMode::ApiKey => match auth.get_token() {
Ok(api_key) => {
eprintln!("API key configured - {}", safe_format_key(&api_key));
print_provider_key_status(&config);
eprintln!("{API_KEY_AUTHENTICATION_NOTICE}");
std::process::exit(0);
}
@@ -210,16 +292,11 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
AuthMode::Headers => {
unreachable!("header auth cannot be loaded from auth storage")
}
AuthMode::BedrockApiKey => {
eprintln!("Logged in using Amazon Bedrock API key");
std::process::exit(0);
}
AuthMode::BedrockAccessKeys => {
eprintln!("Logged in using Amazon Bedrock AWS access keys");
std::process::exit(0);
}
},
Ok(None) => {
if print_provider_key_status(&config) {
std::process::exit(0);
}
eprintln!("Not logged in");
std::process::exit(1);
}
@@ -244,25 +321,7 @@ pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! {
}
};
let cleared_bedrock_config =
if let Some(paths) = ConfigEditsBuilder::bedrock_provider_config_paths_to_clear(&config) {
let edits = paths
.into_iter()
.map(|segments| ConfigEdit::ClearPath { segments });
if let Err(err) = ConfigEditsBuilder::for_config(&config)
.with_edits(edits)
.apply()
.await
{
eprintln!("Error clearing Amazon Bedrock configuration after logout: {err}");
std::process::exit(1);
}
true
} else {
false
};
if logged_out || cleared_bedrock_config {
if logged_out {
eprintln!("Successfully logged out");
} else {
eprintln!("Not logged in");

View File

@@ -9,9 +9,11 @@ use codex_arg0::Arg0DispatchPaths;
use codex_arg0::arg0_dispatch_or_else;
use codex_cli::local_config;
use codex_cli::read_api_key_from_stdin;
use codex_cli::run_login_provider_api_key;
use codex_cli::run_login_status;
use codex_cli::run_login_with_api_key;
use codex_cli::run_logout;
use codex_cli::run_logout_provider;
use codex_exec::Cli as ExecCli;
use codex_exec::Command as ExecCommand;
use codex_exec::ReviewArgs;
@@ -488,10 +490,15 @@ struct LoginCommand {
#[arg(
long = "with-api-key",
help = "Read the API key from stdin (e.g. `printenv OPENAI_API_KEY | codex login --with-api-key`)"
help = "Read the API key from stdin (e.g. `printenv MY_KEY | codex login --with-api-key`)"
)]
with_api_key: bool,
/// Store the key for this model provider (`[model_providers.<id>] api_key = "keyring"`)
/// instead of the shared stored key.
#[arg(long = "provider", value_name = "PROVIDER_ID")]
provider: Option<String>,
#[arg(
long = "api-key",
num_args = 0..=1,
@@ -516,6 +523,10 @@ enum LoginSubcommand {
struct LogoutCommand {
#[clap(skip)]
config_overrides: CliConfigOverrides,
/// Remove only the stored API key of this model provider.
#[arg(long = "provider", value_name = "PROVIDER_ID")]
provider: Option<String>,
}
#[derive(Debug, Parser)]
@@ -1516,15 +1527,27 @@ async fn dispatch_cli(
None => {
if login_cli.api_key.is_some() {
eprintln!(
"The --api-key flag is no longer supported. Pipe the key instead, e.g. `printenv OPENAI_API_KEY | codex login --with-api-key`."
"The --api-key flag is no longer supported. Pipe the key instead, e.g. `printenv MY_KEY | codex login --with-api-key`."
);
std::process::exit(1);
} else if login_cli.with_api_key {
let api_key = read_api_key_from_stdin();
run_login_with_api_key(login_cli.config_overrides, api_key).await;
match login_cli.provider {
Some(provider_id) => {
run_login_provider_api_key(
login_cli.config_overrides,
provider_id,
api_key,
)
.await;
}
None => {
run_login_with_api_key(login_cli.config_overrides, api_key).await;
}
}
} else {
eprintln!(
"Only API key login is supported. Pipe the key on stdin, e.g. `printenv OPENAI_API_KEY | codex login --with-api-key`."
"Only API key login is supported. Pipe the key on stdin, e.g. `printenv MY_KEY | codex login --with-api-key`."
);
std::process::exit(1);
}
@@ -1541,7 +1564,12 @@ async fn dispatch_cli(
&mut logout_cli.config_overrides,
root_config_overrides.clone(),
);
run_logout(logout_cli.config_overrides).await;
match logout_cli.provider {
Some(provider_id) => {
run_logout_provider(logout_cli.config_overrides, provider_id).await;
}
None => run_logout(logout_cli.config_overrides).await,
}
}
Some(Subcommand::Completion(completion_cli)) => {
reject_remote_mode_for_subcommand(

View File

@@ -193,7 +193,11 @@ fn packaged_daemon_launch(action: &str, initial: InitialDaemon) -> Result<()> {
assert_eq!(standalone.join("current").canonicalize()?, cli_selection);
}
if action == "bootstrap" {
assert_eq!(output["autoUpdateEnabled"], false);
// Only stable release versions follow automatic updates; local builds versioned
// 0.0.0 do not. aKode builds carry a release version (0.1.0).
let stable_build =
env!("CARGO_PKG_VERSION") != "0.0.0" && !env!("CARGO_PKG_VERSION").contains(['-', '+']);
assert_eq!(output["autoUpdateEnabled"], stable_build);
}
Ok(())
}

View File

@@ -78,11 +78,6 @@ async fn daemon_exclusion_survives_fork_picker() -> Result<()> {
daemon_startup("fork").await
}
#[tokio::test]
async fn daemon_auto_start_preserves_bedrock_onboarding() -> Result<()> {
daemon_startup("bedrock").await
}
#[tokio::test]
#[cfg(windows)]
async fn elevated_local_tui_uses_embedded_without_starting_daemon() -> Result<()> {
@@ -146,12 +141,6 @@ async fn restrictive_launcher_uses_embedded_if_daemon_cannot_start() -> Result<(
daemon_startup("restrictive-job").await
}
#[tokio::test]
#[cfg(unix)]
async fn bedrock_onboarding_discovers_credentials_on_the_running_daemon() -> Result<()> {
daemon_startup("bedrock-running").await
}
async fn daemon_startup(command: &str) -> Result<()> {
#[cfg(windows)]
let elevated = codex_app_server_daemon::is_elevated()?;
@@ -177,17 +166,24 @@ async fn daemon_startup(command: &str) -> Result<()> {
"failed to prepare CLI test executable"
);
let bedrock_onboarding = matches!(command, "bedrock" | "bedrock-running");
// aKode has no built-in catalog for providers without a catalog URL; keep the bundled one.
let catalog = home.path().join("test-models.json");
fs::write(&catalog, include_str!("../../models-manager/models.json"))?;
fs::write(
home.path().join("config.toml"),
format!(
"model = \"gpt-5.6-terra\"\n\
model_provider = \"mock\"\n\
model_catalog_json = {}\n\
cli_auth_credentials_store = \"file\"\n\
suppress_unstable_features_warning = true\n\
windows.sandbox = \"unelevated\"\n\
tui.disable_paste_burst = true\n\
{}\n\
notice.model_migrations.\"gpt-5.6-terra\" = \"gpt-6-sol\"\n\
[model_providers.mock]\nname = \"mock\"\nbase_url = \"http://127.0.0.1:9/v1\"\nrequires_openai_auth = true\n\
[projects.{}]\ntrust_level = \"{}\"\n",
serde_json::to_string(&catalog.display().to_string())?,
if command == "discovered" {
"tui.status_line=[\"model\",\"thread-id\",\"thread-name\"]\nfeatures.daemon_auto_start=false"
} else if bedrock_onboarding {
@@ -380,7 +376,7 @@ async fn daemon_startup(command: &str) -> Result<()> {
"session_id": thread_id, "id": thread_id,
"timestamp": "2025-01-05T12:00:00Z", "cwd": workspace_path,
"originator": "codex", "cli_version": "0.0.0",
"source": "cli", "model_provider": "openai"
"source": "cli", "model_provider": "mock"
}
});
let message = serde_json::json!({

View File

@@ -25,7 +25,7 @@ fn debug_models_bundled_prints_json() -> Result<()> {
}
#[test]
fn debug_models_default_prints_json_without_auth() -> Result<()> {
fn debug_models_default_prints_empty_json_without_provider() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["debug", "models"]).output()?;
@@ -34,7 +34,8 @@ fn debug_models_default_prints_json_without_auth() -> Result<()> {
let stdout = String::from_utf8(output.stdout)?;
let value: serde_json::Value = serde_json::from_str(&stdout)?;
assert!(value["models"].is_array());
assert!(!value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
// aKode has no default provider and no built-in catalog: nothing to list, no network.
assert!(value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
Ok(())
}

View File

@@ -121,7 +121,9 @@ async fn network_only_reports_recoverable_config_warnings_and_effective_config()
let config = std::fs::read_to_string(&config_path)?;
std::fs::write(
config_path,
format!("{config}\n[otel.span_attributes]\n\"\" = \"missing-key\"\n"),
// OTEL exporters were removed (otel settings are ignored without warnings); use another
// recoverable, warning-only setting.
format!("{config}\n[features.guardianv2]\nasync_classifier_mode = \"conversation\"\n"),
)?;
let output = local_command(&home)?
.args(["doctor", "--network-only", "--json"])
@@ -137,8 +139,8 @@ async fn network_only_reports_recoverable_config_warnings_and_effective_config()
let startup_warning = std::iter::once(warnings)
.chain(warnings.as_array().into_iter().flatten())
.filter_map(Value::as_str)
.find(|warning| warning.starts_with("Ignoring invalid `otel.span_attributes` config"))
.context("missing recoverable OTEL config warning")?;
.find(|warning| warning.starts_with("`[features.guardianv2].async_classifier_mode`"))
.context("missing recoverable config warning")?;
let check_statuses = report["checks"]
.as_object()
.unwrap()
@@ -170,7 +172,7 @@ async fn network_only_reports_recoverable_config_warnings_and_effective_config()
"scope": "invocation config, including managed policy",
"provider": "local",
"startupWarnings": baseline_warning_count + 1,
"startupWarning": "Ignoring invalid `otel.span_attributes` config: configured span attribute key must not be empty",
"startupWarning": "`[features.guardianv2].async_classifier_mode` is deprecated and ignored. Async classification always uses conversations; remove this setting from config.toml or profile configuration files.",
},
})
);

View File

@@ -371,8 +371,10 @@ fn doctor_reports_only_safe_config_error_metadata() -> Result<()> {
"model_provider = \"doctor-test-credential\"",
),
),
// A type error in a known key reports its location (file/line/column) but never
// the offending value.
(
"doctor_config_invalid_data",
"doctor_config_invalid_type",
user_config_file.clone(),
original.replace(
"wire_api = \"responses\"",

View File

@@ -47,7 +47,7 @@ fn mcp_list_reports_invalid_keybinding_reason() -> Result<()> {
.get_output()
.stderr
.clone();
let output = String::from_utf8(output)?;
let output = normalize_config_location(&String::from_utf8(output)?);
insta::allow_duplicates! {
insta::assert_snapshot!(output);
}
@@ -304,3 +304,23 @@ fn no_daemon_rejects_queue_and_explicit_remote_targets() -> Result<()> {
}
Ok(())
}
/// Replaces `<temp home>/config.toml:<line>:<column>` with a stable placeholder.
fn normalize_config_location(output: &str) -> String {
output
.lines()
.map(|line| match line.find("/config.toml:") {
Some(index) => {
let start = line[..index].rfind(' ').map_or(0, |space| space + 1);
let rest = &line[index + "/config.toml:".len()..];
let after_location = rest.splitn(3, ':').nth(2).unwrap_or_default();
format!(
"{}[CODEX_HOME]/config.toml:<line>:<column>:{after_location}",
&line[..start]
)
}
None => line.to_string(),
})
.collect::<Vec<_>>()
.join("\n")
}

View File

@@ -1,9 +1,6 @@
use std::path::Path;
use anyhow::Result;
use codex_config::types::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::login_with_bedrock_access_keys;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::Value;
@@ -169,79 +166,68 @@ fn legacy_chatgpt_auth_is_reported_as_not_logged_in_and_logout_removes_it() -> R
}
#[test]
fn logout_clears_only_the_selected_bedrock_provider() -> Result<()> {
for (model_provider_id, managed_bedrock_auth, model) in [
("amazon-bedrock", true, "openai.gpt-5.6-sol"),
("amazon-bedrock-runtime", true, "global.openai.gpt-5.6-sol"),
("openai", true, "gpt-5.6-sol"),
("amazon-bedrock", false, "gpt-5.6-sol"),
("amazon-bedrock-runtime", false, "us.openai.gpt-5.6-sol"),
("openai", false, "gpt-5.6-sol"),
] {
let codex_home = TempDir::new()?;
let config_path = codex_home.path().join("config.toml");
std::fs::write(
&config_path,
format!(
"cli_auth_credentials_store = \"file\"\n\
model_provider = \"{model_provider_id}\"\n\
model = \"{model}\"\n\
model_reasoning_effort = \"high\"\n\
[model_providers.amazon-bedrock]\n\
base_url = \"https://mantle.example.com/v1\"\n\
[model_providers.amazon-bedrock.aws]\n\
profile = \"mantle-profile\"\n\
region = \"us-west-2\"\n\
auth_refresh = {{ command = \"aws\", args = [\"sso\", \"login\"] }}\n\
[model_providers.amazon-bedrock-runtime]\n\
base_url = \"https://runtime.example.com/v1\"\n\
[model_providers.amazon-bedrock-runtime.aws]\n\
profile = \"runtime-profile\"\n\
region = \"us-east-1\"\n\
auth_refresh = {{ command = \"aws\", args = [\"login\"] }}\n"
),
)?;
if managed_bedrock_auth {
login_with_bedrock_access_keys(
codex_home.path(),
"managed-access-key-id",
"managed-secret-access-key",
Some("managed-session-token"),
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?;
}
let mut expected_config: toml::Value =
toml::from_str(&std::fs::read_to_string(&config_path)?)?;
if model_provider_id != "openai" {
let expected_root = expected_config
.as_table_mut()
.expect("config should be a table");
expected_root.remove("model_provider");
expected_root.remove("model");
expected_root["model_providers"][model_provider_id]
.as_table_mut()
.expect("selected Bedrock provider should be a table")
.remove("aws");
}
let expected_message = if managed_bedrock_auth || model_provider_id != "openai" {
"Successfully logged out"
} else {
"Not logged in"
};
fn provider_api_key_login_uses_private_file_store_and_never_prints_the_key() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
"provider_api_key_store = \"file\"\n\
model_provider = \"imeai\"\n\
[model_providers.imeai]\n\
name = \"imeAI\"\n\
base_url = \"http://127.0.0.1:9/v1\"\n\
api_key = \"keyring\"\n",
)?;
let secret = "sk-provider-secret-0123456789";
codex_command(codex_home.path())?
.env("AWS_ACCESS_KEY_ID", "environment-access-key-id")
.env("AWS_SECRET_ACCESS_KEY", "environment-secret-access-key")
.args(["logout"])
.assert()
.success()
.stderr(contains(expected_message));
let login = codex_command(codex_home.path())?
.args(["login", "--provider", "imeai", "--with-api-key"])
.write_stdin(format!("{secret}\n"))
.assert()
.success();
let stderr = String::from_utf8_lossy(&login.get_output().stderr).to_string();
assert!(
stderr.contains("API key for `imeai` saved in file"),
"{stderr}"
);
assert!(!stderr.contains(secret), "{stderr}");
assert!(!codex_home.path().join("auth.json").exists());
let actual_config: toml::Value = toml::from_str(&std::fs::read_to_string(&config_path)?)?;
assert_eq!(actual_config, expected_config);
let path = codex_home.path().join("provider_api_keys.json");
let stored: Value = serde_json::from_str(&std::fs::read_to_string(&path)?)?;
assert_eq!(stored, json!({ "imeai": secret }));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&path)?.permissions().mode() & 0o777,
0o600
);
}
// The shared stored key is untouched.
assert!(!codex_home.path().join("auth.json").exists());
let status = codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.success();
let stderr = String::from_utf8_lossy(&status.get_output().stderr).to_string();
assert!(
stderr.contains("Provider `imeai`: API key stored in file"),
"{stderr}"
);
assert!(!stderr.contains(secret), "{stderr}");
codex_command(codex_home.path())?
.args(["logout", "--provider", "imeai"])
.assert()
.success()
.stderr(contains("Removed the stored API key for `imeai`"));
assert!(!path.exists());
codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.failure()
.stderr(contains(
"Provider `imeai`: no API key stored (codex login --provider imeai --with-api-key)",
));
Ok(())
}

View File

@@ -1,6 +1,5 @@
---
source: cli/tests/doctor_path_safety.rs
assertion_line: 412
expression: "serde_json::to_string_pretty(&check)?"
---
{

View File

@@ -2,9 +2,11 @@
source: cli/tests/features.rs
expression: output
---
Error: failed to load bootstrap configuration
Error: failed to load configuration
Caused by:
unknown key `backslash` in keybinding `backslash`. Use a printable character (for example `a`), function keys (`f1`-`f24`), or one of: enter, tab, backspace, esc, delete, arrows, home/end, page-up/page-down, space, minus.
See the Codex keymap documentation for supported actions and examples.
in `tui.keymap.editor.insert_newline`
0: [CODEX_HOME]/config.toml:<line>:<column>: unknown key `backslash` in keybinding `backslash`. Use a printable character (for example `a`), function keys (`f1`-`f24`), or one of: enter, tab, backspace, esc, delete, arrows, home/end, page-up/page-down, space, minus.
See the Codex keymap documentation for supported actions and examples.
1: unknown key `backslash` in keybinding `backslash`. Use a printable character (for example `a`), function keys (`f1`-`f24`), or one of: enter, tab, backspace, esc, delete, arrows, home/end, page-up/page-down, space, minus.
See the Codex keymap documentation for supported actions and examples.
in `tui.keymap.editor.insert_newline`

View File

@@ -1,13 +0,0 @@
---
source: cli/tests/features.rs
assertion_line: 52
expression: output
---
Error: failed to load configuration
Caused by:
0: /private/var/folders/6k/c34nw11j2d75r8lqh1hzfz6w0000gn/T/.tmpq6XL7K/config.toml:2:18: unknown key `backslash` in keybinding `backslash`. Use a printable character (for example `a`), function keys (`f1`-`f24`), or one of: enter, tab, backspace, esc, delete, arrows, home/end, page-up/page-down, space, minus.
See the Codex keymap documentation for supported actions and examples.
1: unknown key `backslash` in keybinding `backslash`. Use a printable character (for example `a`), function keys (`f1`-`f24`), or one of: enter, tab, backspace, esc, delete, arrows, home/end, page-up/page-down, space, minus.
See the Codex keymap documentation for supported actions and examples.
in `tui.keymap.editor.insert_newline`

View File

@@ -312,7 +312,8 @@ trust_level = "trusted"
if auth_failure {
fs::write(
source.join(".codex/config.toml"),
"forced_login_method = \"api\"\n",
// The stored API key satisfies `api`; require a login method it cannot satisfy.
"forced_login_method = \"chatgpt\"\n",
)?;
git(
&source,
@@ -330,16 +331,6 @@ trust_level = "trusted"
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.mount(&server)
.await;
Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path(
"/source/backend-api/wham/config/bundle",
))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"config_toml": { "enterprise_managed": [{ "id": "test", "name": "test",
"contents": "developer_instructions = \"managed cloud instructions\"" }] }
})))
.mount(&server)
.await;
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let response = app_test_support::create_final_assistant_message_sse_response("done")?;
let observed_source = source.clone();
@@ -456,7 +447,7 @@ trust_level = "trusted"
let bytes = bytes.context("TUI exited before model request")?;
let text = String::from_utf8_lossy(&bytes);
output.push_str(&text);
if auth_failure && output.contains("API key login is required") && output.contains("Do not use --force.") {
if auth_failure && output.contains("API key login is not permitted") && output.contains("Do not use --force.") {
anyhow::bail!("observed required API login rejection");
}
let replies = queries.feed(&bytes);
@@ -470,7 +461,10 @@ trust_level = "trusted"
let exit =
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), spawned.exit_rx).await??;
assert_ne!(exit, 0);
assert!(output.contains("API key login is required"), "{output}");
assert!(
output.contains("API key login is not permitted"),
"{output}"
);
assert!(!home.join("auth.json").exists());
assert!(output.contains("The checkout was kept"), "{output}");
continue;
@@ -646,7 +640,7 @@ trust_level = "trusted"
);
}
assert_eq!(body["model"], "destination-model");
assert!(context.contains("managed cloud instructions"), "{context}");
// Managed cloud configuration (ChatGPT config bundles) was removed in aKode.
if previous.is_empty() {
// A legacy summary still says launcher A, but persisted turns use checkout B.
let sqlite = codex_state::SqliteConfig::new_for_testing(
@@ -659,26 +653,9 @@ trust_level = "trusted"
.execute(&db)
.await?;
db.close().await;
// B inherits trust from its primary repository; no exact trusted entry masks cloud distrust.
let home_config = home.join("config.toml");
let launcher_config = fs::read_to_string(&home_config)?;
fs::write(
&home_config,
launcher_config.replace(
"cli_auth_credentials_store = \"file\"",
"cli_auth_credentials_store = \"ephemeral\"",
),
)?;
let cache = home.join("cloud-config-bundle-cache.json");
if cache.exists() {
fs::remove_file(&cache)?;
}
let request_count = server.received_requests().await.context("requests")?.len();
Mock::given(wiremock::matchers::path("/source/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"config_toml": {"enterprise_managed": [{"id":"distrust", "name":"distrust",
"contents": format!("[projects.{}]\ntrust_level = \"untrusted\"\n", serde_json::to_string(&codex_config::loader::project_trust_key(Path::new(&checkout)))?)}]}
}))).with_priority(/*priority*/ 1).mount(&server).await;
// B inherits trust from its primary repository; an explicit distrust entry for B
// (formerly delivered by a managed cloud bundle, now a config override) still
// rejects the fork before any checkout is created.
let before = git(&source, &["worktree", "list", "--porcelain"])?;
rejected_start(
&program,
@@ -687,6 +664,13 @@ trust_level = "trusted"
"--enable".into(),
"worktrees".into(),
"--no-alt-screen".into(),
"-c".into(),
format!(
"projects={{{}={{trust_level=\"untrusted\"}}}}",
serde_json::to_string(&codex_config::loader::project_trust_key(
Path::new(&checkout)
))?
),
"fork".into(),
next_owner.clone(),
],
@@ -695,70 +679,7 @@ trust_level = "trusted"
"cannot create a checkout from an explicitly untrusted source",
)
.await?;
assert!(
server
.received_requests()
.await
.context("requests")?
.iter()
.skip(request_count)
.any(|request| request.url.path() == "/source/backend-api/wham/config/bundle")
);
assert_eq!(git(&source, &["worktree", "list", "--porcelain"])?, before);
server.reset().await;
if cache.exists() {
fs::remove_file(&cache)?;
}
let count = server.received_requests().await.context("requests")?.len();
Mock::given(wiremock::matchers::path("/source/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"config_toml": {"enterprise_managed": [{"id":"distrust-source", "name":"distrust-source",
"contents": format!("[projects.{}]\ntrust_level = \"untrusted\"\n", serde_json::to_string(&codex_config::loader::project_trust_key(&source.join(".codex")))?)}]}
}))).mount(&server).await;
let output = rejected_start(
&program,
&[
"--worktree".into(),
"--enable".into(),
"worktrees".into(),
"--no-alt-screen".into(),
"--cd".into(),
source.join(".codex").display().to_string(),
],
&launcher,
&env,
"cannot create a checkout from an explicitly untrusted source",
)
.await?;
let requests = server.received_requests().await.context("requests")?;
let paths = requests
.iter()
.skip(count)
.map(|r| r.url.path())
.collect::<Vec<_>>();
assert!(paths.contains(&"/source/backend-api/wham/config/bundle"));
assert!(!paths.contains(&"/v1/responses"));
let after = git(&source, &["worktree", "list", "--porcelain"])?;
let retained = after
.lines()
.filter_map(|line| line.strip_prefix("worktree "))
.find(|path| {
!before
.lines()
.any(|line| line.strip_prefix("worktree ") == Some(*path))
})
.context("retained untrusted checkout")?;
assert!(output.contains("The checkout was kept"), "{output}");
let metadata = git(
Path::new(retained),
&["rev-parse", "--git-path", "codex-thread.json"],
)?;
assert!(!Path::new(retained).join(metadata).exists());
previous.push(retained.to_owned());
fs::write(&home_config, launcher_config)?;
if cache.exists() {
fs::remove_file(&cache)?;
}
}
previous.push(checkout);
owner = Some(next_owner);