use serde_json::Value;
#[derive(Debug, Clone, Default)]
pub struct LaunchOptions {
pub reasoning_effort: Option<String>,
pub max_output_tokens: Option<u64>,
pub temperature: Option<f64>,
pub mcp_config: Option<String>,
pub strict_mcp_config: bool,
pub additional_directories: Vec<String>,
pub attachments: Vec<String>,
pub json_schema: Option<String>,
pub json_schema_file: Option<String>,
pub system_prompt_file: Option<String>,
pub append_system_prompt_file: Option<String>,
pub gateway: Option<GatewayOptions>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GatewayOptions {
pub base_url: Option<String>,
pub router: Option<String>,
pub token_env: String,
}
impl GatewayOptions {
pub fn with_base_url(base_url: impl Into<String>, token_env: impl Into<String>) -> Self {
Self {
base_url: Some(base_url.into()),
router: None,
token_env: token_env.into(),
}
}
pub fn with_router(router: impl Into<String>, token_env: impl Into<String>) -> Self {
Self {
base_url: None,
router: Some(router.into()),
token_env: token_env.into(),
}
}
}
pub const ROUTER_SERVICE_PATHS: &[(&str, &str)] = &[
("claude", "/api/services/anthropic"),
("codex", "/api/services/codex/v1"),
];
pub const CODEX_GATEWAY_PROVIDER_ID: &str = "agent_commander_gateway";
pub const CLAUDE_GATEWAY_UNSET_ENV: &[&str] = &[
"ANTHROPIC_AUTH_TOKEN",
"ANTHROPIC_API_KEY",
"CLAUDE_CODE_USE_BEDROCK",
"CLAUDE_CODE_USE_VERTEX",
"CLAUDE_CODE_USE_FOUNDRY",
];
fn normalize_gateway_url(value: &str, name: &str) -> Result<String, String> {
let error = || format!("{name} must be an http(s) URL without credentials, query or fragment");
let lower = value.to_ascii_lowercase();
let rest = if lower.starts_with("https://") {
&value[8..]
} else if lower.starts_with("http://") {
&value[7..]
} else {
return Err(error());
};
let authority = rest.split('/').next().unwrap_or_default();
let host = authority
.rsplit_once(':')
.map_or(authority, |(host, _)| host);
if host.is_empty()
|| authority.contains('@')
|| value.contains('?')
|| value.contains('#')
|| value.chars().any(char::is_whitespace)
{
return Err(error());
}
Ok(value.trim_end_matches('/').to_string())
}
pub fn normalize_gateway(
gateway: &GatewayOptions,
tool: Option<&str>,
) -> Result<GatewayOptions, String> {
if gateway.base_url.is_some() == gateway.router.is_some() {
return Err(
"gateway needs exactly one of baseUrl (--gateway-base-url) or router (--gateway-router)"
.to_string(),
);
}
if !crate::tools::shell::is_valid_env_name(&gateway.token_env) {
return Err("gateway.tokenEnv (--gateway-token-env) must name an environment variable ([A-Za-z_][A-Za-z0-9_]*)".to_string());
}
let router = gateway
.router
.as_deref()
.map(|url| normalize_gateway_url(url, "gateway.router (--gateway-router)"))
.transpose()?;
let base_url = match (&router, tool) {
(Some(origin), Some(tool)) => ROUTER_SERVICE_PATHS
.iter()
.find(|(name, _)| *name == tool)
.map(|(_, path)| format!("{origin}{path}")),
_ => gateway
.base_url
.as_deref()
.map(|url| normalize_gateway_url(url, "gateway.baseUrl (--gateway-base-url)"))
.transpose()?,
};
Ok(GatewayOptions {
base_url,
router,
token_env: gateway.token_env.clone(),
})
}
pub fn check_gateway_token(
gateway: Option<&GatewayOptions>,
env: &[(String, String)],
) -> Result<(), String> {
match gateway {
Some(gateway)
if !env
.iter()
.any(|(key, value)| key == &gateway.token_env && !value.is_empty()) =>
{
Err(format!(
"gateway.tokenEnv: environment variable {} is not set or empty",
gateway.token_env
))
}
_ => Ok(()),
}
}
pub fn resolve_gateway(gateway: &GatewayOptions, tool: &str) -> Result<(String, String), String> {
let normalized = normalize_gateway(gateway, Some(tool))?;
match normalized.base_url {
Some(base_url) => Ok((base_url, normalized.token_env)),
None => Err(format!(
"Tool \"{tool}\" has no link-assistant/router service path; pass gateway.baseUrl (--gateway-base-url) instead."
)),
}
}
pub fn claude_gateway_settings(token_env: &str) -> String {
serde_json::json!({ "apiKeyHelper": format!("printenv {token_env}") }).to_string()
}
pub fn codex_gateway_overrides(base_url: &str, token_env: &str) -> Vec<String> {
let prefix = format!("model_providers.{CODEX_GATEWAY_PROVIDER_ID}");
let toml = |value: &str| Value::String(value.to_string()).to_string();
vec![
format!("model_provider={}", toml(CODEX_GATEWAY_PROVIDER_ID)),
format!("{prefix}.name={}", toml("agent-commander gateway")),
format!("{prefix}.base_url={}", toml(base_url)),
format!("{prefix}.env_key={}", toml(token_env)),
format!("{prefix}.wire_api={}", toml("responses")),
]
}
impl PartialEq for LaunchOptions {
fn eq(&self, other: &Self) -> bool {
let Self {
reasoning_effort,
max_output_tokens,
temperature,
mcp_config,
strict_mcp_config,
additional_directories,
attachments,
json_schema,
json_schema_file,
system_prompt_file,
append_system_prompt_file,
gateway,
} = self;
let same_temperature = match (*temperature, other.temperature) {
(None, None) => true,
(Some(a), Some(b)) => {
a.partial_cmp(&b).is_some_and(std::cmp::Ordering::is_eq)
|| (a.is_nan() && b.is_nan())
}
_ => false,
};
same_temperature
&& reasoning_effort == &other.reasoning_effort
&& max_output_tokens == &other.max_output_tokens
&& mcp_config == &other.mcp_config
&& strict_mcp_config == &other.strict_mcp_config
&& additional_directories == &other.additional_directories
&& attachments == &other.attachments
&& json_schema == &other.json_schema
&& json_schema_file == &other.json_schema_file
&& system_prompt_file == &other.system_prompt_file
&& append_system_prompt_file == &other.append_system_prompt_file
&& gateway == &other.gateway
}
}
impl Eq for LaunchOptions {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LaunchCapabilities {
pub reasoning_effort: bool,
pub reasoning_efforts: Option<&'static [&'static str]>,
pub max_output_tokens: bool,
pub temperature: bool,
pub mcp_config: bool,
pub strict_mcp_config: bool,
pub additional_directories: bool,
pub attachments: bool,
pub json_schema: bool,
pub gateway: bool,
}
pub const CLAUDE_REASONING_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];
pub const CODEX_REASONING_EFFORTS: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh"];
const TOOLS: &[&str] = &["claude", "codex", "opencode", "agent", "gemini", "qwen"];
pub(crate) const MAX_OUTPUT_TOKENS_ERROR: &str =
"--max-output-tokens must be a positive safe integer";
pub(crate) const TEMPERATURE_ERROR: &str = "--temperature must be a finite non-negative number";
pub(crate) fn validate_max_output_tokens(value: u64) -> Result<(), &'static str> {
if (1..=9_007_199_254_740_991).contains(&value) {
Ok(())
} else {
Err(MAX_OUTPUT_TOKENS_ERROR)
}
}
pub(crate) fn validate_temperature(value: f64) -> Result<(), &'static str> {
if value.is_finite() && value >= 0.0 {
Ok(())
} else {
Err(TEMPERATURE_ERROR)
}
}
pub fn launch_capabilities(tool: &str) -> LaunchCapabilities {
let (effort, efforts, mcp, strict, dirs, attachments, json_schema) = match tool {
"claude" => (
true,
Some(CLAUDE_REASONING_EFFORTS),
true,
true,
true,
false,
true,
),
"codex" => (
true,
Some(CODEX_REASONING_EFFORTS),
true,
false,
true,
true,
true,
),
"opencode" => (true, None, false, false, false, true, false),
"gemini" => (false, None, false, false, true, false, false),
"qwen" => (false, None, true, false, true, false, true),
_ => (false, None, false, false, false, false, false),
};
LaunchCapabilities {
reasoning_effort: effort,
reasoning_efforts: efforts,
max_output_tokens: matches!(tool, "claude" | "opencode"),
temperature: tool == "agent",
mcp_config: mcp,
strict_mcp_config: strict,
additional_directories: dirs,
attachments,
json_schema,
gateway: matches!(tool, "claude" | "codex"),
}
}
pub fn check_launch_options_supported(tool: &str, launch: &LaunchOptions) -> Result<(), String> {
check_launch_options_against(tool, launch, &launch_capabilities(tool))
}
pub fn check_launch_options_against(
tool: &str,
launch: &LaunchOptions,
capabilities: &LaunchCapabilities,
) -> Result<(), String> {
type Pick = fn(&LaunchCapabilities) -> bool;
if let Some(value) = launch.max_output_tokens {
validate_max_output_tokens(value)?;
}
if let Some(value) = launch.temperature {
validate_temperature(value)?;
}
if let Some(gateway) = &launch.gateway {
normalize_gateway(gateway, Some(tool))?;
}
let checks: [(bool, Pick, &str); 9] = [
(
launch.max_output_tokens.is_some(),
|c| c.max_output_tokens,
"an output token budget (--max-output-tokens)",
),
(
launch.temperature.is_some(),
|c| c.temperature,
"sampling temperature (--temperature)",
),
(
launch.reasoning_effort.is_some(),
|c| c.reasoning_effort,
"reasoning effort (--reasoning-effort)",
),
(
launch.mcp_config.is_some(),
|c| c.mcp_config,
"MCP server configuration (--mcp-config)",
),
(
launch.strict_mcp_config,
|c| c.strict_mcp_config,
"strict MCP configuration (--strict-mcp-config)",
),
(
!launch.additional_directories.is_empty(),
|c| c.additional_directories,
"additional directories (--add-dir)",
),
(
!launch.attachments.is_empty(),
|c| c.attachments,
"file attachments (--attach)",
),
(
launch.json_schema.is_some(),
|c| c.json_schema,
"structured output (--json-schema)",
),
(
launch.gateway.is_some(),
|c| c.gateway,
"an API gateway (--gateway-base-url / --gateway-router)",
),
];
for (requested, pick, label) in checks {
if requested && !pick(capabilities) {
let supporting: Vec<&str> = TOOLS
.iter()
.copied()
.filter(|name| pick(&launch_capabilities(name)))
.collect();
return Err(format!(
"Tool \"{}\" does not support {}. Choose one of: {}; or omit the option.",
tool,
label,
supporting.join(", ")
));
}
}
Ok(())
}
pub fn normalize_reasoning_effort(reasoning_effort: &str) -> String {
assert!(
!reasoning_effort.is_empty()
&& reasoning_effort
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
"Invalid reasoning effort \"{}\". Use a level name such as low, medium or high.",
reasoning_effort
);
reasoning_effort.to_string()
}
pub fn json_schema_arg(json_schema: &str) -> String {
let schema: Value = serde_json::from_str(json_schema)
.unwrap_or_else(|error| panic!("jsonSchema is not valid JSON: {error}"));
assert!(
schema.is_object(),
"jsonSchema must be a JSON Schema object or its JSON text"
);
schema.to_string()
}
fn push_paths(args: &mut Vec<String>, flag: &str, paths: &[String], name: &str) {
for path in paths {
assert!(!path.is_empty(), "{name} must not be empty");
args.push(flag.to_string());
args.push(path.clone());
}
}
pub fn push_directories(args: &mut Vec<String>, flag: &str, directories: &[String]) {
push_paths(args, flag, directories, "additional directories");
}
pub fn push_attachments(args: &mut Vec<String>, flag: &str, attachments: &[String]) {
push_paths(args, flag, attachments, "attachments");
}
fn toml_key(key: &str) -> String {
if !key.is_empty()
&& key
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
key.to_string()
} else {
Value::String(key.to_string()).to_string()
}
}
pub fn to_toml_value(value: &Value) -> Result<String, String> {
match value {
Value::String(_) | Value::Number(_) | Value::Bool(_) => Ok(value.to_string()),
Value::Array(items) => {
let parts: Result<Vec<String>, String> = items.iter().map(to_toml_value).collect();
Ok(format!("[{}]", parts?.join(", ")))
}
Value::Object(map) => {
let mut parts = Vec::new();
for (key, item) in map.iter().filter(|(_, item)| !item.is_null()) {
parts.push(format!("{} = {}", toml_key(key), to_toml_value(item)?));
}
Ok(format!("{{{}}}", parts.join(", ")))
}
Value::Null => Err("Cannot encode null as a TOML value".to_string()),
}
}
pub fn codex_mcp_servers_override(mcp_config: &str) -> Result<String, String> {
if !mcp_config.trim_start().starts_with('{') {
return Err("Tool \"codex\" takes MCP servers as config overrides, not a file path. Pass mcpConfig as inline JSON.".to_string());
}
let config: Value = serde_json::from_str(mcp_config)
.map_err(|error| format!("Invalid mcpConfig JSON: {error}"))?;
let servers = config
.get("mcpServers")
.and_then(Value::as_object)
.ok_or_else(|| "mcpConfig must contain an mcpServers object".to_string())?;
let mut table = serde_json::Map::new();
for (name, server) in servers {
let mut server = server
.as_object()
.cloned()
.ok_or_else(|| format!("MCP server \"{name}\" must be an object"))?;
server.remove("type");
if let Some(headers) = server.remove("headers") {
server.insert("http_headers".to_string(), headers);
}
table.insert(name.clone(), Value::Object(server));
}
Ok(format!(
"mcp_servers={}",
to_toml_value(&Value::Object(table))?
))
}