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

@@ -1,48 +0,0 @@
use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_ID;
use codex_model_provider_info::ModelProviderAwsAuthInfo;
use pretty_assertions::assert_eq;
use super::ConfigToml;
#[test]
fn runtime_provider_accepts_aws_profile_and_region_overrides() {
let config = toml::from_str::<ConfigToml>(
r#"
[model_providers.amazon-bedrock-runtime.aws]
profile = "runtime-profile"
region = "us-west-2"
"#,
)
.expect("Bedrock Runtime AWS overrides should deserialize");
assert_eq!(
config
.model_providers
.get(AMAZON_BEDROCK_RUNTIME_PROVIDER_ID)
.and_then(|provider| provider.aws.clone()),
Some(ModelProviderAwsAuthInfo {
profile: Some("runtime-profile".to_string()),
region: Some("us-west-2".to_string()),
credential_export: None,
auth_refresh: None,
})
);
}
#[test]
fn custom_provider_still_rejects_aws_auth() {
let error = toml::from_str::<ConfigToml>(
r#"
[model_providers.custom]
name = "Custom"
[model_providers.custom.aws]
region = "us-west-2"
"#,
)
.expect_err("custom providers must not accept AWS auth");
assert!(error.to_string().contains(
"provider aws is only supported for `amazon-bedrock` or `amazon-bedrock-runtime`"
));
}

View File

