Files
imeai-aKode/codex-rs/app-server/tests/common/config.rs
andrea.difonzo e39aae0085 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>
2026-11-11 02:11:45 +01:00

244 lines
7.9 KiB
Rust

use codex_features::FEATURES;
use codex_features::Feature;
use std::collections::BTreeMap;
use std::path::Path;
/// Composes the standard mock Responses provider with test-specific configuration.
pub struct MockResponsesConfig {
provider_id: String,
provider_name: String,
provider_base_url: String,
model: String,
approval_policy: String,
sandbox_mode: String,
features: BTreeMap<Feature, bool>,
root_config: Vec<String>,
provider_config: Vec<String>,
extra_config: Vec<String>,
}
impl MockResponsesConfig {
pub fn new(server_uri: &str) -> Self {
Self {
provider_id: "mock_provider".to_string(),
provider_name: "Mock provider for test".to_string(),
provider_base_url: format!("{server_uri}/v1"),
model: "mock-model".to_string(),
approval_policy: "never".to_string(),
sandbox_mode: "read-only".to_string(),
features: BTreeMap::new(),
root_config: Vec::new(),
provider_config: Vec::new(),
extra_config: Vec::new(),
}
}
pub fn with_model_provider(mut self, provider_id: &str) -> Self {
self.provider_id = provider_id.to_string();
self
}
pub fn with_provider_name(mut self, provider_name: &str) -> Self {
self.provider_name = provider_name.to_string();
self
}
pub fn with_provider_base_url(mut self, provider_base_url: &str) -> Self {
self.provider_base_url = provider_base_url.to_string();
self
}
pub fn with_model(mut self, model: &str) -> Self {
self.model = model.to_string();
self
}
pub fn with_approval_policy(mut self, approval_policy: &str) -> Self {
self.approval_policy = approval_policy.to_string();
self
}
pub fn with_sandbox_mode(mut self, sandbox_mode: &str) -> Self {
self.sandbox_mode = sandbox_mode.to_string();
self
}
pub fn enable_feature(mut self, feature: Feature) -> Self {
self.features.insert(feature, true);
self
}
pub fn disable_feature(mut self, feature: Feature) -> Self {
self.features.insert(feature, false);
self
}
pub fn with_features(mut self, features: &BTreeMap<Feature, bool>) -> Self {
self.features.extend(
features
.iter()
.map(|(&feature, &enabled)| (feature, enabled)),
);
self
}
pub fn with_root_config(mut self, config: &str) -> Self {
self.root_config.push(config.to_string());
self
}
pub fn with_provider_config(mut self, config: &str) -> Self {
self.provider_config.push(config.to_string());
self
}
pub fn with_extra_config(mut self, config: &str) -> Self {
self.extra_config.push(config.to_string());
self
}
pub fn write(self, codex_home: &Path) -> std::io::Result<()> {
let Self {
provider_id,
provider_name,
provider_base_url,
model,
approval_policy,
sandbox_mode,
features,
root_config,
provider_config,
extra_config,
} = self;
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)| {
let key = FEATURES
.iter()
.find(|spec| spec.id == feature)
.map(|spec| spec.key)
.expect("feature should have a config key");
format!("{key} = {enabled}")
})
.collect::<Vec<_>>()
.join("\n");
let feature_config = if feature_entries.is_empty() {
String::new()
} else {
format!("[features]\n{feature_entries}\n\n")
};
std::fs::write(
codex_home.join("config.toml"),
format!(
r#"
model = "{model}"
approval_policy = "{approval_policy}"
sandbox_mode = "{sandbox_mode}"
{root_config}
model_provider = "{provider_id}"
{feature_config}[model_providers.{provider_id}]
name = "{provider_name}"
base_url = "{provider_base_url}"
wire_api = "responses"
request_max_retries = 0
stream_max_retries = 0
{provider_config}
{extra_config}
"#
),
)
}
}
/// 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,
feature_flags: &BTreeMap<Feature, bool>,
auto_compact_limit: i64,
requires_openai_auth: Option<bool>,
model_provider_id: &str,
compact_prompt: &str,
) -> std::io::Result<()> {
let mut config = MockResponsesConfig::new(server_uri)
.with_model_provider(model_provider_id)
.with_features(feature_flags)
.with_root_config(&format!(
"compact_prompt = \"{compact_prompt}\"\nmodel_auto_compact_token_limit = {auto_compact_limit}"
))
.with_provider_config("supports_websockets = false");
if model_provider_id == "openai" {
config = config.with_root_config(&format!("openai_base_url = \"{server_uri}/v1\""));
}
if matches!(requires_openai_auth, Some(true)) {
config = config
.with_provider_name("OpenAI")
.with_provider_config("requires_openai_auth = true");
}
config.write(codex_home)
}
pub fn write_mock_responses_config_toml_with_chatgpt_base_url(
codex_home: &Path,
server_uri: &str,
chatgpt_base_url: &str,
) -> std::io::Result<()> {
MockResponsesConfig::new(server_uri)
.with_root_config(&format!("chatgpt_base_url = \"{chatgpt_base_url}\""))
.write(codex_home)
}
#[cfg(test)]
#[path = "config_tests.rs"]
mod tests;