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>,
}
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,
} = 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
}
}
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 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,
}
}
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)?;
}
let checks: [(bool, Pick, &str); 8] = [
(
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)",
),
];
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))?
))
}