Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,683 @@
use akode_app_server_protocol::ModelProviderError;
use akode_arg0::Arg0DispatchPaths;
use akode_config::ConfigLayerStack;
use akode_config::LoaderOverrides;
use akode_config::ThreadConfigLoader;
use akode_config::loader::load_config_layers_state;
use akode_config::loader::load_managed_requirements_state;
use akode_core::config::Config;
use akode_core::config::ConfigBuilder;
use akode_core::config::ConfigOverrides;
use akode_exec_server::LOCAL_FS;
use akode_features::feature_for_key;
use akode_login::AuthManager;
use akode_login::default_client::set_default_client_residency_requirement;
use akode_model_provider_info::built_in_model_providers;
use akode_model_provider_info::merge_configured_model_providers;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_json_to_toml::json_to_toml;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::RwLock;
use toml::Value as TomlValue;
use tracing::instrument;
use tracing::warn;
#[path = "application_network.rs"]
pub(crate) mod application_network;
/// Shared app-server entry point for loading effective Codex configuration.
#[derive(Clone)]
pub(crate) struct ConfigManager {
codex_home: PathBuf,
cli_overrides: Arc<RwLock<Vec<(String, TomlValue)>>>,
runtime_feature_enablement: Arc<RwLock<BTreeMap<String, bool>>>,
loader_overrides: LoaderOverrides,
strict_config: bool,
arg0_paths: Arg0DispatchPaths,
pub(crate) thread_config_loader: Arc<dyn ThreadConfigLoader>,
network_policy: akode_http_client::NetworkPolicyController,
local_network_policy: akode_http_client::NetworkPolicyController,
network_policy_reload: Arc<tokio::sync::Semaphore>,
network_policy_snapshot: Arc<RwLock<Option<Arc<ApplicationPolicySnapshot>>>>,
}
/// Startup configuration, including whether loading had to fall back to defaults.
pub(crate) struct StartupConfig {
pub(crate) config: Config,
pub(crate) used_defaults: bool,
}
/// Startup configuration loaded with local fallback, plus the strictly loaded configuration.
pub(crate) struct ManagedStartupConfig {
pub(crate) bootstrap: Config,
pub(crate) config: std::io::Result<Config>,
}
/// Configuration and policy must finish loading against the same policy snapshot.
pub(crate) struct ApplicationPolicyLoad {
snapshot: Arc<ApplicationPolicySnapshot>,
}
#[derive(PartialEq, Eq)]
struct ApplicationPolicySnapshot {
revision: akode_http_client::NetworkPolicyRevision,
policy: akode_http_client::DestinationPolicy,
}
impl ConfigManager {
pub(crate) fn new(
codex_home: PathBuf,
cli_overrides: Vec<(String, TomlValue)>,
loader_overrides: LoaderOverrides,
strict_config: bool,
arg0_paths: Arg0DispatchPaths,
thread_config_loader: Arc<dyn ThreadConfigLoader>,
) -> Self {
let network_policy = akode_http_client::NetworkPolicyController::default();
Self {
codex_home,
cli_overrides: Arc::new(RwLock::new(cli_overrides)),
runtime_feature_enablement: Arc::new(RwLock::new(BTreeMap::new())),
loader_overrides,
strict_config,
arg0_paths,
thread_config_loader,
network_policy,
local_network_policy: Default::default(),
network_policy_reload: Arc::new(tokio::sync::Semaphore::new(/*permits*/ 1)),
network_policy_snapshot: Arc::default(),
}
}
pub(crate) fn codex_home(&self) -> &Path {
self.codex_home.as_path()
}
pub(crate) fn with_embedded_network_policy(
mut self,
policy: crate::in_process::EmbeddedNetworkPolicy,
) -> Self {
self.network_policy = policy.effective;
self.local_network_policy = policy.local;
self
}
pub(crate) fn user_config_path(&self) -> std::io::Result<AbsolutePathBuf> {
self.loader_overrides.user_config_path(self.codex_home())
}
pub(crate) fn loader_overrides(&self) -> &LoaderOverrides {
&self.loader_overrides
}
pub(crate) fn current_cli_overrides(&self) -> Vec<(String, TomlValue)> {
self.cli_overrides
.read()
.map(|guard| guard.clone())
.unwrap_or_default()
}
pub(crate) fn extend_runtime_feature_enablement<I>(&self, enablement: I) -> Result<(), ()>
where
I: IntoIterator<Item = (String, bool)>,
{
let mut runtime_feature_enablement =
self.runtime_feature_enablement.write().map_err(|_| ())?;
runtime_feature_enablement.extend(enablement);
Ok(())
}
pub(crate) async fn sync_default_client_residency_requirement(&self) {
match self.load_latest_config(/*fallback_cwd*/ None).await {
Ok(config) => {
set_default_client_residency_requirement(config.enforce_residency.value());
}
Err(err) => warn!(
error = %err,
"failed to sync default client residency requirement after auth refresh"
),
}
}
pub(crate) async fn load_latest_config(
&self,
fallback_cwd: Option<PathBuf>,
) -> std::io::Result<Config> {
let Some(fallback_cwd) = fallback_cwd else {
return self.load_non_project_config().await;
};
self.load_with_cli_overrides(
&self.current_cli_overrides(),
/*request_overrides*/ None,
ConfigOverrides::default(),
Some(fallback_cwd),
)
.await
}
/// Loads system, user, and runtime settings without discovering a project
/// from the app-server process's working directory.
pub(crate) async fn load_non_project_config(&self) -> std::io::Result<Config> {
let policy_load = self.refresh_application_network_policy().await?;
let mut config = ConfigBuilder::default()
.codex_home(self.codex_home.clone())
.cli_overrides(self.current_cli_overrides())
.loader_overrides(self.loader_overrides.clone())
.strict_config(self.strict_config)
.fallback_cwd(Some(self.codex_home.clone()))
.thread_config_loader(Arc::clone(&self.thread_config_loader))
.without_project_context()
.build()
.await?;
self.check_application_policy_load(&policy_load)?;
self.apply_network_policy(&mut config);
self.apply_runtime_feature_enablement(&mut config);
self.apply_arg0_paths(&mut config);
Ok(config)
}
pub(crate) async fn load_latest_config_with_session_layers(
&self,
session_layers: &ConfigLayerStack,
cwd: &Path,
) -> std::io::Result<Config> {
let codex_home = AbsolutePathBuf::from_absolute_path(&self.codex_home)?;
let layers = self
.load_config_layers_for_cwd(AbsolutePathBuf::from_absolute_path(cwd)?)
.await?;
let mut config = Config::rebuild_with_session_layers(
session_layers,
cwd.to_path_buf(),
&layers,
codex_home,
)
.await?;
self.apply_network_policy(&mut config);
self.apply_runtime_feature_enablement(&mut config);
self.apply_arg0_paths(&mut config);
Ok(config)
}
/// Checks the retained session route against current managed provider requirements.
pub(crate) async fn check_thread_model_provider(
&self,
current: &Config,
) -> std::io::Result<()> {
let policy_load = self.refresh_application_network_policy().await?;
// Existing threads retain their session route; only managed
// requirements can invalidate it.
let requirements = load_managed_requirements_state(
LOCAL_FS.as_ref(),
&self.codex_home,
akode_config::ConfigLoadOptions {
loader_overrides: self.loader_overrides.clone(),
strict_config: self.strict_config,
},
)
.await?;
self.check_application_policy_load(&policy_load)?;
let selection_changed = requirements
.model_provider
.as_ref()
.is_some_and(|provider_id| provider_id != &current.model_provider_id);
let required_provider = requirements
.model_providers
.as_ref()
.and_then(|providers| providers.get(&current.model_provider_id))
.cloned()
.map(|provider| {
merge_configured_model_providers(
HashMap::new(),
HashMap::from([(current.model_provider_id.clone(), provider)]),
)
.unwrap_or_default()
.remove(&current.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 != &current.model_provider);
if selection_changed || definition_changed {
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
ModelProviderError::ModelProviderPolicyConflict {
model_provider: current.model_provider_id.clone(),
required_model_provider: requirements
.model_provider
.unwrap_or_else(|| current.model_provider_id.clone()),
},
));
}
Ok(())
}
/// Loads a bootstrap config (falling back to defaults when allowed) and the
/// strictly loaded config. Callers choose their error/recovery policy before
/// initializing any runtimes.
pub(crate) async fn load_managed_startup_config(
&self,
cwd: Option<PathBuf>,
) -> std::io::Result<ManagedStartupConfig> {
let bootstrap = self.load_startup_config(cwd.clone()).await?.config;
// Fail closed before startup when managed authentication requirements
// leave no usable login method, even if the bootstrap fell back to defaults.
AuthManager::shared_from_config(&bootstrap, /*enable_codex_api_key_env*/ false)
.await
.map_err(std::io::Error::other)?;
let config = self.load_latest_config(cwd).await;
Ok(ManagedStartupConfig { bootstrap, config })
}
/// Installs local policy first; failed policy loads block traffic while
/// non-strict startup remains available for configuration repair.
pub(crate) async fn load_startup_config(
&self,
fallback_cwd: Option<PathBuf>,
) -> std::io::Result<StartupConfig> {
match self.load_latest_config(fallback_cwd).await {
Ok(config) => Ok(StartupConfig {
config,
used_defaults: false,
}),
Err(error)
if self.strict_config
|| crate::is_unsupported_untrusted_approval_policy_error(&error) =>
{
Err(error)
}
Err(error) => {
warn!(%error, "configuration is unavailable; using default settings");
Ok(StartupConfig {
config: self.load_default_config().await?,
used_defaults: true,
})
}
}
}
pub(crate) async fn load_default_config(&self) -> std::io::Result<Config> {
let mut loader_overrides = self.loader_overrides.clone();
loader_overrides.ignore_user_config = true;
loader_overrides.ignore_project_config = true;
loader_overrides.ignore_managed_requirements |=
self.refresh_local_network_policy().await.is_err();
let mut config = ConfigBuilder::default()
.codex_home(self.codex_home.clone())
.cli_overrides(self.current_cli_overrides())
.loader_overrides(loader_overrides)
.fallback_cwd(Some(self.codex_home.clone()))
.build()
.await?;
self.apply_network_policy(&mut config);
self.apply_runtime_feature_enablement(&mut config);
self.apply_arg0_paths(&mut config);
Ok(config)
}
pub(crate) async fn load_with_overrides(
&self,
request_overrides: Option<HashMap<String, serde_json::Value>>,
typesafe_overrides: ConfigOverrides,
) -> std::io::Result<Config> {
self.load_with_cli_overrides(
&self.current_cli_overrides(),
request_overrides,
typesafe_overrides,
/*fallback_cwd*/ None,
)
.await
}
pub(crate) async fn load_for_cwd(
&self,
request_overrides: Option<HashMap<String, serde_json::Value>>,
typesafe_overrides: ConfigOverrides,
cwd: Option<PathBuf>,
) -> std::io::Result<Config> {
self.load_with_cli_overrides(
&self.current_cli_overrides(),
request_overrides,
typesafe_overrides,
cwd,
)
.await
.and_then(|config| {
config.validate_windows_mxc_requirement()?;
Ok(config)
})
}
/// Validates saved and requested providers before resume overrides or policy can replace them.
pub(crate) async fn load_for_resume(
&self,
saved_provider: Option<&str>,
request_overrides: Option<HashMap<String, serde_json::Value>>,
mut typesafe_overrides: ConfigOverrides,
cwd: Option<PathBuf>,
) -> std::io::Result<Config> {
let requested_provider = typesafe_overrides.model_provider.clone().or_else(|| {
request_overrides
.as_ref()
.and_then(|values| values.get("model_provider"))
.and_then(serde_json::Value::as_str)
.map(str::to_owned)
});
if let Some(saved) = saved_provider {
typesafe_overrides.model_provider = Some(saved.to_owned());
}
self.load_with_validation(
&self.current_cli_overrides(),
request_overrides,
typesafe_overrides,
cwd,
|config, _overrides, layers| {
let requested_provider = requested_provider
.as_deref()
.or(saved_provider)
.or(config.model_provider.as_deref())
.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
{
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
ModelProviderError::ModelProviderPolicyConflict {
model_provider: provider.to_owned(),
required_model_provider: required.to_owned(),
},
));
}
if !config.model_providers.contains_key(provider)
&& !built_in_model_providers().contains_key(provider)
{
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
ModelProviderError::ModelProviderNotConfigured {
model_provider: provider.to_owned(),
},
));
}
}
if let Some(saved) = saved_provider
&& saved != requested_provider
{
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("Cannot change this thread's model provider from `{saved}` to `{requested_provider}` on resume."),
));
}
Ok(())
},
)
.await
.and_then(|config| {
config.validate_windows_mxc_requirement()?;
Ok(config)
})
}
/// Reload sources using the task's session flags before materializing config.
pub(crate) async fn load_permission_config_for_thread(
&self,
thread_config: &Config,
cwd: AbsolutePathBuf,
permission_profile: String,
) -> std::io::Result<Config> {
let mut session_flags = TomlValue::Table(Default::default());
for layer in thread_config.config_layer_stack.layers_low_to_high() {
if matches!(layer.name, akode_config::ConfigLayerSource::SessionFlags) {
akode_config::merge_toml_values(&mut session_flags, &layer.config);
}
}
let overrides = session_flags
.as_table()
.ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
"session flags must be a table",
)
})?
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect::<Vec<_>>();
self.load_with_cli_overrides(
&overrides,
/*request_overrides*/ None,
ConfigOverrides {
cwd: Some(cwd.to_path_buf()),
default_permissions: Some(permission_profile),
codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(),
..Default::default()
},
Some(cwd.to_path_buf()),
)
.await
.and_then(|config| {
config.validate_windows_mxc_requirement()?;
Ok(config)
})
}
#[instrument(level = "trace", skip_all)]
pub(crate) async fn load_with_cli_overrides(
&self,
cli_overrides: &[(String, TomlValue)],
request_overrides: Option<HashMap<String, serde_json::Value>>,
typesafe_overrides: ConfigOverrides,
fallback_cwd: Option<PathBuf>,
) -> std::io::Result<Config> {
self.load_with_validation(
cli_overrides,
request_overrides,
typesafe_overrides,
fallback_cwd,
|_, _, _| Ok(()),
)
.await
}
async fn load_with_validation(
&self,
cli_overrides: &[(String, TomlValue)],
request_overrides: Option<HashMap<String, serde_json::Value>>,
mut typesafe_overrides: ConfigOverrides,
fallback_cwd: Option<PathBuf>,
validate: impl FnOnce(
&akode_config::config_toml::ConfigToml,
&ConfigOverrides,
&ConfigLayerStack,
) -> std::io::Result<()>,
) -> std::io::Result<Config> {
let policy_load = self.refresh_application_network_policy().await?;
let mut request_overrides = request_overrides.unwrap_or_default();
if let Some(value) = request_overrides.remove("bypass_hook_trust") {
typesafe_overrides.bypass_hook_trust = Some(value.as_bool().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
"`bypass_hook_trust` override must be a boolean",
)
})?);
}
let merged_cli_overrides = cli_overrides
.iter()
.cloned()
.chain(
request_overrides
.into_iter()
.map(|(key, value)| (key, json_to_toml(value))),
)
.collect::<Vec<_>>();
let result = akode_core::config::ConfigBuilder::default()
.codex_home(self.codex_home.clone())
.cli_overrides(merged_cli_overrides)
.loader_overrides(self.loader_overrides.clone())
.strict_config(self.strict_config)
.harness_overrides(typesafe_overrides)
.fallback_cwd(fallback_cwd)
.thread_config_loader(Arc::clone(&self.thread_config_loader))
.build_with_validation(validate)
.await;
let mut config = result?;
self.check_application_policy_load(&policy_load)?;
self.apply_network_policy(&mut config);
self.apply_runtime_feature_enablement(&mut config);
self.apply_arg0_paths(&mut config);
Ok(config)
}
pub(crate) async fn load_config_layers_for_cwd(
&self,
cwd: AbsolutePathBuf,
) -> std::io::Result<ConfigLayerStack> {
self.load_config_layers(Some(cwd)).await
}
pub(crate) async fn load_config_layers(
&self,
cwd: Option<AbsolutePathBuf>,
) -> std::io::Result<ConfigLayerStack> {
let policy_load = self.refresh_application_network_policy().await?;
let result = load_config_layers_state(
LOCAL_FS.as_ref(),
&self.codex_home,
cwd,
&self.current_cli_overrides(),
akode_config::ConfigLoadOptions {
loader_overrides: self.loader_overrides().clone(),
strict_config: self.strict_config,
},
self.thread_config_loader.as_ref(),
)
.await;
let layers = result?;
self.check_application_policy_load(&policy_load)?;
Ok(layers)
}
fn apply_runtime_feature_enablement(&self, config: &mut Config) {
apply_runtime_feature_enablement(config, &self.current_runtime_feature_enablement());
}
fn current_runtime_feature_enablement(&self) -> BTreeMap<String, bool> {
self.runtime_feature_enablement
.read()
.map(|guard| guard.clone())
.unwrap_or_default()
}
fn apply_network_policy(&self, config: &mut Config) {
config.application_network_policy = self.network_policy.policy();
config.application_auth_route_config = Some(
akode_login::AuthRouteConfig::from_http_client_factory(
config
.http_client_factory()
.with_network_policy(self.network_policy.policy()),
)
.with_local_bootstrap_factory(
config
.http_client_factory()
.with_network_policy(self.local_network_policy.policy()),
),
);
}
fn apply_arg0_paths(&self, config: &mut Config) {
config.codex_self_exe = self.arg0_paths.codex_self_exe.clone();
config.codex_linux_sandbox_exe = self.arg0_paths.codex_linux_sandbox_exe.clone();
}
#[cfg(test)]
pub(crate) fn new_for_tests(
codex_home: PathBuf,
cli_overrides: Vec<(String, TomlValue)>,
loader_overrides: LoaderOverrides,
) -> Self {
Self::new(
codex_home,
cli_overrides,
loader_overrides,
/*strict_config*/ false,
Arg0DispatchPaths::default(),
Arc::new(akode_config::NoopThreadConfigLoader),
)
}
#[cfg(test)]
pub(crate) fn without_managed_config_for_tests(codex_home: PathBuf) -> Self {
Self::new_for_tests(
codex_home,
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
)
}
}
#[cfg(test)]
#[path = "application_network_tests.rs"]
mod application_network_tests;
#[cfg(test)]
#[path = "config_manager_provider_tests.rs"]
mod provider_tests;
pub(crate) fn protected_feature_keys(config_layer_stack: &ConfigLayerStack) -> BTreeSet<String> {
let mut protected_features = config_layer_stack
.effective_config()
.get("features")
.and_then(toml::Value::as_table)
.map(|features| features.keys().cloned().collect::<BTreeSet<_>>())
.unwrap_or_default();
if let Some(feature_requirements) = config_layer_stack
.requirements_toml()
.feature_requirements
.as_ref()
{
protected_features.extend(feature_requirements.entries.keys().cloned());
}
protected_features
}
pub(crate) fn apply_runtime_feature_enablement(
config: &mut Config,
runtime_feature_enablement: &BTreeMap<String, bool>,
) {
config.runtime_feature_defaults = runtime_feature_enablement
.iter()
.filter_map(|(name, enabled)| feature_for_key(name).map(|feature| (feature, *enabled)))
.collect();
let protected_features = protected_feature_keys(&config.config_layer_stack);
for (name, enabled) in runtime_feature_enablement {
if protected_features.contains(name) {
continue;
}
let Some(feature) = feature_for_key(name) else {
continue;
};
if let Err(err) = config.features.set_enabled(feature, *enabled) {
warn!(
feature = name,
error = %err,
"failed to apply runtime feature enablement"
);
}
}
}