Skip to main content

rpi_cli/
args.rs

1//! CLI argument parsing + help text. Mirrors the TS
2//! The CLI arg surface, scoped
3//! to the flags the v1 Rust CLI honors.
4//!
5//! The TS parser is a hand-rolled positional/flag loop (no `yargs`/`commander`
6//! dep) that collects `messages`, `@file` attachments, known flags, and a map
7//! of *unknown* `--flags` (for extensions to claim later). This port keeps the
8//! same shape so the help text and flag semantics line up 1:1 with the
9//! reference. Unknown long flags are retained in [`Args::unknown_flags`] so a
10//! native extension can claim and consume its own CLI options after loading.
11//!
12//! Divergences from the TS parser (all deliberate v1 scope cuts, documented in
13//! the initial port notes (retired)):
14//! - `--mode rpc`,
15//!   `--fork`, `--approve`/`-na`,
16//!   `--extension`/`-e`, `--skill`, and `--prompt-template` are recognized but
17//!   resource discovery follows the supported project/global directories.
18//!   flags are handled by the Rust loader; remaining compatibility flags are
19//!   accepted with a warning.
20//! - `--thinking` is typed via [`ThinkingLevel`] from `rpi_ai` (the TS parser
21//!   validates against the same string set).
22//! - `--print`/`-p` may consume a following positional as its prompt (the TS
23//!   parser's `next !== undefined && !startsWith('@')` heuristic) — preserved.
24
25use std::collections::BTreeMap;
26use std::path::PathBuf;
27use std::time::Duration;
28
29use rpi_ai::ThinkingLevel;
30
31/// upstream's process-wide offline flag. The CLI normalizes a truthy value
32/// to `1` before dispatch so early subcommands and the regular app path share
33/// the same network gate.
34pub(crate) const RPI_OFFLINE_ENV: &str = "RPI_OFFLINE";
35
36/// Match upstream's environment-flag contract exactly: empty values and
37/// values other than `1`, `true`, or `yes` are false; words are ASCII
38/// case-insensitive.
39pub(crate) fn is_truthy_env_flag(value: Option<&str>) -> bool {
40    value.is_some_and(|value| {
41        value == "1" || value.eq_ignore_ascii_case("true") || value.eq_ignore_ascii_case("yes")
42    })
43}
44
45pub(crate) fn offline_env_enabled() -> bool {
46    is_truthy_env_flag(std::env::var(RPI_OFFLINE_ENV).ok().as_deref())
47}
48
49pub(crate) fn offline_mode_enabled(cli_offline: bool) -> bool {
50    cli_offline || offline_env_enabled()
51}
52
53/// Resolve and normalize offline mode before top-level subcommand dispatch.
54/// This mirrors upstream setting `RPI_OFFLINE=1` after either input enables it,
55/// allowing downstream code to use the same process-wide gate.
56pub(crate) fn normalize_offline_mode(args: &[String]) -> bool {
57    let enabled = offline_mode_enabled(args.iter().any(|arg| arg == "--offline"));
58    if enabled {
59        std::env::set_var(RPI_OFFLINE_ENV, "1");
60    }
61    enabled
62}
63
64/// Drop the global `--offline` flag before an early-dispatched subcommand parses
65/// its own arguments (`rpi update --offline` must not see it as a stray arg).
66pub(crate) fn without_offline_flag(args: &[String]) -> Vec<String> {
67    args.iter()
68        .filter(|arg| arg.as_str() != "--offline")
69        .cloned()
70        .collect()
71}
72
73/// Output mode. Mirrors rpi's text/json/rpc modes.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
75pub enum Mode {
76    #[default]
77    Text,
78    Json,
79    Rpc,
80}
81
82/// Interactive TUI presentation mode. `fullscreen` uses the alternate screen
83/// buffer; `regular` renders into the terminal's normal scrollback.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum TuiMode {
86    Fullscreen,
87    Regular,
88}
89
90const fn default_tui_mode_for(is_macos: bool) -> TuiMode {
91    if is_macos {
92        TuiMode::Regular
93    } else {
94        TuiMode::Fullscreen
95    }
96}
97
98impl Default for TuiMode {
99    fn default() -> Self {
100        default_tui_mode_for(cfg!(target_os = "macos"))
101    }
102}
103
104/// The parsed argument set. Mirrors TS `Args`. Unknown long flags are retained
105/// for extension consumption; unknown short flags remain hard errors.
106#[derive(Debug, Clone, Default)]
107pub struct Args {
108    pub provider: Option<String>,
109    pub model: Option<String>,
110    pub api_key: Option<String>,
111    /// `--base-url` — overrides `ANTHROPIC_BASE_URL` + each model's base URL,
112    /// for third-party Anthropic-compatible gateways/proxies.
113    pub base_url: Option<String>,
114    /// `--timeout <seconds>` overrides the deadline for each LLM API request.
115    pub timeout: Option<Duration>,
116    /// Maximum silence between streamed response bytes; zero disables it.
117    pub stream_idle_timeout: Option<Duration>,
118    pub system_prompt: Option<String>,
119    pub append_system_prompt: Vec<String>,
120    /// `--theme` — built-in theme name or a theme file path.
121    pub theme: Option<String>,
122    pub thinking: Option<ThinkingLevel>,
123
124    pub print: bool,
125    pub mode: Mode,
126    /// `--tui-mode regular|fullscreen` controls the interactive terminal
127    /// buffer. macOS defaults to regular so native selection and terminal
128    /// scrollback remain available together; other platforms use fullscreen.
129    pub tui_mode: TuiMode,
130
131    /// `--list-models [search]`: list the merged model catalog and exit.
132    /// `Some("")` represents the bare flag; `None` means absent.
133    pub list_models: Option<String>,
134    /// `--offline`: disable best-effort startup network checks.
135    pub offline: bool,
136    /// `--export <session-file>`: export a JSONL session to HTML (or copy it
137    /// when the destination ends in `.jsonl`).
138    pub export: Option<PathBuf>,
139    /// Explicit project trust override. `--approve` trusts the current
140    /// project; `--no-approve` keeps project-local resources disabled.
141    pub trust_override: Option<bool>,
142
143    pub continue_session: bool,
144    pub resume: bool,
145    pub session: Option<String>,
146    /// `--session-id <id>`: use the EXACT project session id, creating it if
147    /// missing (pi `--session-id`). Unlike `--session` (partial match), this
148    /// is an exact-id open-or-create.
149    pub session_id: Option<String>,
150    /// `--fork <path|id>`: fork the given session into a new one and start in
151    /// the fork (pi `--fork`).
152    pub fork: Option<String>,
153    /// `--models <patterns>`: comma-separated model patterns for the Ctrl+P
154    /// cycle (globs/fuzzy in pi; v1 writes the matched ids to settings.json's
155    /// scopedModels — the same set /scoped-models edits). Empty = all models.
156    pub models: Option<Vec<String>>,
157    pub session_dir: Option<PathBuf>,
158    pub no_session: bool,
159    pub name: Option<String>,
160
161    pub tools: Option<Vec<String>>,
162    pub exclude_tools: Option<Vec<String>>,
163    pub no_tools: bool,
164    pub no_builtin_tools: bool,
165
166    /// `--no-skills`/`-ns`: skip skill discovery + the `<available_skills>`
167    /// system-prompt listing.
168    pub no_skills: bool,
169    /// `--no-prompt-templates`/`-np`: skip prompt-template discovery (templates
170    /// are on-demand only; this suppresses populating the resource registry).
171    pub no_prompt_templates: bool,
172    /// `--no-context-files`/`-nc`: skip context-file (`AGENTS.md`/`CLAUDE.md`)
173    /// discovery + the `<project_context>` system-prompt block.
174    pub no_context_files: bool,
175    /// `--no-extensions`/`-ne`: skip Rust cdylib extension loading.
176    /// Honored by `session.rs`: when set, no extension directory is scanned.
177    pub no_extensions: bool,
178    /// `--no-themes`: disable custom theme discovery and loading.
179    /// Built-in presets remain available unless a custom `--theme` is given.
180    pub no_themes: bool,
181    /// `--extensions-dir`/`-ed`: an extra directory to scan for cdylib plugins
182    /// (`.dll`/`.so`/`.dylib`), in addition to project `.rpi/extensions`
183    /// and global
184    /// `agent_dir()/extensions` defaults. May be repeated; scanned after
185    /// the defaults (so a same-named tool in a default dir wins first, mirroring
186    /// pi's registration order). `RPI_EXTENSIONS_DIR` (colon-separated on Unix,
187    /// semicolon on Windows) provides the same list via env.
188    pub extensions_dir: Vec<PathBuf>,
189    /// `--extension`/`-e <path>`: load an explicit extension cdylib file (may
190    /// be repeated). Loaded in addition to the discovered dirs.
191    pub extension: Vec<PathBuf>,
192    /// `--skill <path>`: load an explicit skill file or directory (repeated).
193    pub skill: Vec<PathBuf>,
194    /// `--prompt-template <path>`: load an explicit prompt-template file or
195    /// directory (repeated).
196    pub prompt_template: Vec<PathBuf>,
197
198    /// `--local-only`: load only explicitly supplied extension paths.
199    pub dev_local_only: bool,
200    /// `--package-only` / `--project-only`: load project resources and
201    /// extensions from the active project's settings, excluding global ones.
202    pub project_only: bool,
203
204    pub verbose: bool,
205    pub help: bool,
206    pub version: bool,
207
208    /// `--debug-system-prompt`: print the resolved system-prompt sections
209    /// (base, append, context, skills listing) + resource counts to stderr at
210    /// harness build time, then proceed normally. A verification affordance for
211    /// resource-discovery (Part A) — lets a smoke confirm `<available_skills>` +
212    /// `<project_context>` + appended text reached the prompt without a full
213    /// round-trip parse. Mirrors the plan's "add --debug-system-prompt if absent".
214    pub debug_system_prompt: bool,
215
216    /// Positional prompt text (one or more messages). Mirrors TS `messages`.
217    pub messages: Vec<String>,
218    /// `@file` attachments (prefix stripped), as raw paths for the caller to
219    /// expand. Mirrors TS `fileArgs`.
220    pub file_args: Vec<PathBuf>,
221
222    /// Extension-declared or otherwise unknown long flags. Values are either
223    /// JSON booleans (a bare flag) or strings (a flag with a value), matching
224    /// Pi's `unknownFlags` contract so an extension can claim its own options.
225    pub unknown_flags: BTreeMap<String, serde_json::Value>,
226    /// Warnings about recognized-but-ignored flags (v1 scope cuts). Surfaced
227    /// to the user on startup when `--verbose`.
228    pub ignored: Vec<String>,
229    /// Hard parse errors (unknown short flags, missing values). Non-empty ⇒
230    /// `main` prints them + help and exits non-zero.
231    pub errors: Vec<String>,
232}
233
234/// The canonical valid `--thinking` level strings, in level order. Mirrors TS
235/// `VALID_THINKING_LEVELS`.
236pub use rpi_runtime::thinking::VALID_THINKING_LEVELS;
237
238/// Parse a thinking-level string. Mirrors TS `isValidThinkingLevel`.
239pub use rpi_runtime::thinking::parse_thinking_level;
240
241/// `@file`-argument helper mirroring the TS parser: a leading `@` marks a file
242/// attachment (the `@` is stripped).
243fn file_arg(arg: &str) -> Option<PathBuf> {
244    if let Some(rest) = arg.strip_prefix('@') {
245        // Reject the bare `@` (TS keeps it as a message; we treat it as one).
246        if rest.is_empty() {
247            None
248        } else {
249            Some(PathBuf::from(rest))
250        }
251    } else {
252        None
253    }
254}
255
256/// Parse `argv` (excluding the program name). Mirrors TS `parseArgs`.
257///
258/// Long flags accept `--name value` or `--name=value` (the TS parser only
259/// handles `--name=value` for *unknown* flags; we extend it to known flags for
260/// ergonomics). Short flags use a single leading `-`.
261pub fn parse_args(args: &[String]) -> Args {
262    let mut result = Args::default();
263    result.offline = offline_env_enabled();
264    // `RPI_EXTENSIONS_DIR` env: an extra list of plugin dirs prepended to any
265    // `--extensions-dir` flags. Semicolon-separated on Windows, colon-separated
266    // on Unix (PATH-style). Empty entries skipped. `--no-extensions` still wins.
267    if let Ok(raw) = std::env::var("RPI_EXTENSIONS_DIR") {
268        if !raw.is_empty() {
269            let sep = if cfg!(windows) { ';' } else { ':' };
270            for part in raw.split(sep) {
271                let trimmed = part.trim();
272                if !trimmed.is_empty() {
273                    result.extensions_dir.push(PathBuf::from(trimmed));
274                }
275            }
276        }
277    }
278    let mut i = 0;
279    while i < args.len() {
280        let arg = args[i].clone();
281        // Peel an inline `--flag=value` (long flags only — short flags never use
282        // `=`) so the match below compares bare flag names. `inline` holds the
283        // RHS for `take_value` to consume in place of the next argv token.
284        let (flag_key, inline) = if arg.starts_with("--") {
285            match arg.find('=') {
286                Some(eq) => (arg[..eq].to_string(), Some(arg[eq + 1..].to_string())),
287                None => (arg.clone(), None),
288            }
289        } else {
290            (arg.clone(), None)
291        };
292
293        // Take a value: prefer the inline `--flag=value`, else the next argv
294        // token (when it isn't flag-shaped). Advances `i` past a consumed token.
295        // (For unknown-flag diagnostics the closing arm reads `flag_key` itself.)
296        let mut take_value = |result: &mut Args, _flag: &str| -> Option<String> {
297            if let Some(v) = inline.clone() {
298                return Some(v);
299            }
300            if i + 1 < args.len() {
301                let next = &args[i + 1];
302                if !next.starts_with('-') || next == "-" {
303                    i += 1;
304                    return Some(args[i].clone());
305                }
306            }
307            result.errors.push(format!("{flag_key} requires a value"));
308            None
309        };
310
311        match flag_key.as_str() {
312            "--help" | "-h" => result.help = true,
313            "--version" | "-v" => result.version = true,
314            "--print" | "-p" => {
315                result.print = true;
316                // `-p` may consume the following positional as the prompt
317                // (TS heuristic: next is present, doesn't start with `@`, and
318                // isn't a flag — except `---` which TS lets through; we keep
319                // the simple `!@` && `!-` form).
320                if i + 1 < args.len() {
321                    let next = &args[i + 1];
322                    if !next.starts_with('@') && !next.starts_with('-') {
323                        i += 1;
324                        result.messages.push(args[i].clone());
325                    }
326                }
327            }
328            "--mode" => {
329                if let Some(v) = take_value(&mut result, "--mode") {
330                    result.mode = match v.as_str() {
331                        "text" => Mode::Text,
332                        "json" => Mode::Json,
333                        "rpc" => Mode::Rpc,
334                        other => {
335                            result.errors.push(format!(
336                                "Invalid --mode \"{other}\". Valid: text, json, rpc"
337                            ));
338                            Mode::Text
339                        }
340                    };
341                }
342            }
343            "--tui-mode" => {
344                if let Some(v) = take_value(&mut result, "--tui-mode") {
345                    result.tui_mode = match v.to_ascii_lowercase().as_str() {
346                        "regular" => TuiMode::Regular,
347                        "fullscreen" => TuiMode::Fullscreen,
348                        other => {
349                            result.errors.push(format!(
350                                "Invalid --tui-mode \"{other}\". Valid: regular, fullscreen"
351                            ));
352                            TuiMode::Fullscreen
353                        }
354                    };
355                }
356            }
357            "--continue" | "-c" => result.continue_session = true,
358            "--resume" | "-r" => result.resume = true,
359            "--no-session" => result.no_session = true,
360            "--no-tools" | "-nt" => result.no_tools = true,
361            "--no-builtin-tools" | "-nbt" => result.no_builtin_tools = true,
362            "--no-skills" | "-ns" => result.no_skills = true,
363            "--no-prompt-templates" | "-np" => result.no_prompt_templates = true,
364            "--no-context-files" | "-nc" => result.no_context_files = true,
365            "--no-extensions" | "-ne" => result.no_extensions = true,
366            "--local-only" => result.dev_local_only = true,
367            "--package-only" | "--project-only" => result.project_only = true,
368            "--extensions-dir" | "-ed" => {
369                if let Some(v) = take_value(&mut result, &flag_key) {
370                    result.extensions_dir.push(PathBuf::from(v));
371                }
372            }
373            "--verbose" => result.verbose = true,
374            "--debug-system-prompt" => result.debug_system_prompt = true,
375            "--provider" => result.provider = take_value(&mut result, "--provider"),
376            "--model" => result.model = take_value(&mut result, "--model"),
377            "--api-key" => result.api_key = take_value(&mut result, "--api-key"),
378            "--base-url" => result.base_url = take_value(&mut result, "--base-url"),
379            "--timeout" => {
380                if let Some(v) = take_value(&mut result, "--timeout") {
381                    match v.parse::<u64>() {
382                        Ok(seconds) if seconds > 0 => {
383                            result.timeout = Some(Duration::from_secs(seconds));
384                        }
385                        _ => result.errors.push(format!(
386                            "Invalid --timeout \"{v}\". Expected a positive integer number of seconds"
387                        )),
388                    }
389                }
390            }
391            "--stream-idle-timeout" => {
392                if let Some(v) = take_value(&mut result, "--stream-idle-timeout") {
393                    match v.parse::<u64>() {
394                        Ok(seconds) => result.stream_idle_timeout = Some(Duration::from_secs(seconds)),
395                        Err(_) => result.errors.push(format!(
396                            "Invalid --stream-idle-timeout \"{v}\". Expected a non-negative integer number of seconds (0 disables it)"
397                        )),
398                    }
399                }
400            }
401            "--system-prompt" => result.system_prompt = take_value(&mut result, "--system-prompt"),
402            "--append-system-prompt" => {
403                if let Some(v) = take_value(&mut result, "--append-system-prompt") {
404                    result.append_system_prompt.push(v);
405                }
406            }
407            "--name" | "-n" => result.name = take_value(&mut result, "--name"),
408            "--session" => result.session = take_value(&mut result, "--session"),
409            "--session-id" => result.session_id = take_value(&mut result, "--session-id"),
410            "--fork" => result.fork = take_value(&mut result, "--fork"),
411            "--models" => {
412                if let Some(v) = take_value(&mut result, &flag_key) {
413                    result.models = Some(split_csv(&v));
414                }
415            }
416            "--extension" | "-e" => {
417                if let Some(v) = take_value(&mut result, &flag_key) {
418                    result.extension.push(PathBuf::from(v));
419                }
420            }
421            "--skill" => {
422                if let Some(v) = take_value(&mut result, &flag_key) {
423                    result.skill.push(PathBuf::from(v));
424                }
425            }
426            "--prompt-template" => {
427                if let Some(v) = take_value(&mut result, &flag_key) {
428                    result.prompt_template.push(PathBuf::from(v));
429                }
430            }
431            "--session-dir" => {
432                if let Some(v) = take_value(&mut result, "--session-dir") {
433                    result.session_dir = Some(PathBuf::from(v));
434                }
435            }
436            "--thinking" => {
437                if let Some(v) = take_value(&mut result, "--thinking") {
438                    match parse_thinking_level(&v) {
439                        Some(lvl) => result.thinking = Some(lvl),
440                        None => result.ignored.push(format!(
441                            "Invalid --thinking \"{v}\". Valid: {}",
442                            VALID_THINKING_LEVELS.join(", ")
443                        )),
444                    }
445                }
446            }
447            "--tools" | "-t" => {
448                if let Some(v) = take_value(&mut result, &flag_key) {
449                    result.tools = Some(split_csv(&v));
450                }
451            }
452            "--exclude-tools" | "-xt" => {
453                if let Some(v) = take_value(&mut result, &flag_key) {
454                    result.exclude_tools = Some(split_csv(&v));
455                }
456            }
457            "--list-models" => {
458                // Optionally consumes a search term, matching the native
459                // parser's bare-flag versus string distinction.
460                let mut search = inline.clone().unwrap_or_default();
461                if inline.is_none()
462                    && i + 1 < args.len()
463                    && !args[i + 1].starts_with('-')
464                    && !args[i + 1].starts_with('@')
465                {
466                    i += 1;
467                    search = args[i].clone();
468                }
469                result.list_models = Some(search);
470            }
471            "--offline" => result.offline = true,
472            "--export" => {
473                if let Some(value) = take_value(&mut result, &flag_key) {
474                    result.export = Some(PathBuf::from(value));
475                }
476            }
477            "--approve" | "-a" => result.trust_override = Some(true),
478            "--no-approve" | "-na" => result.trust_override = Some(false),
479            // ---- Recognized-but-ignored v1 scope cuts (warn, don't error) ----
480            // `flag_key` has already had any `=value` peeled, so these match the
481            // bare flag name even when the user wrote `--offline=1`.
482            //
483            // NOTE: `--no-skills`/`-ns`, `--no-prompt-templates`/`-np`,
484            // `--no-context-files`/`-nc`, `--no-extensions`/`-ne`, and
485            // `--no-themes` is honored (parsed into a real field above). The
486            // into real fields above), so they no longer reach this arm. The
487            // resource flags gate discovery in `session.rs`; plugin loading
488            // is separately opt-in.
489            other if matches!(other, "--models") => {
490                // Consume a value if the next token isn't a flag (so
491                // `--models sonnet` doesn't swallow `sonnet` as a message).
492                if inline.is_none()
493                    && i + 1 < args.len()
494                    && !args[i + 1].starts_with('-')
495                    && !args[i + 1].starts_with('@')
496                {
497                    i += 1;
498                }
499                result
500                    .ignored
501                    .push(format!("{other} is not supported in v1 (ignored)"));
502            }
503            "--theme" => {
504                result.theme = take_value(&mut result, "--theme");
505            }
506            "--no-themes" => result.no_themes = true,
507            // Unknown long flag (with or without `=`). Preserve it for an
508            // extension to claim after extension registration, matching Pi's
509            // `unknownFlags` behavior. A bare flag is boolean true; a following
510            // non-flag token is its string value.
511            other if other.starts_with("--") => {
512                let name = &flag_key;
513                let value = if let Some(value) = inline {
514                    serde_json::Value::String(value)
515                } else if i + 1 < args.len()
516                    && !args[i + 1].starts_with('-')
517                    && !args[i + 1].starts_with('@')
518                {
519                    i += 1;
520                    serde_json::Value::String(args[i].clone())
521                } else {
522                    serde_json::Value::Bool(true)
523                };
524                result.unknown_flags.insert(name[2..].to_string(), value);
525            }
526            // Unknown short flag → hard error (mirrors TS).
527            other if other.starts_with('-') && other.len() > 1 => {
528                result.errors.push(format!("Unknown option: {other}"));
529            }
530            other => {
531                if let Some(path) = file_arg(other) {
532                    result.file_args.push(path);
533                } else {
534                    result.messages.push(other.to_string());
535                }
536            }
537        }
538        i += 1;
539    }
540
541    // `--print` + `--mode json`: `--print` implies non-interactive, but
542    // `--mode json` selects the JSON event stream. The TS `resolveAppMode`
543    // treats `mode === "json"` as its own non-interactive mode; we follow that.
544    result
545}
546
547/// Split a comma-separated list (mirrors the TS `.split(',').map(trim)`).
548fn split_csv(v: &str) -> Vec<String> {
549    v.split(',')
550        .map(|s| s.trim().to_string())
551        .filter(|s| !s.is_empty())
552        .collect()
553}
554
555/// Resolve the effective output [`Mode`]. Mirrors TS `resolveAppMode`:
556/// `rpc`→rpc, `json`→json, `print` or piped-stdin/redirected-stdout→print,
557/// else interactive. Here `stdin_is_tty`/`stdout_is_tty` come from
558/// `std::io::IsTerminal`.
559pub fn resolve_mode(parsed: &Args, stdin_is_tty: bool, stdout_is_tty: bool) -> RunMode {
560    // Check for --server flag (unknown flag stored in unknown_flags map)
561    if parsed.unknown_flags.contains_key("server") {
562        return RunMode::Rpc;
563    }
564    if parsed.mode == Mode::Rpc {
565        return RunMode::Rpc;
566    }
567    if parsed.mode == Mode::Json {
568        return RunMode::Json;
569    }
570    if parsed.print || !stdin_is_tty || !stdout_is_tty {
571        RunMode::Print
572    } else {
573        RunMode::Interactive
574    }
575}
576
577/// The concrete run mode [`resolve_mode`] picks. Mirrors TS `AppMode`
578/// (`interactive`/`print`/`json`/`rpc`). Distinguished from [`Mode`] (the raw
579/// `--mode` flag value) because the effective mode also folds in `-p` + TTY
580/// detection.
581#[derive(Debug, Clone, Copy, PartialEq, Eq)]
582pub enum RunMode {
583    Interactive,
584    Print,
585    Json,
586    Rpc,
587}
588
589/// Print the help text to stdout. Mirrors TS `printHelp`, scoped to v1 flags.
590pub fn print_help() {
591    let builtin = "read, bash, edit, write, docs";
592    println!(
593        "{name} - AI coding assistant with read, bash, edit, write, docs tools
594
595{u}Usage:{r}
596  {name} [options] [@files...] [messages...]
597
598{u}Options:{r}
599  --provider <name>              Provider name (built-in, installed package, or models.json id)
600  --model <pattern>              Model pattern or ID (supports \"provider/id\" and optional \":<thinking>\")
601  --api-key <key>                API key override for the selected provider
602  --base-url <url>               Override the selected model endpoint
603  --timeout <seconds>            LLM API request timeout (default: 600)
604  --stream-idle-timeout <seconds> Max silence between response bytes (default: 300; 0 disables)
605  --system-prompt <text>         Replace the default system prompt
606  --append-system-prompt <text>  Append text to the system prompt (repeatable)
607  --thinking <level>             off, minimal, low, medium, high, xhigh, max
608  --mode <mode>                  Output mode: text (default), json, or rpc
609  --server [--port <n>] [--bind <ip>]
610                                 Headless server: serve a remote-connectable agent (no TUI)
611  --connect <host:port>          Remote client: connect to a `--server` instance and run the TUI
612                                 (no local provider/tools/session; all agent work is remote)
613  --token <token>                Auth token for `--connect` (printed by `--server`; may also
614                                 be provided via the RPI_SERVER_TOKEN env var)
615  --tui-mode <mode>              TUI buffer: regular or fullscreen (macOS default: regular)
616  --list-models [search]         List available models (with optional fuzzy search)
617  --offline                      Disable startup network operations (same as RPI_OFFLINE=1)
618  --export <file>                Export a JSONL session to HTML and exit
619  --approve, -a                  Force-enable current-project resources
620  --no-approve, -na              Disable current-project resources
621  --print, -p                    Non-interactive: process prompt(s) and exit
622  --continue, -c                 Continue the most recent session
623  --resume, -r                   Browse and select a session to resume
624  --session <id|path>            Use a specific session (partial UUID or file)
625  --session-dir <dir>            Directory for session storage
626  --no-session                   Ephemeral mode (do not persist the session)
627  --name, -n <name>              Set the session display name
628  --tools, -t <list>             Comma-separated allowlist of tool names to enable
629  --exclude-tools, -xt <list>    Comma-separated denylist of tool names to disable
630  --no-tools, -nt                Disable all tools
631  --no-builtin-tools, -nbt       Disable the built-in tools (read, bash, edit, write, docs)
632  --no-skills, -ns               Skip skill discovery (no <available_skills> block)
633  --no-prompt-templates, -np     Skip prompt-template discovery (/expand templates)
634  --no-context-files, -nc        Skip AGENTS.md/CLAUDE.md discovery (no <project_context>)
635  --no-extensions, -ne           Skip Rust cdylib extension loading
636  --extensions-dir, -ed <dir>    Extra dir to scan for plugins (.dll/.so/.dylib); repeatable
637                                 (also via RPI_EXTENSIONS_DIR env: ';' on Windows, ':' on Unix)
638  --local-only                   Skip automatic extension discovery: load only
639                                 --extensions-dir / --extension paths (no project
640                                 .rpi/extensions, no global extensions)
641  --package-only, --project-only Load project skills/prompts/extensions/packages
642                                 from the active project; exclude global resources
643  --debug-system-prompt          Print the resolved system-prompt sections to stderr (verification)
644  --verbose                      Show startup warnings (e.g. ignored flags)
645  --help, -h                     Show this help
646  --version, -v                  Show version
647
648{u}Subcommands:{r}
649  update                       Update the rpi CLI from crates.io
650  auth login|check|logout        Manage persisted credentials in ~/.rpi/auth.json
651                                (see `rpi auth --help`)
652  events path|tail               Inspect the extension event journal (needs
653                                RPI_EVENT_LOG=1; see `rpi events --help`)
654  install <crate>                Install a prebuilt Rust extension (--build for source)
655                                (see `rpi install --help`)
656  uninstall <crate>              Remove an installed Rust cdylib extension
657  package link|list|update|unlink Manage project-local Rust extension packages
658                                (see `rpi package --help`)
659  dev [options]                  Build, watch, and hot-reload a Rust extension
660                                (see `rpi dev --help`)
661  dev-local [options]            Debug only the current Rust extension
662                                (shortcut for `rpi dev --local-only`)
663
664{u}Built-in Tools:{r}
665  {builtin}  (enabled by default)
666
667{u}Examples:{r}
668  # Interactive with an initial prompt
669  {name} \"List all .rs files in src/\"
670
671  # Single-shot print mode
672  {name} -p \"Summarize this project\"
673
674  # Include a file in the initial message
675  {name} @README.md \"What does this project do?\"
676
677  # Continue the previous session
678  {name} -c \"What did we discuss?\"
679
680  # Use a specific model + thinking level
681  {name} --model claude-sonnet-5 --thinking high \"Refactor this\"
682
683  # JSON event stream (one JSON object per line on stdout)
684  {name} --mode json -p \"Inspect the code\"
685
686  # Read-only: no file-modifying tools
687  {name} --tools read,bash -p \"Review the code in src/\"
688
689{u}Environment:{r}
690  ANTHROPIC_API_KEY              Anthropic API key (x-api-key) — fallback when no stored credential
691  ANTHROPIC_AUTH_TOKEN           Bearer token (Authorization: Bearer) for third-party gateways
692  ANTHROPIC_BASE_URL             Override the Anthropic endpoint (e.g. a compatible proxy)
693  OPENAI_API_KEY                 Bearer token for openai-completions/responses
694  RPI_OFFLINE                     Disable startup network operations when set to 1/true/yes
695  RPI_CODING_AGENT_DIR           Override the ~/.rpi config directory (auth.json + models.json)
696  RPI_SESSION_ID                 Session id served by a plugin (set by the host; also honored as an override)
697  RPI_NO_EMOJI                   Render the brand lockup without the crab (1/true/yes)
698
699{u}Notes:{r}
700  Supported HTTP protocols are Anthropic Messages and OpenAI Chat Completions.
701  Define custom model catalogs and provider apiKey values in
702  ~/.rpi/agent/models.json. The interactive TUI, Rust extensions, skills,
703  prompt templates, themes, model cycling, session fork/export, and trust
704  commands are available in the current build. OAuth, RPC, and full model
705  cycling remain outside the current implementation.
706",
707        name = crate::APP_NAME,
708        builtin = builtin,
709        u = "\x1b[1m",
710        r = "\x1b[0m",
711    );
712}
713
714/// Print the version line. Mirrors TS `--version` output (`pi <version>`).
715pub fn print_version() {
716    println!("{} {}", crate::APP_NAME, crate::VERSION);
717}
718
719#[cfg(test)]
720mod tests {
721    use super::*;
722
723    struct RestoreOfflineEnv(Option<std::ffi::OsString>);
724
725    impl Drop for RestoreOfflineEnv {
726        fn drop(&mut self) {
727            match self.0.take() {
728                Some(value) => std::env::set_var(RPI_OFFLINE_ENV, value),
729                None => std::env::remove_var(RPI_OFFLINE_ENV),
730            }
731        }
732    }
733
734    fn s(args: &[&str]) -> Vec<String> {
735        args.iter().map(|a| a.to_string()).collect()
736    }
737
738    #[test]
739    fn parses_basic_prompt() {
740        let a = parse_args(&s(&["hello", "world"]));
741        assert_eq!(a.messages, vec!["hello".to_string(), "world".to_string()]);
742        assert!(!a.help);
743    }
744
745    #[test]
746    fn parses_help_and_version() {
747        let a = parse_args(&s(&["--help"]));
748        assert!(a.help);
749        let a = parse_args(&s(&["-v"]));
750        assert!(a.version);
751    }
752
753    #[test]
754    fn print_consumes_following_positional() {
755        let a = parse_args(&s(&["-p", "summarize"]));
756        assert!(a.print);
757        assert_eq!(a.messages, vec!["summarize".to_string()]);
758    }
759
760    #[test]
761    fn print_does_not_consume_file_or_flag() {
762        let a = parse_args(&s(&["-p", "@file.md"]));
763        assert!(a.print);
764        assert!(a.messages.is_empty());
765        assert_eq!(a.file_args, vec![PathBuf::from("file.md")]);
766    }
767
768    #[test]
769    fn model_and_thinking() {
770        let a = parse_args(&s(&["--model", "claude-sonnet-5", "--thinking", "high"]));
771        assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
772        assert_eq!(a.thinking, Some(ThinkingLevel::High));
773    }
774
775    #[test]
776    fn model_with_thinking_shorthand() {
777        let a = parse_args(&s(&["--model", "claude-sonnet-5:high"]));
778        // The model pattern keeps the `:high`; provider resolution splits it.
779        assert_eq!(a.model.as_deref(), Some("claude-sonnet-5:high"));
780    }
781
782    #[test]
783    fn tools_split_csv() {
784        let a = parse_args(&s(&["--tools", "read, bash ,write"]));
785        assert_eq!(
786            a.tools.as_deref(),
787            Some(&["read".to_string(), "bash".to_string(), "write".to_string()][..])
788        );
789    }
790
791    #[test]
792    fn unknown_short_flag_errors() {
793        let a = parse_args(&s(&["-Z"]));
794        assert!(!a.errors.is_empty());
795    }
796
797    #[test]
798    fn unknown_long_flag_is_retained_for_extensions() {
799        let a = parse_args(&s(&["--frobnicate", "value"]));
800        assert!(a.errors.is_empty());
801        assert_eq!(
802            a.unknown_flags.get("frobnicate"),
803            Some(&serde_json::Value::String("value".into()))
804        );
805        assert!(a.ignored.is_empty());
806    }
807
808    #[test]
809    fn unknown_long_boolean_flag_is_retained() {
810        let a = parse_args(&s(&["--server"]));
811        assert_eq!(
812            a.unknown_flags.get("server"),
813            Some(&serde_json::Value::Bool(true))
814        );
815    }
816
817    #[test]
818    fn unknown_long_flags_keep_string_and_equals_values() {
819        let a = parse_args(&s(&["--port", "8080", "--bind=127.0.0.1"]));
820        assert_eq!(
821            a.unknown_flags.get("port"),
822            Some(&serde_json::Value::String("8080".into()))
823        );
824        assert_eq!(
825            a.unknown_flags.get("bind"),
826            Some(&serde_json::Value::String("127.0.0.1".into()))
827        );
828    }
829
830    #[test]
831    fn models_flag_parses_csv() {
832        let a = parse_args(&s(&["--models", "a,b,c"]));
833        assert!(a.errors.is_empty());
834        assert!(a.ignored.is_empty(), "--models is implemented");
835        assert_eq!(
836            a.models.as_deref(),
837            Some(&["a".to_string(), "b".to_string(), "c".to_string()][..])
838        );
839        // The value is consumed, not read as a message:
840        assert!(a.messages.is_empty());
841    }
842
843    #[test]
844    fn list_models_accepts_bare_and_search_forms() {
845        let bare = parse_args(&s(&["--list-models"]));
846        assert_eq!(bare.list_models.as_deref(), Some(""));
847        assert!(bare.ignored.is_empty());
848        assert!(bare.messages.is_empty());
849
850        let search = parse_args(&s(&["--list-models", "claude"]));
851        assert_eq!(search.list_models.as_deref(), Some("claude"));
852        assert!(search.messages.is_empty());
853
854        let inline = parse_args(&s(&["--list-models=gpt"]));
855        assert_eq!(inline.list_models.as_deref(), Some("gpt"));
856    }
857
858    #[test]
859    fn offline_flag_is_honored_without_warning() {
860        let args = parse_args(&s(&["--offline"]));
861        assert!(args.offline);
862        assert!(args.ignored.is_empty());
863    }
864
865    #[test]
866    fn timeout_parses_seconds_in_separate_and_equals_forms() {
867        let separate = parse_args(&s(&["--timeout", "45"]));
868        assert!(separate.errors.is_empty());
869        assert_eq!(separate.timeout, Some(Duration::from_secs(45)));
870
871        let inline = parse_args(&s(&["--timeout=90"]));
872        assert!(inline.errors.is_empty());
873        assert_eq!(inline.timeout, Some(Duration::from_secs(90)));
874    }
875
876    #[test]
877    fn timeout_rejects_zero_and_invalid_values() {
878        for value in ["0", "1.5", "forever", "18446744073709551616"] {
879            let args = parse_args(&s(&[&format!("--timeout={value}")]));
880            assert_eq!(args.errors.len(), 1, "value: {value}");
881            assert!(args.timeout.is_none(), "value: {value}");
882        }
883    }
884
885    #[test]
886    fn stream_idle_timeout_accepts_both_forms_and_zero_but_rejects_invalid_values() {
887        for (argv, seconds) in [
888            (s(&["--stream-idle-timeout", "45"]), 45),
889            (s(&["--stream-idle-timeout=90"]), 90),
890            (s(&["--stream-idle-timeout=0"]), 0),
891        ] {
892            let args = parse_args(&argv);
893            assert!(args.errors.is_empty(), "{:?}", args.errors);
894            assert_eq!(args.stream_idle_timeout, Some(Duration::from_secs(seconds)));
895            assert!(args.timeout.is_none());
896        }
897        for value in ["-1", "1.5", "no", "18446744073709551616"] {
898            let args = parse_args(&s(&[&format!("--stream-idle-timeout={value}")]));
899            assert!(!args.errors.is_empty(), "{value}");
900            assert!(args.stream_idle_timeout.is_none());
901        }
902        assert!(!parse_args(&s(&["--stream-idle-timeout"])).errors.is_empty());
903    }
904
905    #[test]
906    fn native_pi_offline_truthy_values_are_case_insensitive() {
907        for value in [
908            Some("1"),
909            Some("true"),
910            Some("TRUE"),
911            Some("Yes"),
912            Some("yEs"),
913        ] {
914            assert!(is_truthy_env_flag(value), "value={value:?}");
915        }
916        for value in [
917            None,
918            Some(""),
919            Some("0"),
920            Some("false"),
921            Some("no"),
922            Some(" true "),
923        ] {
924            assert!(!is_truthy_env_flag(value), "value={value:?}");
925        }
926    }
927
928    #[test]
929    fn pi_offline_env_and_cli_flag_share_one_normalized_gate() {
930        let _guard = crate::config::test_support::env_lock().lock().unwrap();
931        let _restore = RestoreOfflineEnv(std::env::var_os(RPI_OFFLINE_ENV));
932
933        std::env::set_var(RPI_OFFLINE_ENV, "YeS");
934        assert!(parse_args(&[]).offline);
935        assert!(normalize_offline_mode(&[]));
936        assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
937
938        std::env::set_var(RPI_OFFLINE_ENV, "0");
939        assert!(!parse_args(&[]).offline);
940        let argv = s(&["--offline"]);
941        assert!(normalize_offline_mode(&argv));
942        assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
943    }
944
945    #[test]
946    fn project_trust_flags_are_honored_without_warning() {
947        let approved = parse_args(&s(&["--approve"]));
948        assert_eq!(approved.trust_override, Some(true));
949        assert!(approved.ignored.is_empty());
950        let denied = parse_args(&s(&["--no-approve"]));
951        assert_eq!(denied.trust_override, Some(false));
952        assert!(denied.ignored.is_empty());
953    }
954
955    #[test]
956    fn export_flag_captures_input_and_output_position() {
957        let args = parse_args(&s(&["--export", "session.jsonl", "transcript.html"]));
958        assert_eq!(args.export, Some(PathBuf::from("session.jsonl")));
959        assert_eq!(args.messages, vec!["transcript.html".to_string()]);
960        assert!(args.ignored.is_empty());
961    }
962
963    #[test]
964    fn session_id_and_fork_flags_parse() {
965        let a = parse_args(&s(&["--session-id", "01abc", "--fork", "xyz"]));
966        assert!(a.errors.is_empty());
967        assert_eq!(a.session_id.as_deref(), Some("01abc"));
968        assert_eq!(a.fork.as_deref(), Some("xyz"));
969        let a = parse_args(&s(&[
970            "-e",
971            "plugin.dll",
972            "--skill",
973            "s",
974            "--prompt-template",
975            "t.md",
976        ]));
977        assert_eq!(a.extension.len(), 1);
978        assert_eq!(a.skill.len(), 1);
979        assert_eq!(a.prompt_template.len(), 1);
980    }
981
982    #[test]
983    fn no_skills_flag_honored() {
984        let a = parse_args(&s(&["-ns"]));
985        assert!(a.errors.is_empty());
986        assert!(a.no_skills);
987        // Honored flags do NOT also warn-ignore themselves.
988        assert!(a.ignored.is_empty());
989    }
990
991    #[test]
992    fn no_prompt_templates_flag_honored() {
993        let a = parse_args(&s(&["--no-prompt-templates"]));
994        assert!(a.no_prompt_templates);
995        assert!(a.ignored.is_empty());
996    }
997
998    #[test]
999    fn no_context_files_flag_honored() {
1000        let a = parse_args(&s(&["-nc"]));
1001        assert!(a.no_context_files);
1002        assert!(a.ignored.is_empty());
1003    }
1004
1005    #[test]
1006    fn no_extensions_flag_honored() {
1007        // `--no-extensions` is parsed and disables both extension backends.
1008        let a = parse_args(&s(&["--no-extensions"]));
1009        assert!(a.no_extensions);
1010        assert!(a.ignored.is_empty());
1011    }
1012
1013    #[test]
1014    fn local_only_flag_is_honored_on_the_regular_parser() {
1015        // The plain `rpi --local-only` form sets the same scope `rpi dev
1016        // --local-only` uses, without the build/watch layer.
1017        let a = parse_args(&s(&["--local-only"]));
1018        assert!(a.errors.is_empty());
1019        assert!(a.dev_local_only);
1020        assert!(a.ignored.is_empty());
1021    }
1022
1023    #[test]
1024    fn project_only_aliases_are_honored() {
1025        for flag in ["--package-only", "--project-only"] {
1026            let a = parse_args(&s(&[flag]));
1027            assert!(a.errors.is_empty());
1028            assert!(a.project_only);
1029            assert!(a.ignored.is_empty());
1030        }
1031    }
1032
1033    #[test]
1034    fn extensions_dir_flag_collects_dirs() {
1035        let a = parse_args(&s(&["--extensions-dir", "/a/b", "-ed", "/c/d"]));
1036        assert_eq!(
1037            a.extensions_dir,
1038            vec![PathBuf::from("/a/b"), PathBuf::from("/c/d")]
1039        );
1040        assert!(a.ignored.is_empty());
1041    }
1042
1043    #[test]
1044    fn extensions_dir_inline_equals_form() {
1045        let a = parse_args(&s(&["--extensions-dir=/x/y"]));
1046        assert_eq!(a.extensions_dir, vec![PathBuf::from("/x/y")]);
1047    }
1048
1049    #[test]
1050    fn extensions_dir_env_is_merged() {
1051        // The env var contributes its split list. We can't fully control env in
1052        // a unit test without `set_var` (process-global + racy under parallel
1053        // tests), so this asserts the flag path only; the env path is exercised
1054        // by the B2 smoke. Keep the test green regardless of the host env by
1055        // NOT asserting emptiness — just confirm the flag appends after env.
1056        let a = parse_args(&s(&["--extensions-dir", "/flag/only"]));
1057        assert!(a
1058            .extensions_dir
1059            .iter()
1060            .any(|p| p == &PathBuf::from("/flag/only")));
1061    }
1062
1063    #[test]
1064    fn file_args_stripped() {
1065        let a = parse_args(&s(&["@a.txt", "@b.md", "hi"]));
1066        assert_eq!(
1067            a.file_args,
1068            vec![PathBuf::from("a.txt"), PathBuf::from("b.md")]
1069        );
1070        assert_eq!(a.messages, vec!["hi".to_string()]);
1071    }
1072
1073    #[test]
1074    fn equals_form_supported() {
1075        let a = parse_args(&s(&["--model=claude-sonnet-5", "--thinking=low"]));
1076        assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1077        assert_eq!(a.thinking, Some(ThinkingLevel::Low));
1078    }
1079
1080    #[test]
1081    fn theme_flag_is_honored() {
1082        let a = parse_args(&s(&["--theme", "ocean.json"]));
1083        assert_eq!(a.theme.as_deref(), Some("ocean.json"));
1084        assert!(a.ignored.is_empty());
1085    }
1086
1087    #[test]
1088    fn no_themes_is_honored() {
1089        let a = parse_args(&s(&["--no-themes"]));
1090        assert!(a.no_themes);
1091        assert!(a.ignored.is_empty());
1092    }
1093
1094    #[test]
1095    fn tui_mode_parses_and_validates() {
1096        assert_eq!(
1097            parse_args(&s(&["--tui-mode", "regular"])).tui_mode,
1098            TuiMode::Regular
1099        );
1100        assert_eq!(
1101            parse_args(&s(&["--tui-mode=fullscreen"])).tui_mode,
1102            TuiMode::Fullscreen
1103        );
1104        let invalid = parse_args(&s(&["--tui-mode", "split"]));
1105        assert!(!invalid.errors.is_empty());
1106    }
1107
1108    #[test]
1109    fn tui_mode_default_preserves_native_macos_scrollback() {
1110        assert_eq!(default_tui_mode_for(true), TuiMode::Regular);
1111        assert_eq!(default_tui_mode_for(false), TuiMode::Fullscreen);
1112    }
1113
1114    #[test]
1115    fn resolve_mode_interactive_when_tty() {
1116        let a = Args {
1117            print: true,
1118            ..Args::default()
1119        };
1120        assert_eq!(resolve_mode(&a, true, true), RunMode::Print);
1121        let a = Args::default();
1122        assert_eq!(resolve_mode(&a, true, true), RunMode::Interactive);
1123        let a = Args {
1124            mode: Mode::Json,
1125            ..Args::default()
1126        };
1127        assert_eq!(resolve_mode(&a, true, true), RunMode::Json);
1128        let a = Args {
1129            mode: Mode::Rpc,
1130            ..Args::default()
1131        };
1132        assert_eq!(resolve_mode(&a, true, true), RunMode::Rpc);
1133    }
1134
1135    #[test]
1136    fn piped_stdout_forces_print() {
1137        let a = Args::default();
1138        // stdout not a TTY ⇒ print even without -p (mirrors TS).
1139        assert_eq!(resolve_mode(&a, true, false), RunMode::Print);
1140    }
1141}