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