use arabica_cli::auth::AuthAction;
use arabica_cli::config::{ResolvedCliConfig, resolve_cli_runtime_config};
use arabica_cli::host::{
HostConfigArgs, LocalRunnerPolicy, build_host_runtime, process_environment,
};
use arabica_cli::interactive::{self, InteractiveOptions};
use arabica_cli::print::{self, OutputFormat, PrintOptions, Resume};
use arabica_cli::sessions::SessionsAction;
use arabica_runner::LocalTool;
use clap::{Args, Parser, Subcommand};
use std::io::IsTerminal;
#[derive(Parser, Debug)]
#[command(name = "arabica", version, about = "Arabica coding agent host")]
struct Cli {
#[command(flatten)]
config: HostConfigArgs,
#[command(subcommand)]
command: Option<Commands>,
#[command(flatten)]
print_args: PrintArgs,
}
#[derive(Args, Debug)]
struct PrintArgs {
#[arg(short = 'p', long = "print", value_name = "TASK")]
print: Option<String>,
#[arg(long, value_enum, default_value_t = OutputFormat::Text)]
output_format: OutputFormat,
#[command(flatten)]
session: SessionArgs,
}
#[derive(Args, Debug, Default)]
struct SessionArgs {
#[arg(long)]
allow_shell: bool,
#[arg(long)]
read_only: bool,
#[arg(long)]
plain: bool,
#[arg(long = "continue", conflicts_with = "resume")]
resume_last: bool,
#[arg(long, value_name = "ID", conflicts_with = "resume_last")]
resume: Option<String>,
#[arg(long = "runner", value_name = "NAME")]
remote_runner: Option<String>,
}
impl SessionArgs {
fn resume_mode(&self) -> Resume {
if self.resume_last {
Resume::Continue
} else if let Some(id) = &self.resume {
Resume::Id(id.clone())
} else {
Resume::None
}
}
fn merge(&mut self, chat: &SessionArgs) -> Result<(), &'static str> {
self.allow_shell |= chat.allow_shell;
self.read_only |= chat.read_only;
self.plain |= chat.plain;
self.resume_last |= chat.resume_last;
if let Some(id) = &chat.resume {
if self.resume.as_ref().is_some_and(|existing| existing != id) {
return Err("--resume was given twice with different session ids");
}
self.resume = Some(id.clone());
}
if self.resume_last && self.resume.is_some() {
return Err("--continue and --resume are mutually exclusive");
}
if let Some(runner) = &chat.remote_runner {
if self
.remote_runner
.as_ref()
.is_some_and(|existing| existing != runner)
{
return Err("--runner was given twice with different runner names");
}
self.remote_runner = Some(runner.clone());
}
Ok(())
}
}
#[derive(Args, Debug)]
struct AcpArgs {
#[arg(long, value_enum, default_value_t = McpProtocol::Auto)]
mcp_protocol: McpProtocol,
}
#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum McpProtocol {
Auto,
Modern,
}
#[derive(Subcommand, Debug)]
enum Commands {
Update(arabica_cli::update::UpdateArgs),
Acp(AcpArgs),
Chat(SessionArgs),
Config {
#[command(subcommand)]
action: Option<arabica_cli::settings::SettingsAction>,
},
Auth {
#[command(subcommand)]
action: AuthAction,
},
Evaluations {
#[command(subcommand)]
action: arabica_cli::evaluation::EvaluationAction,
},
Sessions {
#[command(subcommand)]
action: SessionsAction,
},
Mcp {
#[command(subcommand)]
action: arabica_cli::mcp::commands::McpAction,
},
Models {
#[command(subcommand)]
action: arabica_cli::models::ModelsAction,
},
Runner {
#[command(subcommand)]
action: arabica_cli::runner::RunnerAction,
},
}
#[tokio::main]
async fn main() {
let cli = Cli::parse();
std::process::exit(run(cli).await);
}
async fn run(cli: Cli) -> i32 {
let Cli {
config,
command,
mut print_args,
} = cli;
if let Some(Commands::Chat(chat)) = &command
&& let Err(message) = print_args.session.merge(chat)
{
eprintln!("error: {message}");
return 2;
}
if let Some(Commands::Update(args)) = command {
return if print_args.print.is_some() {
eprintln!("error: -p cannot be combined with the update subcommand");
2
} else {
arabica_cli::update::run(args).await
};
}
if let Some(Commands::Evaluations { action }) = command {
return if print_args.print.is_some() {
eprintln!("error: -p cannot be combined with the evaluations subcommand");
2
} else {
arabica_cli::evaluation::run(action).await
};
}
if let Some(Commands::Sessions { action }) = command {
return if print_args.print.is_some() {
eprintln!("error: -p cannot be combined with the sessions subcommand");
2
} else {
arabica_cli::sessions::run(action)
};
}
if let Some(Commands::Auth { action }) = command {
return if print_args.print.is_some() {
eprintln!("error: -p cannot be combined with the auth subcommand");
2
} else {
arabica_cli::auth::run(action).await
};
}
if let Some(Commands::Mcp { action }) = command {
return if print_args.print.is_some() {
eprintln!("error: -p cannot be combined with the mcp subcommand");
2
} else {
arabica_cli::mcp::commands::run(action).await
};
}
if let Some(Commands::Runner { action }) = command {
return if print_args.print.is_some() {
eprintln!("error: -p cannot be combined with the runner subcommand");
2
} else {
arabica_cli::runner::run(action).await
};
}
if let Some(Commands::Models { action }) = command {
return if print_args.print.is_some() {
eprintln!("error: -p cannot be combined with the models subcommand");
2
} else {
arabica_cli::models::run(action).await
};
}
if let Some(Commands::Config {
action: Some(action),
}) = command
{
return if print_args.print.is_some() {
println!(
"{}",
serde_json::json!({"error": {
"code": "invalid_request",
"message": "The config subcommands cannot be combined with -p.",
"path": []
}})
);
2
} else {
arabica_cli::settings::run(action)
};
}
let resolved = match (|| {
let home = arabica_adapters::default_arabica_home()?;
let cwd = std::env::current_dir()?;
if matches!(command, Some(Commands::Acp(_))) {
arabica_cli::config::resolve_cli_acp_config(&config, &home, &cwd, process_environment)
} else {
resolve_cli_runtime_config(&config, &home, &cwd, process_environment)
}
})() {
Ok(config) => config,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
match (command, &print_args.print) {
(Some(Commands::Acp(_)), Some(_)) => {
eprintln!("error: -p cannot be combined with the acp subcommand");
2
}
(Some(Commands::Acp(args)), None) => {
if args.mcp_protocol == McpProtocol::Modern {
arabica_cli::mcp::require_modern_protocol();
}
run_acp(resolved).await
}
(Some(Commands::Chat(_) | Commands::Config { .. }), Some(_)) => {
eprintln!("error: -p cannot be combined with this subcommand");
2
}
(Some(Commands::Chat(_)), None) => run_chat(resolved, print_args).await,
(Some(Commands::Config { action: None }), None) => match describe_configuration(resolved) {
Ok(()) => 0,
Err(error) => {
eprintln!("error: {error}");
1
}
},
(Some(Commands::Config { action: Some(_) }), None) => {
unreachable!("structured config commands return early")
}
(Some(Commands::Evaluations { .. }), _) => unreachable!("evaluations returns early"),
(Some(Commands::Sessions { .. }), _) => {
unreachable!("Commands::Sessions returns early above")
}
(Some(Commands::Auth { .. }), _) => {
unreachable!("Commands::Auth returns early above")
}
(Some(Commands::Mcp { .. }), _) => {
unreachable!("Commands::Mcp returns early above")
}
(Some(Commands::Models { .. }), _) => {
unreachable!("Commands::Models returns early above")
}
(Some(Commands::Runner { .. }), _) => {
unreachable!("Commands::Runner returns early above")
}
(Some(Commands::Update(_)), _) => unreachable!("update returns early"),
(None, Some(task)) => run_print(resolved, task.clone(), print_args).await,
(None, None) => run_chat(resolved, print_args).await,
}
}
async fn run_chat(resolved: ResolvedCliConfig, args: PrintArgs) -> i32 {
if args.output_format != OutputFormat::Text {
eprintln!("error: --output-format is only available with -p");
return 2;
}
if std::io::stdin().is_terminal() && std::io::stdout().is_terminal() {
arabica_cli::update::schedule_background_update();
}
let options = InteractiveOptions {
allow_shell: args.session.allow_shell,
read_only: args.session.read_only,
resume: args.session.resume_mode(),
remote_runner: args.session.remote_runner.clone(),
};
if !args.session.plain && std::io::stdin().is_terminal() && std::io::stdout().is_terminal() {
match resolved.build_model() {
Ok(model) => {
arabica_cli::tui::run_with_model_configs(
resolved.provider,
model,
resolved.blend_policy,
resolved.model_configs,
options,
)
.await
}
Err(error) => {
eprintln!("error: {error}");
2
}
}
} else {
match resolved.build_model() {
Ok(model) => {
interactive::run_with_model_configs(
resolved.provider,
model,
resolved.blend_policy,
resolved.model_configs,
options,
)
.await
}
Err(error) => {
eprintln!("error: {error}");
2
}
}
}
}
async fn run_acp(resolved: ResolvedCliConfig) -> i32 {
let tool_policy = LocalRunnerPolicy::coding().with_tool(LocalTool::Shell);
match arabica_cli::acp::run(resolved, tool_policy).await {
Ok(()) => 0,
Err(error) => {
eprintln!("error: {error}");
1
}
}
}
async fn run_print(resolved: ResolvedCliConfig, task: String, args: PrintArgs) -> i32 {
let task = match print::resolve_task(&task) {
Ok(task) => task,
Err(error) => {
eprintln!("error: reading task: {error}");
return 2;
}
};
let resume = args.session.resume_mode();
let model = match resolved.build_model() {
Ok(model) => model,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
print::run_with_model(
model,
resolved.blend_policy,
PrintOptions {
task,
output_format: args.output_format,
allow_shell: args.session.allow_shell,
read_only: args.session.read_only,
resume,
remote_runner: args.session.remote_runner,
},
)
.await
}
fn describe_configuration(resolved: ResolvedCliConfig) -> Result<(), Box<dyn std::error::Error>> {
let model = resolved.build_model()?;
let aliases = resolved.models.clone();
let providers = resolved.model_providers.clone();
let model_configs = resolved.model_configs.clone();
let blend_policy = resolved.blend_policy.clone();
let provider_config = resolved.provider;
let api_type = provider_config.api_type;
let base_url = provider_config.base_url.clone();
let model_name = provider_config.model.clone();
let thinking = arabica_cli::config::thinking_level(&provider_config).to_owned();
let runner_root = std::env::current_dir()?;
let arabica_home = arabica_adapters::default_arabica_home()?;
let runtime = build_host_runtime(
model,
&runner_root,
LocalRunnerPolicy::coding(),
&arabica_home,
);
println!("arabica: configuration resolved");
println!(" api_type: {api_type}");
println!(" base_url: {base_url}");
println!(" model: {model_name}");
if !aliases.is_empty() {
println!(" models:");
for (alias, model_id) in aliases {
let provider_name = providers
.get(&alias)
.map(String::as_str)
.unwrap_or("unknown");
let api_type = model_configs
.get(&alias)
.map(|config| config.api_type.to_string())
.unwrap_or_else(|| "unknown".to_owned());
println!(" {alias}: {provider_name}/{model_id} ({api_type})");
}
if let Some(policy) = blend_policy {
println!(
" blend: {} v{} (default {})",
policy.policy_id, policy.version, policy.default_model
);
}
}
println!(" thinking: {thinking}");
println!(" runner_root: {}", runner_root.display());
let home = arabica_adapters::default_arabica_home()?;
println!(
" user config: {}",
arabica_cli::config::user_config_path(&home).display()
);
println!(
" workspace: {}",
arabica_cli::config::workspace_config_path(&home, &runner_root).display()
);
println!(
" tools: {}",
runtime
.tools()
.iter()
.map(|tool| tool.name.as_str())
.collect::<Vec<_>>()
.join(", ")
);
println!(" next: run `arabica` for interactive chat or `arabica -p \"task\"` for scripting");
Ok(())
}