@@ -31,15 +31,11 @@ use crate::types::Tui;
use crate::types::UriBasedFileOpener;
use crate::types::WindowsToml;
use codex_features::FeaturesToml;
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::LMSTUDIO_OSS_PROVIDER_ID;
use codex_model_provider_info::ModelProviderInfo;
use codex_model_provider_info::OLLAMA_CHAT_PROVIDER_REMOVED_ERROR;
use codex_model_provider_info::OLLAMA_OSS_PROVIDER_ID;
use codex_model_provider_info::OPENAI_PROVIDER_ID;
use codex_protocol::config_types::AutoCompactTokenLimitScope;
use codex_protocol::config_types::ForcedLoginMethod;
use codex_protocol::config_types::Personality;
@@ -47,7 +43,7 @@ use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::config_types::SandboxMode;
use codex_protocol::config_types::TrustLevel;
use codex_protocol::config_types::Verbosity;
use codex_protocol::config_types::WebSearchMode;
use codex_protocol::config_types::WebSearchSetting;
use codex_protocol::config_types::WebSearchToolConfig;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::PermissionProfile;
@@ -63,14 +59,7 @@ use serde::Serialize;
use serde::de::Error as SerdeError;
use serde_json::Value as JsonValue;
const RESERVED_MODEL_PROVIDER_IDS: [&str; 6] = [
AMAZON_BEDROCK_PROVIDER_ID,
AMAZON_BEDROCK_RUNTIME_PROVIDER_ID,
GCP_PROVIDER_ID,
OPENAI_PROVIDER_ID,
OLLAMA_OSS_PROVIDER_ID,
LMSTUDIO_OSS_PROVIDER_ID,
];
const RESERVED_MODEL_PROVIDER_IDS: [&str; 2] = [OLLAMA_OSS_PROVIDER_ID, LMSTUDIO_OSS_PROVIDER_ID];
pub const DEFAULT_PROJECT_DOC_MAX_BYTES: usize = 32 * 1024;
@@ -304,6 +293,13 @@ pub struct ConfigToml {
#[serde(default)]
pub cli_auth_credentials_store: Option<AuthCredentialsStoreMode>,
/// Where per-provider API keys (`api_key = "keyring"`) are stored.
/// auto (default): the system keyring if available, otherwise
/// `CODEX_HOME/provider_api_keys.json` (owner-only permissions).
/// keyring: the system keyring only. file: the file only. ephemeral: memory only.
#[serde(default)]
pub provider_api_key_store: Option<AuthCredentialsStoreMode>,
/// Definition for MCP servers that Codex can reach out to for tool calls.
#[serde(default)]
// Uses the raw MCP input shape (custom deserialization) rather than `McpServerConfig`.
@@ -487,8 +483,9 @@ pub struct ConfigToml {
pub experimental_thread_store: Option<ThreadStoreToml>,
pub projects: Option<HashMap<String, ProjectConfig>>,
/// Controls the web search tool mode: disabled, cached, indexed, or live.
pub web_search: Option<WebSearchMode>,
/// Web search: a mode string (disabled, cached, indexed, live) or a `[web_search]`
/// table selecting a client-side backend, e.g. `backend = "searxng"`, `url = "..."`.
pub web_search: Option<WebSearchSetting>,
/// Nested tools section for feature toggles
pub tools: Option<ToolsToml>,
@@ -957,20 +954,7 @@ pub fn validate_reserved_model_provider_ids(
) -> Result<(), String> {
let mut conflicts = model_providers
.keys()
.filter(|key| {
if key.as_str() == "openai" {
let provider = &model_providers[*key];
return provider
!= &ModelProviderInfo {
model_catalog_url: provider.model_catalog_url.clone(),
..Default::default()
};
}
!matches!(
key.as_str(),
AMAZON_BEDROCK_PROVIDER_ID | AMAZON_BEDROCK_RUNTIME_PROVIDER_ID | GCP_PROVIDER_ID
) && RESERVED_MODEL_PROVIDER_IDS.contains(&key.as_str())
})
.filter(|key| RESERVED_MODEL_PROVIDER_IDS.contains(&key.as_str()))
.map(|key| format!("`{key}`"))
.collect::<Vec<_>>();
conflicts.sort_unstable();
@@ -979,7 +963,7 @@ pub fn validate_reserved_model_provider_ids(
} else {
Err(format!(
"model_providers contains reserved built-in provider IDs: {}. \
Built-in providers cannot be overridden. Rename your custom provider (for example, `openai-custom`).",
Built-in providers cannot be overridden. Rename your custom provider (for example, `ollama-custom`).",
conflicts.join(", ")
))
}
@@ -990,34 +974,11 @@ pub fn validate_model_providers(
) -> Result<(), String> {
validate_reserved_model_provider_ids(model_providers)?;
for (key, provider) in model_providers {
if matches!(
key.as_str(),
AMAZON_BEDROCK_PROVIDER_ID | AMAZON_BEDROCK_RUNTIME_PROVIDER_ID
) {
provider
.validate_bedrock_override()
.map_err(|message| format!("model_providers.{key} {message}"))?;
} else if provider.aws.is_some() {
return Err(format!(
"model_providers.{key}: provider aws is only supported for \
`{AMAZON_BEDROCK_PROVIDER_ID}` or `{AMAZON_BEDROCK_RUNTIME_PROVIDER_ID}`"
));
}
if !matches!(
key.as_str(),
AMAZON_BEDROCK_PROVIDER_ID | AMAZON_BEDROCK_RUNTIME_PROVIDER_ID | GCP_PROVIDER_ID
) && key != "openai"
&& provider.name.trim().is_empty()
{
if provider.name.trim().is_empty() {
return Err(format!(
"model_providers.{key}: provider name must not be empty"
));
}
if key == GCP_PROVIDER_ID {
provider
.validate_gcp_credential_file()
.map_err(|message| format!("model_providers.{key}: {message}"))?;
}
provider
.validate()
.map_err(|message| format!("model_providers.{key}: {message}"))?;
@@ -1036,10 +997,6 @@ where
Ok(model_providers)
}
#[cfg(test)]
#[path = "bedrock_runtime_tests.rs"]
mod bedrock_runtime_tests;
pub fn validate_oss_provider(provider: &str) -> std::io::Result<()> {
match provider {
LMSTUDIO_OSS_PROVIDER_ID | OLLAMA_OSS_PROVIDER_ID => Ok(()),
@@ -1150,62 +1107,22 @@ mod tests {
}
#[test]
fn amazon_bedrock_auth_command_must_not_be_empty() {
fn provider_auth_command_must_not_be_empty() {
let err = toml::from_str::<ConfigToml>(
r#"
[model_providers.amazon-bedrock.auth]
[model_providers.corp]
name = "Corp"
base_url = "https://llm.example.com/v1"
[model_providers.corp.auth]
command = " "
"#,
)
.expect_err("empty Amazon Bedrock auth command should be rejected");
.expect_err("empty provider auth command should be rejected");
assert!(
err.to_string().contains(
"model_providers.amazon-bedrock: provider auth.command must not be empty"
)
err.to_string()
.contains("model_providers.corp: provider auth.command must not be empty")
);
}
#[test]
fn gcp_provider_accepts_partial_endpoint_and_auth_overrides() {
let config = toml::from_str::<ConfigToml>(
r#"
[model_providers.gcp]
base_url = "https://vertex.example.com/v1"
[model_providers.gcp.auth]
command = "print-token"
"#,
)
.expect("partial GCP provider overrides should deserialize");
let provider = config
.model_providers
.get(GCP_PROVIDER_ID)
.expect("GCP overrides should be retained");
assert_eq!(
(
provider.base_url.as_deref(),
provider.auth.as_ref().map(|auth| auth.command.as_str()),
),
(Some("https://vertex.example.com/v1"), Some("print-token"))
);
}
#[test]
fn gcp_provider_rejects_relative_credential_file() {
for credential_file in ["", "adc.json", "../adc.json"] {
let error = toml::from_str::<ConfigToml>(&format!(
r#"
[model_providers.gcp]
credential_file = "{credential_file}"
"#,
))
.expect_err("GCP overrides must validate credential paths before merging defaults");
assert!(error.to_string().contains(
"model_providers.gcp: provider credential_file must be an absolute path"
));
}
}
}

View File

@@ -25,7 +25,6 @@ mod mcp_edit;
mod mcp_requirements;
mod mcp_types;
mod merge;
mod model_provider_defaults;
mod model_provider_requirements;
mod overrides;
mod path_context;
@@ -175,7 +174,6 @@ pub use merge::ShellEnvironmentPolicyFilterRepresentation;
pub use merge::is_structured_feature_path;
pub use merge::merge_toml_values;
pub use merge::shell_environment_filter_entry;
pub use model_provider_defaults::apply_default_gcp_auth;
pub use overrides::build_cli_overrides_layer;
pub use path_context::ConfigPathContext;
pub use plugin_edit::PluginConfigEdit;

View File

@@ -1,27 +0,0 @@
//! Applies runtime provider defaults using the resolved session working directory.
use codex_model_provider_info::ModelProviderInfo;
use codex_protocol::config_types::ModelProviderAuthInfo;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::num::NonZeroU64;
/// Supplies GCP command auth when no explicit auth override is configured.
pub fn apply_default_gcp_auth(provider: &mut ModelProviderInfo, cwd: &AbsolutePathBuf) {
provider.auth.get_or_insert_with(|| ModelProviderAuthInfo {
command: if cfg!(windows) {
"gcloud.cmd"
} else {
"gcloud"
}
.to_string(),
args: vec![
"auth".into(),
"application-default".into(),
"print-access-token".into(),
],
timeout_ms: NonZeroU64::new(30_000).unwrap_or(NonZeroU64::MIN),
refresh_interval_ms: 3_000_000,
// Registry construction must not depend on the process cwd, which may be deleted.
cwd: cwd.clone(),
});
}

View File

@@ -85,8 +85,8 @@ name = "Other provider"
fn required_provider_definitions_are_validated_without_local_defaults() -> anyhow::Result<()> {
for invalid in [
"[model_providers.gateway]\nbase_url = 'https://example.test'",
"[model_providers.openai]\nname = 'Reserved'",
"[model_providers.gateway]\nname = 'Gateway'\n[model_providers.gateway.aws]\nregion = 'us-east-1'",
"[model_providers.ollama]\nname = 'Reserved'",
"[model_providers.gateway]\nname = 'Gateway'\nbase_url = 'https://example.test'\napi_key = 'keyring'\nenv_key = 'GATEWAY_KEY'",
] {
let requirements = toml::from_str(invalid)?;
let local =

View File

@@ -304,7 +304,7 @@ mod 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,
@@ -317,9 +317,8 @@ mod tests {
supports_websockets: true,
supports_standalone_web_search: true,
capabilities: None,
project_id: None,
location: None,
credential_file: None,
merge_system_messages: None,
keyring_account: None,
include_internal_metadata: false,
}
}

View File

@@ -183,7 +183,7 @@ fn model_provider_from_proto(
.map(model_provider_auth_from_proto)
.transpose()?,
gateway_oauth: None,
aws: None,
api_key: None,
wire_api,
query_params: provider.query_params.map(redacted_string_map),
http_headers: provider.http_headers.map(redacted_string_map),
@@ -201,10 +201,10 @@ fn model_provider_from_proto(
cyber_access_programs: capabilities.cyber_access_programs,
..Default::default()
}),
project_id: provider.project_id,
location: provider.location,
credential_file: provider.credential_file.map(Into::into),
// Retired Google Cloud fields (project_id, location, credential_file) are ignored.
merge_system_messages: None,
include_internal_metadata: false,
keyring_account: None,
};
Ok((id, info))
}
@@ -223,9 +223,9 @@ fn model_provider_to_proto(
experimental_bearer_token,
auth,
gateway_oauth: _,
aws: _,
project_id,
location,
api_key: _,
merge_system_messages: _,
keyring_account: _,
wire_api,
query_params,
http_headers,
@@ -238,7 +238,6 @@ fn model_provider_to_proto(
supports_websockets,
supports_standalone_web_search,
include_internal_metadata: _,
credential_file,
capabilities,
} = provider;
@@ -247,7 +246,7 @@ fn model_provider_to_proto(
name,
base_url,
model_catalog_url: model_catalog_url.map(RedactedString::into_inner),
credential_file: credential_file.map(|path| path.to_string_lossy().into_owned()),
credential_file: None,
env_key,
env_key_instructions,
experimental_bearer_token: experimental_bearer_token.map(RedactedString::into_inner),
@@ -266,8 +265,8 @@ fn model_provider_to_proto(
requires_openai_auth,
supports_websockets,
supports_standalone_web_search,
project_id,
location,
project_id: None,
location: None,
}
}
@@ -464,9 +463,6 @@ mod tests {
#[test]
fn model_provider_proto_roundtrips_through_domain_type() {
let mut expected = expected_provider();
expected.project_id = Some("vertex-project".to_string());
expected.location = Some("us-central1".to_string());
expected.credential_file = Some(workspace_dir().join("adc.json").into_path_buf());
expected.auth = None;
expected.experimental_bearer_token = Some("synthetic-provider-token".into());
for capabilities in [
@@ -623,14 +619,13 @@ mod tests {
supports_websockets: true,
supports_standalone_web_search: true,
gateway_oauth: None,
aws: None,
api_key: None,
capabilities: Some(ModelProviderCapabilities {
cyber_access_programs: Some(true),
..Default::default()
}),
project_id: None,
location: None,
credential_file: None,
merge_system_messages: None,
keyring_account: None,
include_internal_metadata: false,
}
}