arabica-cli 0.13.1

Arabica: a terminal coding agent with a fullscreen TUI, ACP support for Zed, and one-shot runs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! `arabica`: interactive terminal host, ACP agent, and one-shot runner.

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 {
    /// Run one task non-interactively and exit. Pass "-" to read the task
    /// from stdin instead of the argument.
    #[arg(short = 'p', long = "print", value_name = "TASK")]
    print: Option<String>,
    /// Output format for -p: "text" (default; stdout is only the final
    /// answer) or "jsonl" (stdout is one JSON event per line, live).
    #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
    output_format: OutputFormat,
    #[command(flatten)]
    session: SessionArgs,
}

/// Session flags accepted both before a task (`arabica --plain`) and after
/// the chat subcommand (`arabica chat --plain`).
#[derive(Args, Debug, Default)]
struct SessionArgs {
    /// Allow terminal chat or -p to run the shell tool. Off by default.
    /// Interactive chat asks before execution; -p runs it outright.
    #[arg(long)]
    allow_shell: bool,
    /// Restrict terminal chat or -p to read-only tools.
    #[arg(long)]
    read_only: bool,
    /// Use the simple line-based terminal instead of the full-screen TUI.
    #[arg(long)]
    plain: bool,
    /// Continue the most recent session in this workspace instead
    /// of starting a new one. Mutually exclusive with --resume.
    #[arg(long = "continue", conflicts_with = "resume")]
    resume_last: bool,
    /// Resume a specific session by id instead of starting a new one.
    /// Mutually exclusive with --continue. See `arabica sessions list`.
    #[arg(long, value_name = "ID", conflicts_with = "resume_last")]
    resume: Option<String>,
    /// Run the built-in tools on the remote runner configured as
    /// [runners.NAME] in config.toml instead of in this process.
    #[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
        }
    }

    /// Combines flags given before and after `chat`; clap checks each level
    /// on its own, so the cross-level conflicts are checked here.
    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 {
    /// MCP lifecycle for HTTP and stdio servers: "auto" falls back to the
    /// legacy initialize handshake only when a server proves it is legacy;
    /// "modern" requires MCP 2026-07-28 and never falls back.
    #[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 {
    /// Install the latest signed release or configure automatic CLI updates.
    Update(arabica_cli::update::UpdateArgs),
    /// Run as an Agent Client Protocol v1 agent over stdio (for editors like Zed).
    Acp(AcpArgs),
    /// Start an interactive terminal session (also the default).
    Chat(SessionArgs),
    /// Show resolved configuration, or inspect and edit config.toml as JSON.
    Config {
        #[command(subcommand)]
        action: Option<arabica_cli::settings::SettingsAction>,
    },
    /// Manage saved API credentials.
    Auth {
        #[command(subcommand)]
        action: AuthAction,
    },
    /// Query persisted evaluation reports without a model provider.
    Evaluations {
        #[command(subcommand)]
        action: arabica_cli::evaluation::EvaluationAction,
    },
    /// Inspect sessions stored under $ARABICA_HOME.
    Sessions {
        #[command(subcommand)]
        action: SessionsAction,
    },
    /// Authorize remote MCP servers that use OAuth.
    Mcp {
        #[command(subcommand)]
        action: arabica_cli::mcp::commands::McpAction,
    },
    /// Manage, discover, and sync models from upstream providers.
    Models {
        #[command(subcommand)]
        action: arabica_cli::models::ModelsAction,
    },
    /// Serve workspaces to a remote agent loop (Loop–Runner Protocol).
    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;
    }

    // These commands need no working model provider.
    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 {
    // Shell is opt-in at the policy layer (`LocalRunnerPolicy::coding` does
    // not include it: it is the tool with no confinement, the one place the
    // permission gate is the only boundary). ACP is exactly the surface
    // built to gate it -- the client asks the user before every call
    // (`acp/permission.rs`'s default policy always routes `shell` through
    // `session/request_permission`) -- so a coding agent that can never
    // build, test, or run `git` would not be a meaningfully useful trade
    // for that safety.
    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
}

/// `arabica config`: report the resolved provider without starting a run.
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;
    // Never printed: the api_key field itself is not touched below.
    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(())
}