use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::collections::{BTreeMap, BTreeSet};
use agent_client_protocol::schema::v1::{
EnvVariable, HttpHeader, McpServer, McpServerHttp, McpServerStdio,
};
use arabica_provider::{ApiProviderConfig, ApiType};
use arabica_runtime::{
BlendRoutingPolicy, BlendToolRoute, ToolArgumentPermissionRule, ToolPermissionPolicy,
ToolPermissionRule,
};
use serde::{Deserialize, Serialize};
use crate::host::{HostConfigArgs, workspace_id_for};
pub const SOE_POLICY_ID: &str = "soe";
pub fn soe_policy(alias: String) -> BlendRoutingPolicy {
BlendRoutingPolicy {
policy_id: SOE_POLICY_ID.to_owned(),
version: 1,
default_model: alias.clone(),
after_tool_success: None,
after_tool_error: None,
recovery_model: None,
planning_model: None,
tool_routes: Vec::new(),
recovery_after_no_progress_steps: default_recovery_threshold(),
minimum_model_dwell_steps: default_model_dwell_steps(),
tool_call_capable_models: [alias.clone()].into(),
typed_completion_capable_models: [alias].into(),
}
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct UserConfig {
#[serde(default)]
providers: BTreeMap<String, UserProvider>,
#[serde(default)]
mcp: Vec<UserMcpServer>,
#[serde(default)]
models: BTreeMap<String, UserModel>,
#[serde(default)]
blend: Option<UserBlend>,
#[serde(default)]
context: Option<arabica_runtime::ContextPolicy>,
#[serde(default)]
skills: UserSkills,
#[serde(default)]
evaluation: Option<toml::Value>,
#[serde(default)]
permissions: Option<UserPermissions>,
#[serde(default)]
runners: BTreeMap<String, UserRunner>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct UserRunner {
url: String,
workspace: String,
ca_cert: PathBuf,
client_cert: PathBuf,
client_key: PathBuf,
server_name: Option<String>,
runner_id: Option<String>,
call_timeout_secs: Option<u64>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RemoteRunnerSettings {
pub url: url::Url,
pub workspace: String,
pub ca_cert: PathBuf,
pub client_cert: PathBuf,
pub client_key: PathBuf,
pub server_name: Option<String>,
pub runner_id: Option<String>,
pub call_timeout_secs: u64,
}
pub const DEFAULT_REMOTE_CALL_TIMEOUT_SECS: u64 = 900;
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct UserPermissions {
default: Option<String>,
#[serde(default)]
tools: BTreeMap<String, String>,
#[serde(default)]
rules: Vec<UserPermissionRule>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct UserPermissionRule {
tool: String,
parameter: String,
pattern: String,
action: String,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct UserSkills {
#[serde(default)]
roots: Vec<PathBuf>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct UserModel {
provider: String,
model_id: String,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct UserBlend {
policy_id: Option<String>,
version: Option<u64>,
default_model: Option<String>,
after_tool_success: Option<String>,
after_tool_error: Option<String>,
recovery_model: Option<String>,
#[serde(default)]
planning_model: Option<String>,
#[serde(default)]
tool_routes: Vec<BlendToolRoute>,
recovery_after_no_progress_steps: Option<usize>,
minimum_model_dwell_steps: Option<usize>,
#[serde(default)]
tool_call_capable_models: BTreeSet<String>,
#[serde(default)]
typed_completion_capable_models: BTreeSet<String>,
#[serde(default)]
default_policy: Option<String>,
#[serde(default)]
policies: BTreeMap<String, UserBlendPolicy>,
}
impl UserBlend {
fn configured_default_policy_id(&self) -> Option<&str> {
self.default_policy
.as_deref()
.or(self.policy_id.as_deref())
.or_else(|| self.policies.keys().next().map(String::as_str))
.or_else(|| self.default_model.as_ref().map(|_| "cli-config"))
}
fn configured_default_model(&self) -> Option<&str> {
if let Some(default_model) = self.default_model.as_deref() {
return Some(default_model);
}
self.configured_default_policy_id()
.and_then(|id| self.policies.get(id))
.map(|policy| policy.default_model.as_str())
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct UserBlendPolicy {
#[serde(default)]
version: Option<u64>,
default_model: String,
#[serde(default)]
after_tool_success: Option<String>,
#[serde(default)]
after_tool_error: Option<String>,
#[serde(default)]
recovery_model: Option<String>,
#[serde(default)]
planning_model: Option<String>,
#[serde(default)]
tool_routes: Vec<BlendToolRoute>,
#[serde(default = "default_recovery_threshold")]
recovery_after_no_progress_steps: usize,
#[serde(default = "default_model_dwell_steps")]
minimum_model_dwell_steps: usize,
#[serde(default)]
tool_call_capable_models: BTreeSet<String>,
#[serde(default)]
typed_completion_capable_models: BTreeSet<String>,
}
fn default_recovery_threshold() -> usize {
2
}
fn default_model_dwell_steps() -> usize {
1
}
#[derive(Debug)]
pub struct ResolvedCliConfig {
pub invocation: HostConfigArgs,
pub provider: ApiProviderConfig,
pub blend_policy: Option<BlendRoutingPolicy>,
pub blend_policies: BTreeMap<String, BlendRoutingPolicy>,
pub models: BTreeMap<String, String>,
pub model_providers: BTreeMap<String, String>,
pub model_configs: BTreeMap<String, ApiProviderConfig>,
pub permission_policy: ToolPermissionPolicy,
}
impl ResolvedCliConfig {
pub fn model_catalog(&self) -> crate::host::HostModelCatalog {
crate::host::HostModelCatalog {
provider: self.provider.clone(),
models: self.models.clone(),
blend_policy: self.blend_policy.clone(),
model_configs: self.model_configs.clone(),
}
}
pub fn build_model(&self) -> Result<crate::host::HostModel, Box<dyn std::error::Error>> {
Ok(self.model_catalog().build_model()?)
}
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct UserMcpServer {
name: String,
command: Option<String>,
#[serde(default)]
args: Vec<String>,
env: Option<BTreeMap<String, String>>,
url: Option<String>,
headers: Option<BTreeMap<String, String>>,
auth: Option<UserMcpAuth>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "mode", rename_all = "lowercase", deny_unknown_fields)]
enum UserMcpAuth {
Command {
command: Vec<String>,
binding: Option<String>,
},
Oauth {
binding: Option<String>,
client_id: Option<String>,
client_metadata_url: Option<String>,
#[serde(default)]
scopes: Vec<String>,
},
}
impl UserMcpAuth {
fn to_auth(&self) -> crate::mcp::auth::McpAuth {
match self.clone() {
Self::Command { command, binding } => {
crate::mcp::auth::McpAuth::Command { command, binding }
}
Self::Oauth {
binding,
client_id,
client_metadata_url,
scopes,
} => crate::mcp::auth::McpAuth::Oauth {
binding,
client_id,
client_metadata_url,
scopes,
},
}
}
}
impl UserMcpServer {
fn has_credentials(&self) -> bool {
self.env.as_ref().is_some_and(|map| !map.is_empty())
|| self.headers.as_ref().is_some_and(|map| !map.is_empty())
}
fn to_mcp_server(&self) -> Result<McpServer, String> {
match (&self.command, &self.url) {
(Some(command), None) => {
let env = self
.env
.clone()
.unwrap_or_default()
.into_iter()
.map(|(name, value)| EnvVariable::new(name, value))
.collect::<Vec<_>>();
Ok(McpServer::Stdio(
McpServerStdio::new(self.name.clone(), command.clone())
.args(self.args.clone())
.env(env),
))
}
(None, Some(url)) => {
let headers = self
.headers
.clone()
.unwrap_or_default()
.into_iter()
.map(|(name, value)| HttpHeader::new(name, value))
.collect::<Vec<_>>();
let mut server =
McpServerHttp::new(self.name.clone(), url.clone()).headers(headers);
if let Some(auth) = &self.auth {
server = server.meta(auth.to_auth().to_meta());
}
Ok(McpServer::Http(server))
}
(Some(_), Some(_)) => Err(format!(
"MCP server '{}' declares both command and url; pick one transport",
self.name
)),
(None, None) => Err(format!(
"MCP server '{}' declares neither command nor url",
self.name
)),
}
}
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct UserProvider {
auth: Option<String>,
api_type: Option<String>,
api_key: Option<String>,
api_key_env: Option<String>,
base_url: Option<String>,
thinking: Option<String>,
reasoning_effort: Option<String>,
max_tokens: Option<u32>,
request_timeout_secs: Option<u64>,
anthropic_cache_static_prefix: Option<bool>,
}
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct WorkspaceSettings {
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub model_alias: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub thinking: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub blend_policy: Option<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub model_thinking: BTreeMap<String, String>,
}
pub fn user_config_path(home: &Path) -> PathBuf {
home.join("config.toml")
}
pub fn workspace_config_path(home: &Path, cwd: &Path) -> PathBuf {
home.join("workspaces")
.join(workspace_id_for(cwd).to_string())
.join("config.toml")
}
pub fn read_workspace_settings(
home: &Path,
cwd: &Path,
) -> Result<WorkspaceSettings, Box<dyn std::error::Error>> {
read_toml(&workspace_config_path(home, cwd))
}
fn read_toml<T: for<'de> Deserialize<'de> + Default>(
path: &Path,
) -> Result<T, Box<dyn std::error::Error>> {
match fs::read_to_string(path) {
Ok(text) => Ok(toml::from_str(&text).map_err(|error: toml::de::Error| {
let location = error
.span()
.map(|span| {
let prefix = &text[..span.start.min(text.len())];
let line = prefix.bytes().filter(|byte| *byte == b'\n').count() + 1;
let column = prefix
.rsplit('\n')
.next()
.map_or(1, |row| row.chars().count() + 1);
format!(" at line {line}, column {column}")
})
.unwrap_or_default();
format!("invalid TOML in {}{location}", path.display())
})?),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(T::default()),
Err(error) => Err(format!("cannot read {}: {error}", path.display()).into()),
}
}
fn read_user_config(home: &Path) -> Result<UserConfig, Box<dyn std::error::Error>> {
let path = user_config_path(home);
let config: UserConfig = read_toml(&path)?;
for (name, provider) in &config.providers {
if name.trim().is_empty() {
return Err(format!("{} contains an empty provider name", path.display()).into());
}
if provider
.api_key
.as_ref()
.is_some_and(|key| key.trim().is_empty())
{
return Err(format!(
"{} contains an empty API key for provider {name:?}",
path.display()
)
.into());
}
if provider
.api_key_env
.as_ref()
.is_some_and(|key| key.trim().is_empty())
{
return Err(format!(
"{} contains an empty api_key_env for provider {name:?}",
path.display()
)
.into());
}
}
let has_credentials = config
.providers
.values()
.any(|provider| provider.api_key.is_some())
|| config.mcp.iter().any(UserMcpServer::has_credentials);
if has_credentials {
let metadata = fs::symlink_metadata(&path)?;
if !metadata.file_type().is_file() {
return Err(format!(
"{} must be a regular file when it contains credentials",
path.display()
)
.into());
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if metadata.permissions().mode() & 0o077 != 0 {
return Err(format!(
"{} contains credentials and must be readable only by its owner (chmod 600)",
path.display()
)
.into());
}
}
}
Ok(config)
}
pub(crate) struct SettingsValidationError {
pub path: Vec<String>,
pub message: &'static str,
}
pub(crate) fn validate_settings_document(
document: &toml::Value,
) -> Result<(), SettingsValidationError> {
fn invalid(path: Vec<String>, message: &'static str) -> SettingsValidationError {
SettingsValidationError { path, message }
}
fn field(section: &str, name: &str, key: &str) -> Vec<String> {
vec![section.to_owned(), name.to_owned(), key.to_owned()]
}
fn http_url(value: &str) -> bool {
url::Url::parse(value)
.is_ok_and(|url| matches!(url.scheme(), "http" | "https") && url.host_str().is_some())
}
let config: UserConfig = document.clone().try_into().map_err(|_| invalid(
Vec::new(),
"The configuration has an unsupported field, an incorrect field type, or a missing required field. Match the documented config.toml schema.",
))?;
for (name, provider) in &config.providers {
let path = |key| field("providers", name, key);
if name.trim().is_empty() {
return Err(invalid(
vec!["providers".to_owned(), name.clone()],
"Provider IDs must not be empty.",
));
}
if provider
.api_key
.as_ref()
.is_some_and(|value| value.trim().is_empty())
{
return Err(invalid(
path("api_key"),
"An API key must not be empty. Remove the field to use another credential source.",
));
}
if provider
.api_key_env
.as_ref()
.is_some_and(|value| value.trim().is_empty() || value.contains(['=', '\0']))
{
return Err(invalid(
path("api_key_env"),
"Specify a non-empty environment variable name without equals signs or NUL characters.",
));
}
let chatgpt = provider
.auth
.as_ref()
.is_some_and(|auth| auth.eq_ignore_ascii_case("chatgpt"));
if provider.auth.is_some() && !chatgpt {
return Err(invalid(
path("auth"),
"The supported provider authentication mode is chatgpt. Remove auth to use an API key.",
));
}
if chatgpt && (provider.api_key.is_some() || provider.api_key_env.is_some()) {
return Err(invalid(
path("auth"),
"ChatGPT authentication cannot be combined with API-key fields.",
));
}
let api_type = provider
.api_type
.as_deref()
.map(str::parse::<ApiType>)
.transpose()
.map_err(|_| invalid(path("api_type"), "Select a supported provider API type."))?
.unwrap_or(if chatgpt {
ApiType::OpenAiResponses
} else {
ApiType::OpenAiChatCompletions
});
if chatgpt && api_type != ApiType::OpenAiResponses {
return Err(invalid(
path("api_type"),
"ChatGPT authentication requires the OpenAI Responses API.",
));
}
if let Some(base_url) = &provider.base_url {
if !http_url(base_url) {
return Err(invalid(
path("base_url"),
"Use an absolute HTTP or HTTPS provider URL.",
));
}
if chatgpt && base_url.trim_end_matches('/') != "https://api.openai.com/v1" {
return Err(invalid(
path("base_url"),
"ChatGPT authentication requires https://api.openai.com/v1.",
));
}
}
if provider.max_tokens == Some(0) {
return Err(invalid(
path("max_tokens"),
"The token limit must be positive.",
));
}
if provider.request_timeout_secs == Some(0) {
return Err(invalid(
path("request_timeout_secs"),
"The request timeout must be positive.",
));
}
if provider.anthropic_cache_static_prefix == Some(true)
&& api_type != ApiType::AnthropicMessages
{
return Err(invalid(
path("anthropic_cache_static_prefix"),
"Static prefix caching requires the Anthropic Messages API.",
));
}
if provider.thinking.is_some() && provider.reasoning_effort.is_some() {
return Err(invalid(
path("thinking"),
"Configure either thinking or reasoning_effort, not both.",
));
}
let mut configuration = ApiProviderConfig::new(
api_type,
"settings-validation",
"https://example.invalid",
"settings-validation",
);
for (key, value) in [
("thinking", &provider.thinking),
("reasoning_effort", &provider.reasoning_effort),
] {
if let Some(value) = value {
set_thinking(&mut configuration, value).map_err(|_| {
invalid(
path(key),
"Select a thinking level supported by this provider API type.",
)
})?;
}
}
}
for (alias, model) in &config.models {
if alias.trim().is_empty() {
return Err(invalid(
vec!["models".to_owned(), alias.clone()],
"Model aliases must not be empty.",
));
}
if !config.providers.contains_key(&model.provider) {
return Err(invalid(
field("models", alias, "provider"),
"Select an existing provider before saving this model.",
));
}
if model.model_id.trim().is_empty() {
return Err(invalid(
field("models", alias, "model_id"),
"A model ID must not be empty.",
));
}
}
if let Some(blend) = &config.blend {
let aliases = config
.models
.iter()
.map(|(alias, model)| (alias.clone(), model.model_id.clone()))
.collect();
let policies = configured_file_blend_policies(blend, &aliases).map_err(|_| invalid(
vec!["blend".to_owned()],
"Policies require existing model aliases, positive version and thresholds, and valid unique tool routes. Use either a single policy or named policies.",
))?;
if blend
.default_policy
.as_ref()
.is_some_and(|id| !policies.contains_key(id))
{
return Err(invalid(
vec!["blend".to_owned(), "default_policy".to_owned()],
"Select an existing default policy.",
));
}
}
let mut server_names = BTreeSet::new();
for (index, server) in config.mcp.iter().enumerate() {
let path = |key: &str| vec!["mcp".to_owned(), index.to_string(), key.to_owned()];
if server.name.trim().is_empty() || !server_names.insert(server.name.as_str()) {
return Err(invalid(
path("name"),
"MCP server names must be non-empty and unique.",
));
}
match (&server.command, &server.url) {
(Some(command), None)
if Path::new(command).is_absolute() && !command.contains('\0') =>
{
if server.auth.is_some() {
return Err(invalid(
path("auth"),
"Authentication modes apply only to MCP servers configured with a URL.",
));
}
if server
.headers
.as_ref()
.is_some_and(|headers| !headers.is_empty())
{
return Err(invalid(
path("headers"),
"HTTP headers apply only to MCP servers configured with a URL.",
));
}
}
(Some(_), None) => {
return Err(invalid(
path("command"),
"Use an absolute executable path for an MCP stdio server.",
));
}
(None, Some(url)) if http_url(url) => {
if !server.args.is_empty() || server.env.as_ref().is_some_and(|env| !env.is_empty())
{
return Err(invalid(
path("url"),
"Arguments and environment variables apply only to MCP stdio servers.",
));
}
}
(None, Some(_)) => {
return Err(invalid(
path("url"),
"Use an absolute HTTP or HTTPS MCP URL.",
));
}
_ => {
return Err(invalid(
path("command"),
"Configure exactly one MCP transport: command or url.",
));
}
}
if server.args.iter().any(|argument| argument.contains('\0')) {
return Err(invalid(
path("args"),
"MCP arguments must not contain NUL characters.",
));
}
for (key, value) in server.env.iter().flatten() {
if key.is_empty() || key.contains(['=', '\0']) || value.contains('\0') {
let mut path = path("env");
path.push(key.clone());
return Err(invalid(
path,
"Environment names must be non-empty and contain no equals sign or NUL; values must contain no NUL.",
));
}
}
for (key, value) in server.headers.iter().flatten() {
let mut field_path = path("headers");
field_path.push(key.clone());
let name = reqwest::header::HeaderName::from_bytes(key.as_bytes())
.map_err(|_| invalid(field_path.clone(), "Specify a valid HTTP header name."))?;
reqwest::header::HeaderValue::from_str(value).map_err(|_| {
invalid(
field_path.clone(),
"The HTTP header value contains unsupported characters.",
)
})?;
if matches!(
name.as_str(),
"accept"
| "content-type"
| "mcp-session-id"
| "last-event-id"
| "mcp-protocol-version"
| "mcp-method"
| "mcp-name"
) || name.as_str().starts_with("mcp-param-")
{
return Err(invalid(
field_path,
"Protocol-owned MCP headers are generated automatically and cannot be overridden.",
));
}
}
}
for (index, server) in config.mcp.iter().enumerate() {
let Some(auth) = &server.auth else {
continue;
};
let path = |key: &str| vec!["mcp".to_owned(), index.to_string(), key.to_owned()];
if auth.to_auth().validate(&server.name).is_err() {
return Err(invalid(
path("auth"),
"Use an absolute credential command, a binding of 1 to 200 characters, a non-empty client_id, and an HTTPS client_metadata_url.",
));
}
if server
.headers
.iter()
.flatten()
.any(|(key, _)| key.eq_ignore_ascii_case("authorization"))
{
return Err(invalid(
path("headers"),
"Remove the Authorization header; the auth table supplies it.",
));
}
}
for (index, root) in config.skills.roots.iter().enumerate() {
if root.as_os_str().is_empty() || root.to_string_lossy().contains('\0') {
return Err(invalid(
vec!["skills".to_owned(), "roots".to_owned(), index.to_string()],
"Specify a non-empty skills directory path without NUL characters.",
));
}
}
if let Some(context) = &config.context {
context.validate().map_err(|_| invalid(vec!["context".to_owned()], "The context policy requires valid sets, references, a non-empty ID, and a positive version."))?;
}
if let Some(evaluation) = config.evaluation {
let evaluation: arabica_runtime::EvaluationConfig =
evaluation.try_into().map_err(|_| {
invalid(
vec!["evaluation".to_owned()],
"The evaluation configuration contains an unsupported field or field type.",
)
})?;
let registry =
arabica_runtime::EvaluationRegistry::builtins(&evaluation).map_err(|_| {
invalid(
vec!["evaluation".to_owned()],
"The evaluation configuration has invalid clustering bounds or strategies.",
)
})?;
let evidence = arabica_runtime::EvaluationEvidence::from_history(&[]);
registry
.context(&evaluation.context_strategy, &evidence)
.and_then(|_| {
registry
.model(&evaluation.model_strategy, &evidence)
.map(|_| ())
})
.map_err(|_| {
invalid(
vec!["evaluation".to_owned()],
"Select registered evaluation strategies.",
)
})?;
}
resolve_permission_policy(config.permissions.as_ref()).map_err(|_| invalid(vec!["permissions".to_owned()], "Permission rules require valid tool names, parameters, regex patterns, and allow, ask, or deny actions."))?;
Ok(())
}
pub fn user_config_key(home: &Path) -> Result<Option<String>, Box<dyn std::error::Error>> {
Ok(read_user_config(home)?
.providers
.values()
.find_map(|provider| provider.api_key.clone()))
}
pub fn user_config_api_key_env(home: &Path) -> Result<Option<String>, Box<dyn std::error::Error>> {
let config = read_user_config(home)?;
let Some(alias) = config
.blend
.as_ref()
.and_then(UserBlend::configured_default_model)
else {
return Ok(None);
};
let Some(model) = config.models.get(alias) else {
return Ok(None);
};
let Some(provider) = config.providers.get(&model.provider) else {
return Ok(None);
};
Ok(Some(
provider
.api_key_env
.clone()
.unwrap_or_else(|| provider_api_key_env(&model.provider)),
))
}
pub fn user_config_mcp(home: &Path) -> Result<Vec<McpServer>, Box<dyn std::error::Error>> {
let config = read_user_config(home)?;
config
.mcp
.iter()
.map(|server| server.to_mcp_server().map_err(Into::into))
.collect()
}
pub fn user_config_context(
home: &Path,
) -> Result<Option<arabica_runtime::ContextPolicy>, Box<dyn std::error::Error>> {
let policy = read_user_config(home)?.context;
if let Some(policy) = &policy {
policy.validate()?;
}
Ok(policy)
}
pub fn user_config_evaluation(
home: &Path,
) -> Result<arabica_runtime::EvaluationConfig, Box<dyn std::error::Error>> {
let config: arabica_runtime::EvaluationConfig = read_user_config(home)?
.evaluation
.map(toml::Value::try_into)
.transpose()?
.unwrap_or_default();
let registry = arabica_runtime::EvaluationRegistry::builtins(&config)?;
let evidence = arabica_runtime::EvaluationEvidence::from_history(&[]);
registry.context(&config.context_strategy, &evidence)?;
registry.model(&config.model_strategy, &evidence)?;
Ok(config)
}
pub fn user_config_blend_policies(
home: &Path,
cwd: &Path,
) -> Result<BTreeMap<String, BlendRoutingPolicy>, Box<dyn std::error::Error>> {
let resolved = resolve_cli_runtime_config(
&HostConfigArgs::default(),
home,
cwd,
crate::host::process_environment,
)?;
Ok(resolved.blend_policies)
}
pub fn user_config_runner(
home: &Path,
name: &str,
) -> Result<RemoteRunnerSettings, Box<dyn std::error::Error>> {
let mut config = read_user_config(home)?;
let Some(runner) = config.runners.remove(name) else {
let known: Vec<&str> = config.runners.keys().map(String::as_str).collect();
return Err(if known.is_empty() {
format!(
"no [runners.{name}] table in {}",
user_config_path(home).display()
)
.into()
} else {
format!("unknown runner {name:?}; configured: {}", known.join(", ")).into()
});
};
let url = url::Url::parse(&runner.url)
.map_err(|_| format!("runners.{name}.url is not a valid URL"))?;
if url.scheme() != "wss" {
return Err(format!("runners.{name}.url must use wss://").into());
}
if runner.workspace.trim().is_empty() {
return Err(format!("runners.{name}.workspace must not be empty").into());
}
if runner.call_timeout_secs == Some(0) {
return Err(format!("runners.{name}.call_timeout_secs must be positive").into());
}
let resolve = |path: PathBuf| {
if path.is_absolute() {
path
} else {
home.join(path)
}
};
Ok(RemoteRunnerSettings {
url,
workspace: runner.workspace,
ca_cert: resolve(runner.ca_cert),
client_cert: resolve(runner.client_cert),
client_key: resolve(runner.client_key),
server_name: runner.server_name,
runner_id: runner.runner_id,
call_timeout_secs: runner
.call_timeout_secs
.unwrap_or(DEFAULT_REMOTE_CALL_TIMEOUT_SECS),
})
}
pub fn user_config_skill_roots(home: &Path) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
Ok(read_user_config(home)?
.skills
.roots
.into_iter()
.map(|root| {
if root.is_absolute() {
root
} else {
home.join(root)
}
})
.collect())
}
pub fn resolve_cli_config(
args: &HostConfigArgs,
home: &Path,
cwd: &Path,
lookup: impl Fn(&str) -> Option<String>,
) -> Result<ApiProviderConfig, Box<dyn std::error::Error>> {
Ok(resolve_cli_runtime_config(args, home, cwd, lookup)?.provider)
}
fn configured_blend_policies(
blend: &UserBlend,
models: &BTreeMap<String, String>,
home: &Path,
) -> Result<BTreeMap<String, BlendRoutingPolicy>, Box<dyn std::error::Error>> {
let mut policies = configured_file_blend_policies(blend, models)?;
if let Ok(records) = arabica_adapters::SqliteEvaluationStore::read_policy_versions(
&home.join("evaluation.sqlite3"),
None,
) {
for record in records {
let policy = record.policy;
let key = format!("{}-v{}", record.policy_id, record.version);
if validate_blend_policy(&policy, models).is_ok() {
policies.entry(key).or_insert(policy);
}
}
}
Ok(policies)
}
fn configured_file_blend_policies(
blend: &UserBlend,
models: &BTreeMap<String, String>,
) -> Result<BTreeMap<String, BlendRoutingPolicy>, Box<dyn std::error::Error>> {
let named_policies = !blend.policies.is_empty();
let mut policies = BTreeMap::new();
if named_policies {
if blend.policy_id.is_some()
|| blend.version.is_some()
|| blend.default_model.is_some()
|| blend.after_tool_success.is_some()
|| blend.after_tool_error.is_some()
|| blend.recovery_model.is_some()
|| blend.planning_model.is_some()
|| !blend.tool_routes.is_empty()
|| blend.recovery_after_no_progress_steps.is_some()
|| blend.minimum_model_dwell_steps.is_some()
|| !blend.tool_call_capable_models.is_empty()
|| !blend.typed_completion_capable_models.is_empty()
{
return Err(
"configure either the single [blend] policy or [blend.policies.<name>] entries, not both".into(),
);
}
for (id, configured) in &blend.policies {
let policy = BlendRoutingPolicy {
policy_id: id.clone(),
version: configured.version.unwrap_or(1),
default_model: configured.default_model.clone(),
after_tool_success: configured.after_tool_success.clone(),
after_tool_error: configured.after_tool_error.clone(),
recovery_model: configured.recovery_model.clone(),
planning_model: configured.planning_model.clone(),
tool_routes: configured.tool_routes.clone(),
recovery_after_no_progress_steps: configured.recovery_after_no_progress_steps,
minimum_model_dwell_steps: configured.minimum_model_dwell_steps,
tool_call_capable_models: configured.tool_call_capable_models.clone(),
typed_completion_capable_models: configured.typed_completion_capable_models.clone(),
};
validate_blend_policy(&policy, models)?;
policies.insert(id.clone(), policy);
}
} else {
let id = blend
.policy_id
.clone()
.or_else(|| blend.default_policy.clone())
.unwrap_or_else(|| "cli-config".to_owned());
let policy = BlendRoutingPolicy {
policy_id: id.clone(),
version: blend.version.unwrap_or(1),
default_model: blend
.default_model
.clone()
.ok_or("[blend].default_model is required")?,
after_tool_success: blend.after_tool_success.clone(),
after_tool_error: blend.after_tool_error.clone(),
recovery_model: blend.recovery_model.clone(),
planning_model: blend.planning_model.clone(),
tool_routes: blend.tool_routes.clone(),
recovery_after_no_progress_steps: blend
.recovery_after_no_progress_steps
.unwrap_or_else(default_recovery_threshold),
minimum_model_dwell_steps: blend
.minimum_model_dwell_steps
.unwrap_or_else(default_model_dwell_steps),
tool_call_capable_models: blend.tool_call_capable_models.clone(),
typed_completion_capable_models: blend.typed_completion_capable_models.clone(),
};
validate_blend_policy(&policy, models)?;
policies.insert(id, policy);
}
Ok(policies)
}
pub fn resolve_cli_runtime_config(
args: &HostConfigArgs,
home: &Path,
cwd: &Path,
lookup: impl Fn(&str) -> Option<String>,
) -> Result<ResolvedCliConfig, Box<dyn std::error::Error>> {
resolve_runtime_config(args, home, cwd, lookup, true)
}
pub fn resolve_cli_acp_config(
args: &HostConfigArgs,
home: &Path,
cwd: &Path,
lookup: impl Fn(&str) -> Option<String>,
) -> Result<ResolvedCliConfig, Box<dyn std::error::Error>> {
resolve_runtime_config(args, home, cwd, lookup, false)
}
fn resolve_runtime_config(
args: &HostConfigArgs,
home: &Path,
cwd: &Path,
lookup: impl Fn(&str) -> Option<String>,
use_workspace: bool,
) -> Result<ResolvedCliConfig, Box<dyn std::error::Error>> {
let user = read_user_config(home)?;
let permission_policy = resolve_permission_policy(user.permissions.as_ref())?;
let workspace = if use_workspace {
read_workspace_settings(home, cwd)?
} else {
WorkspaceSettings::default()
};
if user.models.is_empty() && user.blend.is_some() {
return Err("[blend] requires at least one [models.<alias>] entry".into());
}
if !user.models.is_empty() && user.blend.is_none() {
return Err(
"[models] requires a [blend] table with a default_model or named policy".into(),
);
}
if user.models.is_empty() {
return Err(format!(
"configure [providers.<name>], [models.<alias>], and [blend] in {}; \
run `arabica auth chatgpt-login` to set up a ChatGPT plan, or see https://github.com/haowei2000/Arabica/blob/main/docs/cli.md",
user_config_path(home).display()
)
.into());
}
let models = user
.models
.iter()
.map(|(alias, model)| {
if alias.trim().is_empty()
|| model.model_id.trim().is_empty()
|| model.provider.trim().is_empty()
{
return Err(format!(
"model alias, provider, and model_id must not be empty ({alias:?})"
));
}
Ok((alias.clone(), model.model_id.clone()))
})
.collect::<Result<BTreeMap<_, _>, String>>()?;
let blend = user.blend.as_ref().expect("validated Blend configuration");
let blend_policies = configured_blend_policies(blend, &models, home)?;
let selected_policy_id = args
.policy
.as_deref()
.or(workspace.blend_policy.as_deref())
.or_else(|| blend.configured_default_policy_id())
.ok_or("a Blend policy is required")?;
let is_soe = selected_policy_id == SOE_POLICY_ID && !blend_policies.contains_key(SOE_POLICY_ID);
let configured_policy_id = if is_soe {
blend
.configured_default_policy_id()
.ok_or("a Blend policy is required")?
} else {
selected_policy_id
};
let configured_default_alias = blend_policies
.get(configured_policy_id)
.ok_or_else(|| format!("unknown Blend policy {selected_policy_id:?}"))?
.default_model
.clone();
if !user.models.contains_key(&configured_default_alias) {
return Err(format!(
"[blend].default_model alias {configured_default_alias:?} is not configured"
)
.into());
}
let default_alias = args
.model_alias
.clone()
.or_else(|| is_soe.then(|| workspace.model_alias.clone()).flatten())
.unwrap_or(configured_default_alias);
if !user.models.contains_key(&default_alias) {
return Err(format!("workspace model alias {default_alias:?} is not configured").into());
}
let default_model = user
.models
.get(&default_alias)
.ok_or("[blend].default_model must reference a configured model alias")?;
let default_provider_name = default_model.provider.clone();
let mut model_configs = BTreeMap::new();
for (alias, model) in &user.models {
let user_provider = user.providers.get(&model.provider).ok_or_else(|| {
format!(
"model alias {alias:?} references unknown provider {:?}",
model.provider
)
})?;
let same_as_default_provider = model.provider == default_provider_name;
let chatgpt_auth = user_provider
.auth
.as_deref()
.is_some_and(|auth| auth.eq_ignore_ascii_case("chatgpt"));
if user_provider
.auth
.as_deref()
.is_some_and(|auth| !auth.eq_ignore_ascii_case("chatgpt"))
{
return Err(format!(
"unsupported auth mode for provider {:?}; expected chatgpt",
model.provider
)
.into());
}
if chatgpt_auth && (user_provider.api_key.is_some() || user_provider.api_key_env.is_some())
{
return Err(format!(
"provider {:?} cannot combine auth = \"chatgpt\" with API-key settings",
model.provider
)
.into());
}
let api_type = if same_as_default_provider {
args.api_type
.clone()
.or_else(|| lookup("ARABICA__API_TYPE"))
.or_else(|| user_provider.api_type.clone())
} else {
user_provider.api_type.clone()
}
.unwrap_or_else(|| {
if chatgpt_auth {
ApiType::OpenAiResponses.to_string()
} else {
ApiType::OpenAiChatCompletions.to_string()
}
})
.parse::<ApiType>()?;
if chatgpt_auth && api_type != ApiType::OpenAiResponses {
return Err(format!(
"provider {:?} with auth = \"chatgpt\" must use the OpenAI Responses API",
model.provider
)
.into());
}
let base_url = if same_as_default_provider {
args.base_url
.clone()
.or_else(|| lookup("ARABICA__BASE_URL"))
.or_else(|| user_provider.base_url.clone())
} else {
user_provider.base_url.clone()
}
.or_else(|| chatgpt_auth.then(|| "https://api.openai.com/v1".to_owned()))
.ok_or_else(|| format!("base_url is required for provider {:?}", model.provider))?;
if chatgpt_auth && base_url.trim_end_matches('/') != "https://api.openai.com/v1" {
return Err(format!(
"provider {:?} using ChatGPT plan authentication must call https://api.openai.com/v1",
model.provider
)
.into());
}
let env_name = user_provider
.api_key_env
.clone()
.unwrap_or_else(|| provider_api_key_env(&model.provider));
let environment_key = lookup(&env_name).filter(|key| !key.trim().is_empty());
let saved_key = if same_as_default_provider
&& environment_key.is_none()
&& user_provider.api_key.is_none()
{
crate::auth::read_saved_key(home)?
} else {
None
};
let api_key = if chatgpt_auth {
"chatgpt-oauth-managed".to_owned()
} else {
environment_key
.or_else(|| user_provider.api_key.clone())
.or(saved_key)
.ok_or_else(|| {
format!(
"API key is required for provider {:?}; set {env_name} or api_key",
model.provider
)
})?
};
if user_provider.max_tokens == Some(0) {
return Err(format!(
"max_tokens must be positive for provider {:?}",
model.provider
)
.into());
}
if user_provider.request_timeout_secs == Some(0) {
return Err(format!(
"request_timeout_secs must be positive for provider {:?}",
model.provider
)
.into());
}
if user_provider.anthropic_cache_static_prefix == Some(true)
&& api_type != ApiType::AnthropicMessages
{
return Err(format!(
"anthropic_cache_static_prefix is only supported for Anthropic provider {:?}",
model.provider
)
.into());
}
if user_provider.reasoning_effort.is_some() && user_provider.thinking.is_some() {
return Err(format!(
"configure only one of thinking or reasoning_effort for provider {:?}",
model.provider
)
.into());
}
let mut config =
ApiProviderConfig::new(api_type, api_key, base_url, model.model_id.clone());
if chatgpt_auth {
let credentials_path = crate::auth::chatgpt_credentials_path(home);
let credentials = crate::auth::read_chatgpt_credentials(home)?
.ok_or("ChatGPT plan is not connected; run `arabica auth chatgpt-login`")?;
if credentials.access_token.is_empty() || credentials.refresh_token.is_empty() {
return Err("ChatGPT plan is signed out; run `arabica auth chatgpt-login`".into());
}
config.chatgpt_credentials = Some(credentials_path);
}
config.max_tokens = user_provider.max_tokens;
config.request_timeout_secs = user_provider.request_timeout_secs.unwrap_or(300);
config.anthropic_cache_static_prefix =
user_provider.anthropic_cache_static_prefix.unwrap_or(false);
config.thinking_enabled = false;
if let Some(effort) = &user_provider.reasoning_effort {
set_thinking(&mut config, effort)?;
}
if let Some(thinking) = user_provider.thinking.as_deref() {
set_thinking(&mut config, thinking)?;
}
if is_soe && let Some(thinking) = workspace.model_thinking.get(alias) {
set_thinking(&mut config, thinking)?;
}
if alias == &default_alias {
if let Some(thinking) = args.thinking.as_deref().or_else(|| {
(is_soe && !workspace.model_thinking.contains_key(alias))
.then_some(workspace.thinking.as_deref())
.flatten()
}) {
set_thinking(&mut config, thinking)?;
}
if let Some(model_id) = args
.model
.clone()
.or_else(|| is_soe.then(|| workspace.model.clone()).flatten())
.or_else(|| lookup("ARABICA__MODEL"))
{
config.model = model_id;
}
}
model_configs.insert(alias.clone(), config);
}
let mut selected_policy = if is_soe {
soe_policy(default_alias.clone())
} else {
blend_policies[selected_policy_id].clone()
};
selected_policy.default_model = default_alias.clone();
validate_blend_policy(&selected_policy, &models)?;
let blend_policy = Some(selected_policy);
let provider = model_configs
.get(&default_alias)
.expect("validated default alias")
.clone();
Ok(ResolvedCliConfig {
invocation: args.clone(),
provider,
blend_policy,
blend_policies,
models,
model_providers: user
.models
.iter()
.map(|(alias, model)| (alias.clone(), model.provider.clone()))
.collect(),
model_configs,
permission_policy,
})
}
fn resolve_permission_policy(
configured: Option<&UserPermissions>,
) -> Result<ToolPermissionPolicy, String> {
let mut policy = ToolPermissionPolicy {
default: ToolPermissionRule::Ask,
by_tool: [
"read_file",
"list_dir",
"grep",
"find_files",
"memory_search",
"memory_read",
]
.into_iter()
.map(|tool| (tool.to_owned(), ToolPermissionRule::Allow))
.collect(),
argument_rules: Vec::new(),
};
let Some(configured) = configured else {
return Ok(policy);
};
if let Some(rule) = &configured.default {
policy.by_tool.clear();
policy.default = parse_permission_rule(rule, "permissions.default")?;
}
for (tool, rule) in &configured.tools {
if tool.trim().is_empty() {
return Err("[permissions.tools] tool names must not be empty".to_owned());
}
policy.by_tool.insert(
tool.clone(),
parse_permission_rule(rule, &format!("permissions.tools.{tool}"))?,
);
}
for (index, configured_rule) in configured.rules.iter().enumerate() {
let field = format!("permissions.rules[{index}]");
if configured_rule.tool.trim().is_empty() {
return Err(format!("{field}.tool must not be empty"));
}
if configured_rule.parameter.trim().is_empty() {
return Err(format!("{field}.parameter must not be empty"));
}
regex::Regex::new(&configured_rule.pattern)
.map_err(|error| format!("{field}.pattern is not a valid regex: {error}"))?;
policy.argument_rules.push(ToolArgumentPermissionRule {
tool: configured_rule.tool.clone(),
parameter: configured_rule.parameter.clone(),
pattern: configured_rule.pattern.clone(),
rule: parse_permission_rule(&configured_rule.action, &format!("{field}.action"))?,
});
}
Ok(policy)
}
fn parse_permission_rule(value: &str, field: &str) -> Result<ToolPermissionRule, String> {
match value.trim().to_ascii_lowercase().as_str() {
"allow" => Ok(ToolPermissionRule::Allow),
"ask" => Ok(ToolPermissionRule::Ask),
"deny" => Ok(ToolPermissionRule::Deny),
_ => Err(format!("{field} must be one of: allow, ask, deny")),
}
}
fn validate_blend_policy(
policy: &BlendRoutingPolicy,
models: &BTreeMap<String, String>,
) -> Result<(), String> {
if !models.contains_key(&policy.default_model) {
return Err(format!(
"[blend].default_model alias {:?} is not configured",
policy.default_model
));
}
let aliases = std::iter::once(policy.default_model.as_str())
.chain(policy.after_tool_success.as_deref())
.chain(policy.after_tool_error.as_deref())
.chain(policy.recovery_model.as_deref())
.chain(policy.planning_model.as_deref())
.chain(policy.tool_routes.iter().map(|route| route.model.as_str()))
.chain(policy.tool_call_capable_models.iter().map(String::as_str))
.chain(
policy
.typed_completion_capable_models
.iter()
.map(String::as_str),
);
if policy.policy_id.trim().is_empty()
|| policy.version == 0
|| policy.recovery_after_no_progress_steps == 0
|| policy.minimum_model_dwell_steps == 0
|| aliases.into_iter().any(|alias| !models.contains_key(alias))
{
return Err(format!(
"Blend policy {:?} has an invalid value or references an undefined model alias",
policy.policy_id
));
}
let mut route_ids = BTreeSet::new();
for route in &policy.tool_routes {
if route.id.trim().is_empty() || !route_ids.insert(route.id.as_str()) {
return Err(format!(
"Blend policy {:?} has an empty or duplicate tool route id",
policy.policy_id
));
}
if let arabica_runtime::BlendToolMatcher::RegexName(pattern)
| arabica_runtime::BlendToolMatcher::EventTraceRegex(pattern)
| arabica_runtime::BlendToolMatcher::EventTraceV1Regex(pattern) = &route.matcher
{
regex::Regex::new(pattern).map_err(|error| {
format!(
"Blend policy {:?} has invalid route regex {:?}: {error}",
policy.policy_id, pattern
)
})?;
}
}
Ok(())
}
fn provider_api_key_env(provider: &str) -> String {
let suffix = provider
.chars()
.map(|character| {
if character.is_ascii_alphanumeric() {
character.to_ascii_uppercase()
} else {
'_'
}
})
.collect::<String>();
format!("ARABICA_PROVIDER_{suffix}_API_KEY")
}
pub fn set_thinking(config: &mut ApiProviderConfig, value: &str) -> Result<(), String> {
match (config.api_type, value) {
(_, "off" | "default") => {
config.thinking_enabled = false;
config.reasoning_effort = None;
}
(ApiType::OpenAiChatCompletions, "on") => {
config.thinking_enabled = true;
config.reasoning_effort = None;
}
(ApiType::OpenAiResponses, "low" | "medium" | "high" | "xhigh" | "max") => {
config.thinking_enabled = true;
config.reasoning_effort = Some(value.to_owned());
}
_ => {
return Err(format!(
"unsupported thinking level {value:?} for {}",
config.api_type
));
}
}
Ok(())
}
pub fn thinking_levels(api_type: ApiType) -> &'static [&'static str] {
match api_type {
ApiType::OpenAiResponses => &["default", "low", "medium", "high", "xhigh", "max"],
ApiType::OpenAiChatCompletions => &["off", "on"],
_ => &["off"],
}
}
pub fn thinking_level(config: &ApiProviderConfig) -> &str {
if !config.thinking_enabled && config.api_type == ApiType::OpenAiResponses {
"default"
} else if !config.thinking_enabled {
"off"
} else if config.api_type == ApiType::OpenAiResponses {
config.reasoning_effort.as_deref().unwrap_or("high")
} else {
"on"
}
}
pub(crate) fn reset_configured_model_thinking(
home: &Path,
configs: &mut BTreeMap<String, ApiProviderConfig>,
) -> Result<(), Box<dyn std::error::Error>> {
let user = read_user_config(home)?;
for (alias, config) in configs {
let Some(model) = user.models.get(alias) else {
continue;
};
let provider = user
.providers
.get(&model.provider)
.ok_or_else(|| format!("model alias {alias:?} references an unknown provider"))?;
if provider.thinking.is_some() && provider.reasoning_effort.is_some() {
return Err(format!(
"configure only one of thinking or reasoning_effort for provider {:?}",
model.provider
)
.into());
}
set_thinking(config, "off")?;
if let Some(thinking) = provider
.thinking
.as_deref()
.or(provider.reasoning_effort.as_deref())
{
set_thinking(config, thinking)?;
}
}
Ok(())
}
pub fn policy_selection_key<'a>(
policies: &'a BTreeMap<String, BlendRoutingPolicy>,
policy: &'a BlendRoutingPolicy,
) -> &'a str {
policies
.iter()
.find(|(_, candidate)| {
candidate.policy_id == policy.policy_id && candidate.version == policy.version
})
.map_or(policy.policy_id.as_str(), |(key, _)| key.as_str())
}
pub fn save_workspace_settings(
home: &Path,
cwd: &Path,
edit: impl FnOnce(&mut WorkspaceSettings),
) -> Result<(), Box<dyn std::error::Error>> {
let path = workspace_config_path(home, cwd);
let mut settings: WorkspaceSettings = read_toml(&path)?;
edit(&mut settings);
let body = toml::to_string_pretty(&settings)?;
let parent = path.parent().expect("config path has parent");
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
let mut builder = fs::DirBuilder::new();
builder.recursive(true).mode(0o700).create(parent)?;
}
#[cfg(not(unix))]
fs::create_dir_all(parent)?;
let temporary = parent.join(format!(".config-{}.tmp", uuid::Uuid::now_v7()));
let result = (|| -> Result<(), Box<dyn std::error::Error>> {
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(&temporary)?;
file.write_all(body.as_bytes())?;
file.sync_all()?;
fs::rename(&temporary, &path)?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn user_defaults_workspace_choice_and_flags_have_stable_precedence() {
let root = std::env::temp_dir().join(format!("structure-config-{}", uuid::Uuid::now_v7()));
let home = root.join("home");
let cwd = root.join("project");
fs::create_dir_all(&home).unwrap();
fs::create_dir_all(&cwd).unwrap();
fs::write(
user_config_path(&home),
"[providers.test]\nbase_url = 'https://example.test/v1'\nthinking = 'on'\n\n[models.default]\nprovider = 'test'\nmodel_id = 'user-model'\n\n[blend]\ndefault_model = 'default'\n",
)
.unwrap();
let env = |name: &str| match name {
"ARABICA_PROVIDER_TEST_API_KEY" => Some("secret".to_owned()),
"ARABICA__MODEL" => Some("env-model".to_owned()),
_ => None,
};
let defaults = resolve_cli_config(&HostConfigArgs::default(), &home, &cwd, env).unwrap();
assert_eq!(defaults.model, "env-model");
assert_eq!(defaults.base_url, "https://example.test/v1");
assert!(defaults.thinking_enabled);
save_workspace_settings(&home, &cwd, |settings| {
settings.blend_policy = Some(SOE_POLICY_ID.to_owned());
settings.model = Some("workspace-model".to_owned());
settings.thinking = Some("off".to_owned());
})
.unwrap();
let workspace = resolve_cli_config(&HostConfigArgs::default(), &home, &cwd, env).unwrap();
assert_eq!(workspace.model, "workspace-model");
assert!(!workspace.thinking_enabled);
let flags = HostConfigArgs {
model: Some("flag-model".to_owned()),
..HostConfigArgs::default()
};
let selected = resolve_cli_config(&flags, &home, &cwd, env).unwrap();
assert_eq!(selected.model, "flag-model");
assert!(
!fs::read_to_string(workspace_config_path(&home, &cwd))
.unwrap()
.contains("secret")
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn model_aliases_and_blend_policy_resolve_from_user_toml() {
let root =
std::env::temp_dir().join(format!("structure-blend-config-{}", uuid::Uuid::now_v7()));
let home = root.join("home");
let cwd = root.join("project");
fs::create_dir_all(&home).unwrap();
fs::create_dir_all(&cwd).unwrap();
fs::write(
user_config_path(&home),
r#"
[providers.test]
base_url = "https://example.test/v1"
[models.fast]
provider = "test"
model_id = "model-mini"
[models.strong]
provider = "test"
model_id = "model-pro"
[blend]
policy_id = "coding"
version = 3
default_model = "fast"
after_tool_error = "strong"
recovery_model = "strong"
recovery_after_no_progress_steps = 2
tool_call_capable_models = ["fast", "strong"]
typed_completion_capable_models = ["strong"]
"#,
)
.unwrap();
let resolved =
resolve_cli_runtime_config(&HostConfigArgs::default(), &home, &cwd, |name| {
(name == "ARABICA_PROVIDER_TEST_API_KEY").then(|| "test-key".to_owned())
})
.unwrap();
assert_eq!(resolved.provider.model, "model-mini");
assert_eq!(resolved.models["strong"], "model-pro");
assert_eq!(resolved.blend_policy.as_ref().unwrap().version, 3);
assert_eq!(resolved.blend_policies.len(), 1);
assert_eq!(
resolved
.blend_policy
.as_ref()
.unwrap()
.typed_completion_capable_models,
BTreeSet::from(["strong".to_owned()])
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn workspace_selection_and_invocation_overrides_preserve_policy_templates() {
let root =
std::env::temp_dir().join(format!("arabica-selections-{}", uuid::Uuid::now_v7()));
let home = root.join("home");
let cwd = root.join("project");
fs::create_dir_all(&home).unwrap();
fs::create_dir_all(&cwd).unwrap();
fs::write(
user_config_path(&home),
r#"
[providers.test]
api_type = "open_ai_responses"
base_url = "https://example.test/v1"
[models.daily]
provider = "test"
model_id = "daily-model"
[models.strong]
provider = "test"
model_id = "strong-model"
[blend]
default_policy = "routine"
[blend.policies.routine]
default_model = "daily"
[blend.policies.precise]
default_model = "strong"
planning_model = "strong"
"#,
)
.unwrap();
save_workspace_settings(&home, &cwd, |settings| {
settings.blend_policy = Some("precise".to_owned());
settings.model_alias = Some("daily".to_owned());
settings
.model_thinking
.insert("daily".to_owned(), "low".to_owned());
settings
.model_thinking
.insert("strong".to_owned(), "high".to_owned());
})
.unwrap();
let env =
|name: &str| (name == "ARABICA_PROVIDER_TEST_API_KEY").then(|| "test-key".to_owned());
let saved =
resolve_cli_runtime_config(&HostConfigArgs::default(), &home, &cwd, env).unwrap();
assert_eq!(saved.blend_policy.as_ref().unwrap().policy_id, "precise");
assert_eq!(saved.provider.model, "strong-model");
assert_eq!(thinking_level(&saved.provider), "default");
assert_eq!(saved.blend_policies["precise"].default_model, "strong");
save_workspace_settings(&home, &cwd, |settings| {
settings.blend_policy = Some(SOE_POLICY_ID.to_owned());
})
.unwrap();
let soe = resolve_cli_runtime_config(&HostConfigArgs::default(), &home, &cwd, env).unwrap();
let policy = soe.blend_policy.as_ref().unwrap();
assert_eq!(policy.policy_id, SOE_POLICY_ID);
assert_eq!(policy.default_model, "daily");
assert!(policy.planning_model.is_none());
assert!(policy.after_tool_error.is_none());
assert_eq!(
policy.tool_call_capable_models,
BTreeSet::from(["daily".to_owned()])
);
assert_eq!(thinking_level(&soe.provider), "low");
assert_eq!(thinking_level(&soe.model_configs["strong"]), "high");
let soe_flags = HostConfigArgs {
policy: Some(SOE_POLICY_ID.to_owned()),
model_alias: Some("strong".to_owned()),
thinking: Some("max".to_owned()),
..Default::default()
};
let explicit_soe = resolve_cli_runtime_config(&soe_flags, &home, &cwd, env).unwrap();
assert_eq!(explicit_soe.provider.model, "strong-model");
assert_eq!(thinking_level(&explicit_soe.provider), "max");
assert_eq!(thinking_level(&explicit_soe.model_configs["daily"]), "low");
save_workspace_settings(&home, &cwd, |settings| {
settings.blend_policy = Some("precise".to_owned());
})
.unwrap();
let returned =
resolve_cli_runtime_config(&HostConfigArgs::default(), &home, &cwd, env).unwrap();
assert_eq!(returned.provider.model, "strong-model");
assert_eq!(thinking_level(&returned.provider), "default");
assert_eq!(thinking_level(&returned.model_configs["daily"]), "default");
let remembered = read_workspace_settings(&home, &cwd).unwrap();
assert_eq!(remembered.model_thinking["daily"], "low");
assert_eq!(remembered.model_thinking["strong"], "high");
let flags = HostConfigArgs {
policy: Some("precise".to_owned()),
thinking: Some("max".to_owned()),
..Default::default()
};
let selected = resolve_cli_runtime_config(&flags, &home, &cwd, env).unwrap();
assert_eq!(selected.provider.model, "strong-model");
assert_eq!(thinking_level(&selected.provider), "max");
assert_eq!(thinking_level(&selected.model_configs["daily"]), "default");
let acp = resolve_cli_acp_config(&HostConfigArgs::default(), &home, &cwd, env).unwrap();
assert_eq!(acp.blend_policy.as_ref().unwrap().policy_id, "routine");
assert_eq!(thinking_level(&acp.provider), "default");
let invalid = HostConfigArgs {
policy: Some("missing".to_owned()),
..Default::default()
};
assert!(
resolve_cli_runtime_config(&invalid, &home, &cwd, env)
.unwrap_err()
.to_string()
.contains("unknown Blend policy")
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn configured_named_soe_retains_its_cli_routes_and_ignores_builtin_preferences() {
let root = std::env::temp_dir().join(format!("arabica-named-soe-{}", uuid::Uuid::now_v7()));
let home = root.join("home");
let cwd = root.join("project");
fs::create_dir_all(&home).unwrap();
fs::create_dir_all(&cwd).unwrap();
fs::write(
user_config_path(&home),
r#"
[providers.test]
api_type = "open_ai_responses"
base_url = "https://example.test/v1"
thinking = "medium"
[models.fast]
provider = "test"
model_id = "model-fast"
[models.strong]
provider = "test"
model_id = "model-strong"
[blend]
default_policy = "soe"
[blend.policies.soe]
default_model = "fast"
after_tool_error = "strong"
planning_model = "strong"
"#,
)
.unwrap();
save_workspace_settings(&home, &cwd, |settings| {
settings.blend_policy = Some(SOE_POLICY_ID.to_owned());
settings.model_alias = Some("strong".to_owned());
settings.thinking = Some("off".to_owned());
settings
.model_thinking
.insert("fast".to_owned(), "low".to_owned());
})
.unwrap();
let env =
|name: &str| (name == "ARABICA_PROVIDER_TEST_API_KEY").then(|| "test-key".to_owned());
let resolved =
resolve_cli_runtime_config(&HostConfigArgs::default(), &home, &cwd, env).unwrap();
let policy = resolved.blend_policy.as_ref().unwrap();
assert_eq!(policy.policy_id, SOE_POLICY_ID);
assert_eq!(policy.default_model, "fast");
assert_eq!(policy.after_tool_error.as_deref(), Some("strong"));
assert_eq!(policy.planning_model.as_deref(), Some("strong"));
assert_eq!(thinking_level(&resolved.provider), "medium");
let flags = HostConfigArgs {
policy: Some(SOE_POLICY_ID.to_owned()),
model_alias: Some("strong".to_owned()),
thinking: Some("max".to_owned()),
..Default::default()
};
let selected = resolve_cli_runtime_config(&flags, &home, &cwd, env).unwrap();
assert_eq!(selected.provider.model, "model-strong");
assert_eq!(thinking_level(&selected.provider), "max");
assert_eq!(
selected
.blend_policy
.as_ref()
.unwrap()
.after_tool_error
.as_deref(),
Some("strong")
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn named_blend_policies_resolve_and_select_the_configured_default() {
let root =
std::env::temp_dir().join(format!("structure-policy-config-{}", uuid::Uuid::now_v7()));
let home = root.join("home");
let cwd = root.join("project");
fs::create_dir_all(&home).unwrap();
fs::create_dir_all(&cwd).unwrap();
fs::write(
user_config_path(&home),
r#"
[providers.test]
base_url = "https://example.test/v1"
[models.fast]
provider = "test"
model_id = "model-mini"
[models.strong]
provider = "test"
model_id = "model-pro"
[blend]
default_policy = "coding"
[blend.policies.coding]
default_model = "fast"
after_tool_error = "strong"
[blend.policies.precise]
default_model = "strong"
minimum_model_dwell_steps = 3
"#,
)
.unwrap();
let resolved =
resolve_cli_runtime_config(&HostConfigArgs::default(), &home, &cwd, |name| {
(name == "ARABICA_PROVIDER_TEST_API_KEY").then(|| "test-key".to_owned())
})
.unwrap();
assert_eq!(resolved.blend_policy.as_ref().unwrap().policy_id, "coding");
assert_eq!(
resolved.blend_policy.as_ref().unwrap().default_model,
"fast"
);
assert_eq!(resolved.blend_policies.len(), 2);
assert_eq!(resolved.blend_policies["precise"].default_model, "strong");
assert_eq!(
resolved.blend_policies["precise"].minimum_model_dwell_steps,
3
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn skill_roots_and_initial_modes_resolve_from_user_configuration() {
let root =
std::env::temp_dir().join(format!("structure-skill-config-{}", uuid::Uuid::now_v7()));
fs::create_dir_all(&root).unwrap();
fs::write(
user_config_path(&root),
r#"
[skills]
roots = ["skills"]
[context]
policy_id = "test"
version = 1
include = ["skill:review"]
unfolded = ["skill:review"]
"#,
)
.unwrap();
assert_eq!(
user_config_skill_roots(&root).unwrap(),
vec![root.join("skills")]
);
let policy = user_config_context(&root).unwrap().unwrap();
assert_eq!(policy.default_mode, arabica_protocol::ContextMode::Folded);
assert!(policy.unfolded.contains("skill:review"));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn aliases_resolve_distinct_provider_dialects_and_credentials() {
let root =
std::env::temp_dir().join(format!("structure-multi-provider-{}", uuid::Uuid::now_v7()));
let home = root.join("home");
let cwd = root.join("project");
fs::create_dir_all(&home).unwrap();
fs::create_dir_all(&cwd).unwrap();
fs::write(
user_config_path(&home),
r#"
[providers.openai]
api_type = "open_ai_responses"
base_url = "https://openai.example/v1"
max_tokens = 4096
thinking = "high"
[providers.anthropic]
api_type = "anthropic_messages"
base_url = "https://anthropic.example/v1"
api_key_env = "ANTHROPIC_KEY"
api_key = "config-secret"
request_timeout_secs = 90
anthropic_cache_static_prefix = true
[models.fast]
provider = "openai"
model_id = "gpt-mini"
[models.strong]
provider = "anthropic"
model_id = "claude-opus"
[blend]
default_model = "fast"
"#,
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(user_config_path(&home), fs::Permissions::from_mode(0o600))
.unwrap();
}
let resolved =
resolve_cli_runtime_config(&HostConfigArgs::default(), &home, &cwd, |name| {
(name == "ARABICA_PROVIDER_OPENAI_API_KEY").then(|| "env-openai-secret".to_owned())
})
.unwrap();
assert_eq!(
resolved.model_configs["fast"].api_type,
ApiType::OpenAiResponses
);
assert_eq!(resolved.model_configs["fast"].api_key, "env-openai-secret");
assert_eq!(resolved.model_configs["fast"].max_tokens, Some(4096));
assert_eq!(
resolved.model_configs["fast"].reasoning_effort.as_deref(),
Some("high")
);
assert_eq!(
resolved.model_configs["strong"].api_type,
ApiType::AnthropicMessages
);
assert_eq!(resolved.model_configs["strong"].api_key, "config-secret");
assert_eq!(resolved.model_configs["strong"].request_timeout_secs, 90);
assert!(resolved.model_configs["strong"].anthropic_cache_static_prefix);
let env_precedence = resolve_cli_runtime_config(
&HostConfigArgs::default(),
&home,
&cwd,
|name| match name {
"ARABICA_PROVIDER_OPENAI_API_KEY" => Some("env-openai-secret".to_owned()),
"ANTHROPIC_KEY" => Some("env-anthropic-secret".to_owned()),
_ => None,
},
)
.unwrap();
assert_eq!(
env_precedence.model_configs["strong"].api_key,
"env-anthropic-secret"
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn chatgpt_auth_selects_the_official_responses_endpoint_and_profile() {
let root =
std::env::temp_dir().join(format!("arabica-si-wc-config-{}", uuid::Uuid::now_v7()));
let home = root.join("home");
let cwd = root.join("project");
fs::create_dir_all(&home).unwrap();
fs::create_dir_all(&cwd).unwrap();
fs::write(
user_config_path(&home),
r#"
[providers.openai]
auth = "chatgpt"
[models.default]
provider = "openai"
model_id = "gpt-6.1-sol"
[blend]
default_model = "default"
"#,
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(user_config_path(&home), fs::Permissions::from_mode(0o600))
.unwrap();
}
let credentials_path = crate::auth::chatgpt_credentials_path(&home);
let credentials = arabica_provider::ChatGptCredentials {
email: Some("user@example.test".to_owned()),
subject: "subject".to_owned(),
client_id: "oaiapp_test".to_owned(),
ext_agent_host_id: "urn:uuid:test".to_owned(),
id_token: "id".to_owned(),
access_token: "access".to_owned(),
refresh_token: "refresh".to_owned(),
scopes: vec!["chatgpt.tokens.use.direct".to_owned()],
expires_at_unix: u64::MAX,
};
fs::write(&credentials_path, serde_json::to_vec(&credentials).unwrap()).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&credentials_path, fs::Permissions::from_mode(0o600)).unwrap();
}
let resolved =
resolve_cli_runtime_config(&HostConfigArgs::default(), &home, &cwd, |_| None).unwrap();
let config = &resolved.model_configs["default"];
assert_eq!(config.api_type, ApiType::OpenAiResponses);
assert_eq!(config.base_url, "https://api.openai.com/v1");
assert_eq!(
config.chatgpt_credentials.as_deref(),
Some(credentials_path.as_path())
);
fs::write(
user_config_path(&home),
r#"
[providers.openai]
auth = "chatgpt"
base_url = "https://other.example/v1"
[models.default]
provider = "openai"
model_id = "gpt-6.1-sol"
[blend]
default_model = "default"
"#,
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(user_config_path(&home), fs::Permissions::from_mode(0o600))
.unwrap();
}
assert!(
resolve_cli_runtime_config(&HostConfigArgs::default(), &home, &cwd, |_| None).is_err()
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn context_policy_parses_independently_and_rejects_invalid_sets() {
let root =
std::env::temp_dir().join(format!("structure-context-config-{}", uuid::Uuid::now_v7()));
fs::create_dir_all(&root).unwrap();
fs::write(
user_config_path(&root),
r#"
[context]
policy_id = "read-only"
version = 1
base_sets = ["files"]
exclude = ["tool:write_file"]
disabled_sources = ["mcp"]
[context.sets]
files = ["tool:read_file", "tool:write_file"]
"#,
)
.unwrap();
let policy = user_config_context(&root).unwrap().unwrap();
assert!(policy.sets["files"].contains("tool:read_file"));
assert!(
policy
.disabled_sources
.contains(&arabica_protocol::ContextSourceKind::Mcp)
);
fs::write(
user_config_path(&root),
"[context]\npolicy_id='x'\nversion=1\nbase_sets=['missing']\n",
)
.unwrap();
assert!(user_config_context(&root).is_err());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn model_alias_rejects_an_unknown_provider_before_resolving_credentials() {
let root = std::env::temp_dir().join(format!(
"structure-unknown-provider-{}",
uuid::Uuid::now_v7()
));
let home = root.join("home");
let cwd = root.join("project");
fs::create_dir_all(&home).unwrap();
fs::create_dir_all(&cwd).unwrap();
fs::write(
user_config_path(&home),
"[models.default]\nprovider = 'missing'\nmodel_id = 'model'\n\n[blend]\ndefault_model = 'default'\n",
)
.unwrap();
let error = resolve_cli_runtime_config(&HostConfigArgs::default(), &home, &cwd, |_| None)
.unwrap_err()
.to_string();
assert!(error.contains("unknown provider"), "{error}");
fs::write(
user_config_path(&home),
"[providers.p]\nbase_url = 'https://provider.example/v1'\n\n[models.valid]\nprovider = 'p'\nmodel_id = 'model'\n\n[blend]\ndefault_model = 'missing'\n",
)
.unwrap();
let error = resolve_cli_runtime_config(&HostConfigArgs::default(), &home, &cwd, |_| None)
.unwrap_err()
.to_string();
assert!(error.contains("default_model alias"), "{error}");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn evaluation_config_selects_independent_strategies_and_rejects_unknown_ids() {
let root = std::env::temp_dir().join(format!(
"structure-evaluation-config-{}",
uuid::Uuid::now_v7()
));
fs::create_dir_all(&root).unwrap();
assert_eq!(
user_config_evaluation(&root).unwrap(),
arabica_runtime::EvaluationConfig::default()
);
fs::write(user_config_path(&root), "[evaluation]\ncontext_strategy='behavior-clusters'\nmodel_strategy='observational'\nmax_clusters=2\nmin_cluster_runs=4\n").unwrap();
let config = user_config_evaluation(&root).unwrap();
assert_eq!(config.context_strategy, "behavior-clusters");
assert_eq!(config.model_strategy, "observational");
assert_eq!(config.max_clusters, 2);
fs::write(
user_config_path(&root),
"[evaluation]\nmodel_strategy='missing'\n",
)
.unwrap();
assert!(user_config_evaluation(&root).is_err());
fs::write(user_config_path(&root), "[evaluation]\nmax_clusters=0\n").unwrap();
assert!(user_config_evaluation(&root).is_err());
fs::write(
user_config_path(&root),
"[evaluation]\nmax_clusters='invalid-type'\nunknown_field=true\n",
)
.unwrap();
assert!(user_config_evaluation(&root).is_err());
assert!(user_config_context(&root).unwrap().is_none());
assert!(user_config_skill_roots(&root).unwrap().is_empty());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn invalid_saved_thinking_is_reported() {
let root = std::env::temp_dir().join(format!("structure-config-{}", uuid::Uuid::now_v7()));
let home = root.join("home");
let cwd = root.join("project");
fs::create_dir_all(&home).unwrap();
fs::write(
user_config_path(&home),
"[providers.test]\nbase_url = 'https://example.test/v1'\nthinking = 'high'\n\n[models.default]\nprovider = 'test'\nmodel_id = 'model'\n\n[blend]\ndefault_model = 'default'\n",
)
.unwrap();
let result = resolve_cli_config(
&HostConfigArgs {
model: Some("model".to_owned()),
base_url: Some("https://example.test/v1".to_owned()),
..HostConfigArgs::default()
},
&home,
&cwd,
|name| (name == "ARABICA_PROVIDER_TEST_API_KEY").then(|| "secret".to_owned()),
);
assert!(
result
.unwrap_err()
.to_string()
.contains("unsupported thinking level")
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn saved_auth_supplies_key_and_environment_takes_precedence() {
let root = std::env::temp_dir().join(format!("structure-config-{}", uuid::Uuid::now_v7()));
let home = root.join("home");
let cwd = root.join("project");
crate::auth::save_key(&home, "saved-secret").unwrap();
fs::create_dir_all(&home).unwrap();
fs::write(
user_config_path(&home),
"[providers.default]\nbase_url = 'https://example.test/v1'\n\n[models.default]\nprovider = 'default'\nmodel_id = 'configured-model'\n\n[blend]\ndefault_model = 'default'\n",
)
.unwrap();
let args = HostConfigArgs {
model: Some("model".to_owned()),
base_url: Some("https://example.test/v1".to_owned()),
..HostConfigArgs::default()
};
let saved = resolve_cli_config(&args, &home, &cwd, |_| None).unwrap();
assert_eq!(saved.api_key, "saved-secret");
let env = resolve_cli_config(&args, &home, &cwd, |name| {
(name == "ARABICA_PROVIDER_DEFAULT_API_KEY").then(|| "env-secret".to_owned())
})
.unwrap();
assert_eq!(env.api_key, "env-secret");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn user_config_key_requires_private_file_and_environment_still_wins() {
let root = std::env::temp_dir().join(format!("structure-config-{}", uuid::Uuid::now_v7()));
let home = root.join("home");
let cwd = root.join("project");
fs::create_dir_all(&home).unwrap();
fs::write(
user_config_path(&home),
"[providers.test]\napi_key = 'config-secret'\nbase_url = 'https://example.test/v1'\n\n[models.default]\nprovider = 'test'\nmodel_id = 'model'\n\n[blend]\ndefault_model = 'default'\n",
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(user_config_path(&home), fs::Permissions::from_mode(0o644))
.unwrap();
let error =
resolve_cli_config(&HostConfigArgs::default(), &home, &cwd, |_| None).unwrap_err();
assert!(error.to_string().contains("chmod 600"));
assert!(!error.to_string().contains("config-secret"));
fs::set_permissions(user_config_path(&home), fs::Permissions::from_mode(0o600))
.unwrap();
}
let config = resolve_cli_config(&HostConfigArgs::default(), &home, &cwd, |_| None).unwrap();
assert_eq!(config.api_key, "config-secret");
let env = resolve_cli_config(&HostConfigArgs::default(), &home, &cwd, |name| {
(name == "ARABICA_PROVIDER_TEST_API_KEY").then(|| "env-secret".to_owned())
})
.unwrap();
assert_eq!(env.api_key, "env-secret");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn user_config_mcp_parses_stdio_and_http_servers() {
let root = std::env::temp_dir().join(format!("structure-config-{}", uuid::Uuid::now_v7()));
fs::create_dir_all(&root).unwrap();
fs::write(
user_config_path(&root),
"[[mcp]]\nname = 'alpha'\ncommand = '/usr/bin/env'\nargs = ['python', '-m', 'fixture']\n\n[mcp.env]\nTOKEN = 'alpha-secret'\n\n[[mcp]]\nname = 'remote'\nurl = 'https://mcp.example.test/mcp'\n\n[mcp.headers]\nAuthorization = 'Bearer http-secret'\n",
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(user_config_path(&root), fs::Permissions::from_mode(0o600))
.unwrap();
}
let servers = user_config_mcp(&root).unwrap();
assert_eq!(servers.len(), 2);
let stdio = match &servers[0] {
McpServer::Stdio(config) => config,
other => panic!("expected stdio server, got {other:?}"),
};
assert_eq!(stdio.name, "alpha");
assert_eq!(stdio.args, vec!["python", "-m", "fixture"]);
assert_eq!(stdio.env[0].name, "TOKEN");
let http = match &servers[1] {
McpServer::Http(config) => config,
other => panic!("expected http server, got {other:?}"),
};
assert_eq!(http.url, "https://mcp.example.test/mcp");
assert_eq!(http.headers[0].name, "Authorization");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn user_config_mcp_auth_tables_become_dynamic_auth_declarations() {
let root = std::env::temp_dir().join(format!("structure-config-{}", uuid::Uuid::now_v7()));
fs::create_dir_all(&root).unwrap();
fs::write(
user_config_path(&root),
"[[mcp]]\nname = 'remote'\nurl = 'https://mcp.example.test/mcp'\n\n[mcp.auth]\nmode = 'oauth'\nbinding = 'work'\nclient_id = 'arabica-desktop'\nscopes = ['mcp']\n\n[[mcp]]\nname = 'brokered'\nurl = 'https://other.example.test/mcp'\n\n[mcp.auth]\nmode = 'command'\ncommand = ['/usr/local/bin/token-helper', '--account', 'work']\n",
)
.unwrap();
let servers = user_config_mcp(&root).unwrap();
let auth = servers
.iter()
.map(|server| match server {
McpServer::Http(config) => {
crate::mcp::auth::McpAuth::from_meta(&config.name, config.meta.as_ref())
.unwrap()
.unwrap()
}
other => panic!("expected HTTP server, got {other:?}"),
})
.collect::<Vec<_>>();
assert_eq!(
auth,
[
crate::mcp::auth::McpAuth::Oauth {
binding: Some("work".to_owned()),
client_id: Some("arabica-desktop".to_owned()),
client_metadata_url: None,
scopes: vec!["mcp".to_owned()],
},
crate::mcp::auth::McpAuth::Command {
command: vec![
"/usr/local/bin/token-helper".to_owned(),
"--account".to_owned(),
"work".to_owned()
],
binding: None,
},
]
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn mcp_auth_tables_are_validated_with_their_transport() {
for (document, field) in [
(
"[[mcp]]\nname='x'\ncommand='/bin/true'\n[mcp.auth]\nmode='oauth'\n",
"auth",
),
(
"[[mcp]]\nname='x'\nurl='https://mcp.example.test'\n[mcp.headers]\nAuthorization='Bearer static'\n[mcp.auth]\nmode='oauth'\n",
"headers",
),
(
"[[mcp]]\nname='x'\nurl='https://mcp.example.test'\n[mcp.auth]\nmode='command'\ncommand=['relative-helper']\n",
"auth",
),
] {
let document = toml::from_str::<toml::Value>(document).unwrap();
let error = validate_settings_document(&document)
.err()
.unwrap_or_else(|| panic!("{document:?} must be rejected"));
assert_eq!(error.path.last().map(String::as_str), Some(field));
}
let document = toml::from_str::<toml::Value>(
"[[mcp]]\nname='x'\nurl='https://mcp.example.test'\n[mcp.auth]\nmode='broker'\nbinding='a'\n",
)
.unwrap();
assert!(validate_settings_document(&document).is_err());
}
#[test]
fn user_config_mcp_rejects_missing_and_double_transports() {
let root = std::env::temp_dir().join(format!("structure-config-{}", uuid::Uuid::now_v7()));
fs::create_dir_all(&root).unwrap();
fs::write(user_config_path(&root), "[[mcp]]\nname = 'broken'\n").unwrap();
let error = user_config_mcp(&root).unwrap_err().to_string();
assert!(error.contains("neither command nor url"), "{error}");
fs::write(
user_config_path(&root),
"[[mcp]]\nname = 'broken'\ncommand = '/bin/true'\nurl = 'https://mcp.example.test'\n",
)
.unwrap();
let error = user_config_mcp(&root).unwrap_err().to_string();
assert!(error.contains("both command and url"), "{error}");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn mcp_credentials_require_an_owner_only_config_file() {
let root = std::env::temp_dir().join(format!("structure-config-{}", uuid::Uuid::now_v7()));
fs::create_dir_all(&root).unwrap();
fs::write(
user_config_path(&root),
"[[mcp]]\nname = 'remote'\nurl = 'https://mcp.example.test'\n\n[mcp.headers]\nAuthorization = 'Bearer secret'\n",
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(user_config_path(&root), fs::Permissions::from_mode(0o644))
.unwrap();
let error = user_config_mcp(&root).unwrap_err().to_string();
assert!(error.contains("chmod 600"), "{error}");
assert!(!error.contains("secret"), "{error}");
fs::set_permissions(user_config_path(&root), fs::Permissions::from_mode(0o600))
.unwrap();
}
assert_eq!(user_config_mcp(&root).unwrap().len(), 1);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn user_config_mcp_is_empty_when_absent_and_unknown_fields_are_rejected() {
let root = std::env::temp_dir().join(format!("structure-config-{}", uuid::Uuid::now_v7()));
fs::create_dir_all(&root).unwrap();
assert_eq!(user_config_mcp(&root).unwrap().len(), 0);
fs::write(
user_config_path(&root),
"[[mcp]]\nname = 'x'\ncommand = '/bin/true'\ntypo = true\n",
)
.unwrap();
let error = user_config_mcp(&root).unwrap_err().to_string();
assert!(error.contains("invalid TOML"), "{error}");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn malformed_user_config_does_not_echo_credential() {
let root = std::env::temp_dir().join(format!("structure-config-{}", uuid::Uuid::now_v7()));
fs::create_dir_all(&root).unwrap();
fs::write(
user_config_path(&root),
"[providers.test]\napi_key = 'secret-value'\ninvalid = [\n",
)
.unwrap();
let error = user_config_key(&root).unwrap_err().to_string();
assert!(error.contains("invalid TOML"));
assert!(!error.contains("secret-value"));
fs::remove_dir_all(root).unwrap();
}
}