Skip to main content

rpi_cli/
args.rs

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