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/// Visibility of the native interactive footer.
123#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
124#[serde(rename_all = "kebab-case")]
125pub enum TuiFooter {
126    #[default]
127    Full,
128    Context,
129    Hidden,
130    Auto,
131}
132
133/// The parsed argument set. Mirrors TS `Args`. Unknown long flags are retained
134/// for extension consumption; unknown short flags remain hard errors.
135#[derive(Debug, Clone, Default)]
136pub struct Args {
137    pub provider: Option<String>,
138    pub model: Option<String>,
139    pub api_key: Option<String>,
140    /// `--base-url` — overrides `ANTHROPIC_BASE_URL` + each model's base URL,
141    /// for third-party Anthropic-compatible gateways/proxies.
142    pub base_url: Option<String>,
143    /// `--timeout <seconds>` overrides the deadline for each LLM API request.
144    pub timeout: Option<Duration>,
145    /// Maximum silence between streamed response bytes; zero disables it.
146    pub stream_idle_timeout: Option<Duration>,
147    pub resource_config: Option<PathBuf>,
148    pub resource_transition: Option<PathBuf>,
149    pub system_prompt: Option<String>,
150    pub append_system_prompt: Vec<String>,
151    /// `--theme` — built-in theme name or a theme file path.
152    pub theme: Option<String>,
153    pub thinking: Option<ThinkingLevel>,
154
155    pub print: bool,
156    /// Select an ephemeral session and turn off native durable execution.
157    pub mini: bool,
158    /// The empty string selects the configured default area.
159    pub host: Option<String>,
160    pub mode: Mode,
161    pub rpc_message_updates: RpcMessageUpdates,
162    /// `--tui-mode regular|fullscreen` controls the interactive terminal
163    /// buffer. macOS defaults to regular so native selection and terminal
164    /// scrollback remain available together; other platforms use fullscreen.
165    pub tui_mode: TuiMode,
166    /// `--tui-footer full|context|hidden|auto` controls the built-in footer.
167    pub tui_footer: TuiFooter,
168
169    /// `--list-models [search]`: list the merged model catalog and exit.
170    /// `Some("")` represents the bare flag; `None` means absent.
171    pub list_models: Option<String>,
172    /// `--offline`: disable best-effort startup network checks.
173    pub offline: bool,
174    /// `--export <session-file>`: export a JSONL session to HTML (or copy it
175    /// when the destination ends in `.jsonl`).
176    pub export: Option<PathBuf>,
177    /// Explicit project trust override. `--approve` trusts the current
178    /// project; `--no-approve` keeps project-local resources disabled.
179    pub trust_override: Option<bool>,
180
181    pub continue_session: bool,
182    pub resume: bool,
183    pub session: Option<String>,
184    /// `--session-id <id>`: use the EXACT project session id, creating it if
185    /// missing (pi `--session-id`). Unlike `--session` (partial match), this
186    /// is an exact-id open-or-create.
187    pub session_id: Option<String>,
188    /// `--fork <path|id>`: fork the given session into a new one and start in
189    /// the fork (pi `--fork`).
190    pub fork: Option<String>,
191    /// `--fork-entry <entryId>`: cut the new branch at this message entry
192    /// instead of the lane leaf. The id must match exactly — unlike `--fork`'s
193    /// partial session id, no prefix or substring match is attempted.
194    /// Requires `--fork`.
195    pub fork_entry: Option<String>,
196    /// `--fork-position at|before`: whether `--fork-entry` includes (`at`) or
197    /// excludes (`before`) its message. `None` keeps the harness default for an
198    /// explicit entry, which is `before` (`ForkOptions::Branch`).
199    /// Requires `--fork` and `--fork-entry`; without an explicit entry the
200    /// harness applies the position to the implicit lane leaf and truncates it.
201    pub fork_position: Option<rpi_harness::session::types::ForkPosition>,
202    /// `--models <patterns>`: comma-separated model patterns for the Ctrl+P
203    /// cycle (globs/fuzzy in pi; v1 writes the matched ids to settings.json's
204    /// scopedModels — the same set /scoped-models edits). Empty = all models.
205    pub models: Option<Vec<String>>,
206    pub session_dir: Option<PathBuf>,
207    pub no_session: bool,
208    pub name: Option<String>,
209
210    pub tools: Option<Vec<String>>,
211    pub exclude_tools: Option<Vec<String>>,
212    pub no_tools: bool,
213    pub no_builtin_tools: bool,
214    /// Native durable host selection. CLI parsing enables it by default; the
215    /// temporary `--no-native-durable` escape hatch selects legacy session behavior.
216    pub native_durable: bool,
217    /// Explicit experimental v2 epoch; requires native durable admission.
218    pub experimental_durable_epoch: Option<String>,
219
220    /// `--no-skills`/`-ns`: skip skill discovery + the `<available_skills>`
221    /// system-prompt listing.
222    pub no_skills: bool,
223    /// `--no-prompt-templates`/`-np`: skip prompt-template discovery (templates
224    /// are on-demand only; this suppresses populating the resource registry).
225    pub no_prompt_templates: bool,
226    /// `--no-context-files`/`-nc`: skip context-file (`AGENTS.md`/`CLAUDE.md`)
227    /// discovery + the `<project_context>` system-prompt block.
228    pub no_context_files: bool,
229    /// `--no-extensions`/`-ne`: skip Rust cdylib extension loading.
230    /// Honored by `session.rs`: when set, no extension directory is scanned.
231    pub no_extensions: bool,
232    /// `--no-themes`: disable custom theme discovery and loading.
233    /// Built-in presets remain available unless a custom `--theme` is given.
234    pub no_themes: bool,
235    /// `--extensions-dir`/`-ed`: an extra directory to scan for cdylib plugins
236    /// (`.dll`/`.so`/`.dylib`), in addition to project `.rpi/extensions`
237    /// and global
238    /// `agent_dir()/extensions` defaults. May be repeated; scanned after
239    /// the defaults (so a same-named tool in a default dir wins first, mirroring
240    /// pi's registration order). `RPI_EXTENSIONS_DIR` (colon-separated on Unix,
241    /// semicolon on Windows) provides the same list via env.
242    pub extensions_dir: Vec<PathBuf>,
243    /// `--extension`/`-e <path>`: load an explicit extension cdylib file (may
244    /// be repeated). Loaded in addition to the discovered dirs.
245    pub extension: Vec<PathBuf>,
246    /// `--skill <path>`: load an explicit skill file or directory (repeated).
247    pub skill: Vec<PathBuf>,
248    /// `--prompt-template <path>`: load an explicit prompt-template file or
249    /// directory (repeated).
250    pub prompt_template: Vec<PathBuf>,
251
252    /// `--local-only`: load only explicitly supplied extension paths.
253    pub dev_local_only: bool,
254    /// `--package-only` / `--project-only`: load project resources and
255    /// extensions from the active project's settings, excluding global ones.
256    pub project_only: bool,
257
258    pub verbose: bool,
259    pub help: bool,
260    pub version: bool,
261
262    /// `--debug-system-prompt`: print the resolved system-prompt sections
263    /// (base, append, context, skills listing) + resource counts to stderr at
264    /// harness build time, then proceed normally. A verification affordance for
265    /// resource-discovery (Part A) — lets a smoke confirm `<available_skills>` +
266    /// `<project_context>` + appended text reached the prompt without a full
267    /// round-trip parse. Mirrors the plan's "add --debug-system-prompt if absent".
268    pub debug_system_prompt: bool,
269
270    /// Positional prompt text (one or more messages). Mirrors TS `messages`.
271    pub messages: Vec<String>,
272    /// `@file` attachments (prefix stripped), as raw paths for the caller to
273    /// expand. Mirrors TS `fileArgs`.
274    pub file_args: Vec<PathBuf>,
275
276    /// Extension-declared or otherwise unknown long flags. Values are either
277    /// JSON booleans (a bare flag) or strings (a flag with a value), matching
278    /// Pi's `unknownFlags` contract so an extension can claim its own options.
279    pub unknown_flags: BTreeMap<String, serde_json::Value>,
280    /// Warnings about recognized-but-ignored flags (v1 scope cuts). Surfaced
281    /// to the user on startup when `--verbose`.
282    pub ignored: Vec<String>,
283    /// Hard parse errors (unknown short flags, missing values). Non-empty ⇒
284    /// `main` prints them + help and exits non-zero.
285    pub errors: Vec<String>,
286}
287
288impl Args {
289    pub(crate) fn fork_cut_errors(&self) -> Vec<&'static str> {
290        let mut errors = Vec::new();
291        if self.fork.is_none() {
292            if self.fork_entry.is_some() {
293                errors.push("--fork-entry requires --fork");
294            }
295            if self.fork_position.is_some() {
296                errors.push("--fork-position requires --fork");
297            }
298        } else if (self.fork_entry.is_some() || self.fork_position.is_some())
299            && (self.fork.as_deref() == Some("")
300                || self.no_session
301                || self.continue_session
302                || self.resume)
303        {
304            errors.push("--fork cut flags require an active --fork selection");
305        }
306        if self
307            .fork_entry
308            .as_deref()
309            .is_some_and(|id| id.trim().is_empty())
310        {
311            errors.push("--fork-entry requires a nonempty entry ID");
312        }
313        // An implicit leaf combined with `before` would drop that leaf.
314        if self.fork_entry.is_none() && self.fork_position.is_some() {
315            errors.push("--fork-position requires --fork-entry");
316        }
317        errors
318    }
319}
320
321/// The canonical valid `--thinking` level strings, in level order. Mirrors TS
322/// `VALID_THINKING_LEVELS`.
323pub use rpi_runtime::thinking::VALID_THINKING_LEVELS;
324
325/// Parse a thinking-level string. Mirrors TS `isValidThinkingLevel`.
326pub use rpi_runtime::thinking::parse_thinking_level;
327
328/// `@file`-argument helper mirroring the TS parser: a leading `@` marks a file
329/// attachment (the `@` is stripped).
330fn file_arg(arg: &str) -> Option<PathBuf> {
331    if let Some(rest) = arg.strip_prefix('@') {
332        // Reject the bare `@` (TS keeps it as a message; we treat it as one).
333        if rest.is_empty() {
334            None
335        } else {
336            Some(PathBuf::from(rest))
337        }
338    } else {
339        None
340    }
341}
342
343/// Parse `argv` (excluding the program name). Mirrors TS `parseArgs`.
344///
345/// Long flags accept `--name value` or `--name=value` (the TS parser only
346/// handles `--name=value` for *unknown* flags; we extend it to known flags for
347/// ergonomics). Short flags use a single leading `-`.
348pub fn parse_args(args: &[String]) -> Args {
349    parse_startup_args(args, false)
350}
351
352pub(crate) fn parse_startup_args(args: &[String], package: bool) -> Args {
353    // Native durable is the CLI default. Keep `Args::default()` unchanged for
354    // embedded/test hosts that construct programmatic options explicitly.
355    let mut result = Args {
356        native_durable: true,
357        offline: offline_env_enabled(),
358        ..Args::default()
359    };
360    // `RPI_EXTENSIONS_DIR` env: an extra list of plugin dirs prepended to any
361    // `--extensions-dir` flags. Semicolon-separated on Windows, colon-separated
362    // on Unix (PATH-style). Empty entries skipped. `--no-extensions` still wins.
363    let mut env_extension_dirs = Vec::new();
364    if let Ok(raw) = std::env::var("RPI_EXTENSIONS_DIR") {
365        if !raw.is_empty() {
366            let sep = if cfg!(windows) { ';' } else { ':' };
367            for part in raw.split(sep) {
368                let trimmed = part.trim();
369                if !trimmed.is_empty() {
370                    env_extension_dirs.push(PathBuf::from(trimmed));
371                }
372            }
373        }
374    }
375    let mut i = 0;
376    let mut host_arg_count = 0;
377    let mut host_tui_arg_count = 0;
378    let mut unsupported_host_rpc_flag = None;
379    while i < args.len() {
380        let arg = args[i].clone();
381        // Peel an inline `--flag=value` (long flags only — short flags never use
382        // `=`) so the match below compares bare flag names. `inline` holds the
383        // RHS for `take_value` to consume in place of the next argv token.
384        let (flag_key, inline) = if arg.starts_with("--") {
385            match arg.find('=') {
386                Some(eq) => (arg[..eq].to_string(), Some(arg[eq + 1..].to_string())),
387                None => (arg.clone(), None),
388            }
389        } else {
390            (arg.clone(), None)
391        };
392
393        // Take a value: prefer the inline `--flag=value`, else the next argv
394        // token (when it isn't flag-shaped). Advances `i` past a consumed token.
395        // (For unknown-flag diagnostics the closing arm reads `flag_key` itself.)
396        if !matches!(
397            flag_key.as_str(),
398            "--host"
399                | "--mode"
400                | "--session"
401                | "-s"
402                | "--session-id"
403                | "--session-dir"
404                | "--fork"
405                | "--fork-entry"
406                | "--fork-position"
407                | "--provider"
408                | "--model"
409                | "--resource-config"
410                | "--resource-transition"
411                | "--permission-gate"
412                | "--bypass"
413                | "--approve"
414                | "-a"
415                | "--no-approve"
416                | "-na"
417                | "--offline"
418                | "--no-native-durable"
419                | "--no-session"
420                | "--rpc-message-updates"
421                | "--help"
422                | "-h"
423                | "--version"
424                | "-v"
425        ) && flag_key.starts_with('-')
426        {
427            unsupported_host_rpc_flag.get_or_insert_with(|| flag_key.clone());
428        }
429
430        let mut take_value = |result: &mut Args, _flag: &str| -> Option<String> {
431            if let Some(v) = inline.clone() {
432                return Some(v);
433            }
434            if i + 1 < args.len() {
435                let next = &args[i + 1];
436                if !next.starts_with('-') || next == "-" {
437                    i += 1;
438                    return Some(args[i].clone());
439                }
440            }
441            result.errors.push(format!("{flag_key} requires a value"));
442            None
443        };
444
445        match flag_key.as_str() {
446            "--help" | "-h" => result.help = true,
447            "--version" | "-v" => result.version = true,
448            "--print" | "-p" => {
449                result.print = true;
450                // `-p` may consume the following positional as the prompt
451                // (TS heuristic: next is present, doesn't start with `@`, and
452                // isn't a flag — except `---` which TS lets through; we keep
453                // the simple `!@` && `!-` form).
454                if i + 1 < args.len() {
455                    let next = &args[i + 1];
456                    if !next.starts_with('@') && !next.starts_with('-') {
457                        i += 1;
458                        result.messages.push(args[i].clone());
459                    }
460                }
461            }
462            "--mode" => {
463                if let Some(v) = take_value(&mut result, "--mode") {
464                    result.mode = match v.as_str() {
465                        "text" => Mode::Text,
466                        "json" => Mode::Json,
467                        "rpc" => Mode::Rpc,
468                        other => {
469                            result.errors.push(format!(
470                                "Invalid --mode \"{other}\". Valid: text, json, rpc"
471                            ));
472                            Mode::Text
473                        }
474                    };
475                }
476            }
477            "--rpc-message-updates" => {
478                if let Some(value) = take_value(&mut result, "--rpc-message-updates") {
479                    match value.as_str() {
480                        "snapshot" => result.rpc_message_updates = RpcMessageUpdates::Snapshot,
481                        "compact-deltas" => result.rpc_message_updates = RpcMessageUpdates::CompactDeltas,
482                        other => result.errors.push(format!(
483                            "Invalid --rpc-message-updates \"{other}\". Valid: snapshot, compact-deltas"
484                        )),
485                    }
486                }
487            }
488            "--tui-mode" => {
489                if let Some(v) = take_value(&mut result, "--tui-mode") {
490                    host_tui_arg_count += if inline.is_some() { 1 } else { 2 };
491                    result.tui_mode = match v.to_ascii_lowercase().as_str() {
492                        "regular" => TuiMode::Regular,
493                        "fullscreen" => TuiMode::Fullscreen,
494                        other => {
495                            result.errors.push(format!(
496                                "Invalid --tui-mode \"{other}\". Valid: regular, fullscreen"
497                            ));
498                            TuiMode::Fullscreen
499                        }
500                    };
501                }
502            }
503            "--tui-footer" => {
504                if let Some(value) = take_value(&mut result, "--tui-footer") {
505                    host_tui_arg_count += if inline.is_some() { 1 } else { 2 };
506                    match value.as_str() {
507                        "full" => result.tui_footer = TuiFooter::Full,
508                        "context" => result.tui_footer = TuiFooter::Context,
509                        "hidden" => result.tui_footer = TuiFooter::Hidden,
510                        "auto" => result.tui_footer = TuiFooter::Auto,
511                        other => result.errors.push(format!(
512                            "Invalid --tui-footer \"{other}\". Valid: full, context, hidden, auto"
513                        )),
514                    }
515                }
516            }
517            "--continue" | "-c" => result.continue_session = true,
518            "--resume" | "-r" => result.resume = true,
519            "--host" => {
520                if result.host.is_some() {
521                    result
522                        .errors
523                        .push("--host may only be supplied once".into());
524                }
525                let area = if let Some(area) = inline {
526                    if area.is_empty() {
527                        result.errors.push("--host= requires an area name".into());
528                    }
529                    area
530                } else if let Some(next) = args.get(i + 1).filter(|next| {
531                    !next.starts_with('-') && !next.starts_with('@') && !next.is_empty()
532                }) {
533                    i += 1;
534                    host_arg_count += 1;
535                    next.clone()
536                } else {
537                    String::new()
538                };
539                host_arg_count += 1;
540                result.host = Some(area);
541            }
542            "--mini" => {
543                result.mini = true;
544                if inline.is_some() {
545                    result.errors.push("--mini does not take a value".into());
546                }
547            }
548            "--no-session" => result.no_session = true,
549            "--no-tools" | "-nt" => result.no_tools = true,
550            "--no-builtin-tools" | "-nbt" => result.no_builtin_tools = true,
551            // `--native-durable` remains accepted for scripts during the
552            // transition; `--no-native-durable` is the temporary escape hatch.
553            "--native-durable" => result.native_durable = true,
554            "--no-native-durable" => result.native_durable = false,
555            "--experimental-durable-epoch" => {
556                if result.experimental_durable_epoch.is_some() {
557                    result
558                        .errors
559                        .push("--experimental-durable-epoch may only be supplied once".into());
560                }
561                if let Some(epoch) = take_value(&mut result, "--experimental-durable-epoch") {
562                    result.experimental_durable_epoch = Some(epoch);
563                }
564            }
565            "--no-skills" | "-ns" => result.no_skills = true,
566            "--no-prompt-templates" | "-np" => result.no_prompt_templates = true,
567            "--no-context-files" | "-nc" => result.no_context_files = true,
568            "--no-extensions" | "-ne" => result.no_extensions = true,
569            "--local-only" => result.dev_local_only = true,
570            "--package-only" | "--project-only" => result.project_only = true,
571            "--extensions-dir" | "-ed" => {
572                if let Some(v) = take_value(&mut result, &flag_key) {
573                    result.extensions_dir.push(PathBuf::from(v));
574                }
575            }
576            "--verbose" => result.verbose = true,
577            "--debug-system-prompt" => result.debug_system_prompt = true,
578            "--provider" => result.provider = take_value(&mut result, "--provider"),
579            "--model" => result.model = take_value(&mut result, "--model"),
580            "--api-key" => result.api_key = take_value(&mut result, "--api-key"),
581            "--base-url" => result.base_url = take_value(&mut result, "--base-url"),
582            "--timeout" => {
583                if let Some(v) = take_value(&mut result, "--timeout") {
584                    match v.parse::<u64>() {
585                        Ok(seconds) if seconds > 0 => {
586                            result.timeout = Some(Duration::from_secs(seconds));
587                        }
588                        _ => result.errors.push(format!(
589                            "Invalid --timeout \"{v}\". Expected a positive integer number of seconds"
590                        )),
591                    }
592                }
593            }
594            "--stream-idle-timeout" => {
595                if let Some(v) = take_value(&mut result, "--stream-idle-timeout") {
596                    match v.parse::<u64>() {
597                        Ok(seconds) => result.stream_idle_timeout = Some(Duration::from_secs(seconds)),
598                        Err(_) => result.errors.push(format!(
599                            "Invalid --stream-idle-timeout \"{v}\". Expected a non-negative integer number of seconds (0 disables it)"
600                        )),
601                    }
602                }
603            }
604            "--resource-config" => {
605                result.resource_config =
606                    take_value(&mut result, "--resource-config").map(PathBuf::from)
607            }
608            "--resource-transition" => {
609                result.resource_transition =
610                    take_value(&mut result, "--resource-transition").map(PathBuf::from)
611            }
612            "--system-prompt" => result.system_prompt = take_value(&mut result, "--system-prompt"),
613            "--append-system-prompt" => {
614                if let Some(v) = take_value(&mut result, "--append-system-prompt") {
615                    result.append_system_prompt.push(v);
616                }
617            }
618            "--name" | "-n" => result.name = take_value(&mut result, "--name"),
619            "--session" => result.session = take_value(&mut result, "--session"),
620            "--session-id" => result.session_id = take_value(&mut result, "--session-id"),
621            "--fork" => result.fork = take_value(&mut result, "--fork"),
622            "--fork-entry" => {
623                if let Some(value) = take_value(&mut result, "--fork-entry") {
624                    if value.trim().is_empty() {
625                        result
626                            .errors
627                            .push("--fork-entry requires a nonempty entry ID".into());
628                    } else if result.fork_entry.replace(value).is_some() {
629                        result.errors.push("duplicate --fork-entry".into());
630                    }
631                }
632            }
633            "--fork-position" => {
634                if let Some(value) = take_value(&mut result, "--fork-position") {
635                    // Mirror `ForkPosition`'s two variants; `AT`/`BEFORE` are
636                    // accepted so the flag is not case-sensitive by accident.
637                    if result.fork_position.is_some() {
638                        result.errors.push("duplicate --fork-position".into());
639                    } else if value.eq_ignore_ascii_case("at") {
640                        result.fork_position = Some(rpi_harness::session::types::ForkPosition::At);
641                    } else if value.eq_ignore_ascii_case("before") {
642                        result.fork_position =
643                            Some(rpi_harness::session::types::ForkPosition::Before);
644                    } else {
645                        result.errors.push(format!(
646                            "Invalid --fork-position \"{value}\". Expected at or before"
647                        ));
648                    }
649                }
650            }
651            "--models" => {
652                if let Some(v) = take_value(&mut result, &flag_key) {
653                    result.models = Some(split_csv(&v));
654                }
655            }
656            "--extension" | "-e" => {
657                if let Some(v) = take_value(&mut result, &flag_key) {
658                    result.extension.push(PathBuf::from(v));
659                }
660            }
661            "--skill" => {
662                if let Some(v) = take_value(&mut result, &flag_key) {
663                    result.skill.push(PathBuf::from(v));
664                }
665            }
666            "--prompt-template" => {
667                if let Some(v) = take_value(&mut result, &flag_key) {
668                    result.prompt_template.push(PathBuf::from(v));
669                }
670            }
671            "--session-dir" => {
672                if let Some(v) = take_value(&mut result, "--session-dir") {
673                    result.session_dir = Some(PathBuf::from(v));
674                }
675            }
676            "--thinking" => {
677                if let Some(v) = take_value(&mut result, "--thinking") {
678                    match parse_thinking_level(&v) {
679                        Some(lvl) => result.thinking = Some(lvl),
680                        None => result.ignored.push(format!(
681                            "Invalid --thinking \"{v}\". Valid: {}",
682                            VALID_THINKING_LEVELS.join(", ")
683                        )),
684                    }
685                }
686            }
687            "--tools" | "-t" => {
688                if let Some(v) = take_value(&mut result, &flag_key) {
689                    result.tools = Some(split_csv(&v));
690                }
691            }
692            "--exclude-tools" | "-xt" => {
693                if let Some(v) = take_value(&mut result, &flag_key) {
694                    result.exclude_tools = Some(split_csv(&v));
695                }
696            }
697            "--list-models" => {
698                // Optionally consumes a search term, matching the native
699                // parser's bare-flag versus string distinction.
700                let mut search = inline.clone().unwrap_or_default();
701                if inline.is_none()
702                    && i + 1 < args.len()
703                    && !args[i + 1].starts_with('-')
704                    && !args[i + 1].starts_with('@')
705                {
706                    i += 1;
707                    search = args[i].clone();
708                }
709                result.list_models = Some(search);
710            }
711            "--offline" => result.offline = true,
712            "--export" => {
713                if let Some(value) = take_value(&mut result, &flag_key) {
714                    result.export = Some(PathBuf::from(value));
715                }
716            }
717            "--approve" | "-a" => result.trust_override = Some(true),
718            "--no-approve" | "-na" => result.trust_override = Some(false),
719            // ---- Recognized-but-ignored v1 scope cuts (warn, don't error) ----
720            // `flag_key` has already had any `=value` peeled, so these match the
721            // bare flag name even when the user wrote `--offline=1`.
722            //
723            // NOTE: `--no-skills`/`-ns`, `--no-prompt-templates`/`-np`,
724            // `--no-context-files`/`-nc`, `--no-extensions`/`-ne`, and
725            // `--no-themes` is honored (parsed into a real field above). The
726            // into real fields above), so they no longer reach this arm. The
727            // resource flags gate discovery in `session.rs`; plugin loading
728            // is separately opt-in.
729            other if matches!(other, "--models") => {
730                // Consume a value if the next token isn't a flag (so
731                // `--models sonnet` doesn't swallow `sonnet` as a message).
732                if inline.is_none()
733                    && i + 1 < args.len()
734                    && !args[i + 1].starts_with('-')
735                    && !args[i + 1].starts_with('@')
736                {
737                    i += 1;
738                }
739                result
740                    .ignored
741                    .push(format!("{other} is not supported in v1 (ignored)"));
742            }
743            "--theme" => {
744                result.theme = take_value(&mut result, "--theme");
745                if result.theme.is_some() {
746                    host_tui_arg_count += if inline.is_some() { 1 } else { 2 };
747                }
748            }
749            "--no-themes" => {
750                host_tui_arg_count += 1;
751                result.no_themes = true;
752            }
753            // Unknown long flag (with or without `=`). Preserve it for an
754            // extension to claim after extension registration, matching Pi's
755            // `unknownFlags` behavior. A bare flag is boolean true; a following
756            // non-flag token is its string value.
757            other if other.starts_with("--") => {
758                let name = &flag_key;
759                let value = if let Some(value) = inline {
760                    serde_json::Value::String(value)
761                } else if i + 1 < args.len()
762                    && !args[i + 1].starts_with('-')
763                    && !args[i + 1].starts_with('@')
764                {
765                    i += 1;
766                    serde_json::Value::String(args[i].clone())
767                } else {
768                    serde_json::Value::Bool(true)
769                };
770                result.unknown_flags.insert(name[2..].to_string(), value);
771            }
772            // Unknown short flag → hard error (mirrors TS).
773            other if other.starts_with('-') && other.len() > 1 => {
774                result.errors.push(format!("Unknown option: {other}"));
775            }
776            other => {
777                if let Some(path) = file_arg(other) {
778                    result.file_args.push(path);
779                } else {
780                    result.messages.push(other.to_string());
781                }
782            }
783        }
784        i += 1;
785    }
786
787    let fork_errors = result.fork_cut_errors();
788    result
789        .errors
790        .extend(fork_errors.into_iter().map(str::to_owned));
791
792    if result.host.is_some()
793        && !result.mini
794        && result.mode != Mode::Rpc
795        && args.len() != host_arg_count + host_tui_arg_count
796    {
797        result.errors.push(
798            "Host TUI accepts --tui-mode, --tui-footer, --theme and --no-themes; prompt options require --mini"
799                .into(),
800        );
801    }
802
803    if result.host.is_some() && !result.mini && result.mode == Mode::Rpc {
804        if let Some(flag) = unsupported_host_rpc_flag {
805            result
806                .errors
807                .push(format!("{flag} is not supported by Host RPC"));
808        }
809    }
810
811    if result.mini {
812        result.no_session = true;
813        result.native_durable = false;
814        for (present, flag) in [
815            (result.continue_session, "--continue"),
816            (result.resume, "--resume"),
817            (result.session.is_some(), "--session"),
818            (result.session_id.is_some(), "--session-id"),
819            (result.session_dir.is_some(), "--session-dir"),
820            (result.fork.is_some(), "--fork"),
821            (result.export.is_some(), "--export"),
822        ] {
823            if present {
824                result
825                    .errors
826                    .push(format!("--mini cannot be combined with {flag}"));
827            }
828        }
829    }
830    if result.host.is_some() && result.mini {
831        for (present, flag) in [
832            (result.name.is_some(), "--name"),
833            (result.mode != Mode::Text, "--mode json/rpc"),
834            (result.list_models.is_some(), "--list-models"),
835            (result.models.is_some(), "--models"),
836            (result.resource_config.is_some(), "--resource-config"),
837            (
838                result.resource_transition.is_some(),
839                "--resource-transition",
840            ),
841            (!result.extension.is_empty(), "--extension"),
842            (!result.extensions_dir.is_empty(), "--extensions-dir"),
843            (!result.skill.is_empty(), "--skill"),
844            (!result.prompt_template.is_empty(), "--prompt-template"),
845            (result.theme.is_some(), "--theme"),
846        ] {
847            if present {
848                result
849                    .errors
850                    .push(format!("--mini cannot be combined with {flag}"));
851            }
852        }
853        for flag in result.unknown_flags.keys() {
854            result
855                .errors
856                .push(format!("--mini does not support --{flag}"));
857        }
858    }
859    if !package && result.resource_config.is_none() && result.resource_transition.is_none() {
860        // Exact startup ignores discovery environment, but still rejects explicit CLI dirs.
861        env_extension_dirs.append(&mut result.extensions_dir);
862        result.extensions_dir = env_extension_dirs;
863    }
864    // `--print` + `--mode json`: `--print` implies non-interactive, but
865    // `--mode json` selects the JSON event stream. The TS `resolveAppMode`
866    // treats `mode === "json"` as its own non-interactive mode; we follow that.
867    if let Err(error) = crate::native_durable::experimental_epoch::policy(&result) {
868        result.errors.push(error);
869    }
870    result
871}
872
873/// Split a comma-separated list (mirrors the TS `.split(',').map(trim)`).
874fn split_csv(v: &str) -> Vec<String> {
875    v.split(',')
876        .map(|s| s.trim().to_string())
877        .filter(|s| !s.is_empty())
878        .collect()
879}
880
881/// Resolve the effective output [`Mode`]. Mirrors TS `resolveAppMode`:
882/// `rpc`→rpc, `json`→json, `print` or piped-stdin/redirected-stdout→print,
883/// else interactive. Here `stdin_is_tty`/`stdout_is_tty` come from
884/// `std::io::IsTerminal`.
885pub fn resolve_mode(parsed: &Args, stdin_is_tty: bool, stdout_is_tty: bool) -> RunMode {
886    // Check for --server flag (unknown flag stored in unknown_flags map)
887    if parsed.unknown_flags.contains_key("server") {
888        return RunMode::Rpc;
889    }
890    if parsed.mode == Mode::Rpc {
891        return RunMode::Rpc;
892    }
893    if parsed.mode == Mode::Json {
894        return RunMode::Json;
895    }
896    if parsed.print || !stdin_is_tty || !stdout_is_tty {
897        RunMode::Print
898    } else {
899        RunMode::Interactive
900    }
901}
902
903/// The concrete run mode [`resolve_mode`] picks. Mirrors TS `AppMode`
904/// (`interactive`/`print`/`json`/`rpc`). Distinguished from [`Mode`] (the raw
905/// `--mode` flag value) because the effective mode also folds in `-p` + TTY
906/// detection.
907#[derive(Debug, Clone, Copy, PartialEq, Eq)]
908pub enum RunMode {
909    Interactive,
910    Print,
911    Json,
912    Rpc,
913}
914
915/// Print the help text to stdout. Mirrors TS `printHelp`, scoped to v1 flags.
916pub fn print_help() {
917    let builtin = "read, bash, edit, write, docs";
918    println!(
919        "{name} - AI coding assistant with read, bash, edit, write, docs tools
920
921{u}Usage:{r}
922  {name} [options] [@files...] [messages...]
923
924{u}Options:{r}
925  --provider <name>              Provider name (built-in, installed package, or models.json id)
926  --model <pattern>              Model pattern or ID (supports \"provider/id\" and optional \":<thinking>\")
927  --api-key <key>                API key override for the selected provider
928  --base-url <url>               Override the selected model endpoint
929  --timeout <seconds>            LLM API request timeout (default: 600)
930  --stream-idle-timeout <seconds> Max silence between response bytes (default: 300; 0 disables)
931  --resource-capabilities       Pure bounded JSON resource protocol profile (use alone; no startup)
932  --resource-session-read <file> Strict bounded nonexecuting saved-session read (standalone)
933  --resource-transition <file>   Explicit same-session resource CAS (RPC only; see docs/resource-transition-rpc.md)
934  --resource-config <file>       Exact versioned startup resources (RPC only; see docs/resource-selection-rpc.md)
935  --system-prompt <text>         Replace the default system prompt
936  --append-system-prompt <text>  Append text to the system prompt (repeatable)
937  --thinking <level>             off, minimal, low, medium, high, xhigh, max
938  --mode <mode>                  Output mode: text (default), json, or rpc
939  --rpc-message-updates <mode>   RPC updates: compact-deltas (default) or snapshot (legacy)
940  --host [area]                  Run in a shared local Host area (Unix), in TUI, RPC, or --mini mode
941  --host[=area] --mini [prompt]   Run a one-shot text prompt in that Host
942  --server [--port <n>] [--bind <ip>]
943                                 Headless server: serve a remote-connectable agent (no TUI)
944  --native-host [area]          Join or start a persistent Host area (macOS)
945  --connect <host:port>          Remote client: connect to a `--server` instance and run the TUI
946                                 (no local provider/tools/session; all agent work is remote)
947  --token <token>                Auth token for `--connect` (printed by `--server`; may also
948                                 be provided via the RPI_SERVER_TOKEN env var)
949  --tui-mode <mode>              TUI buffer: regular or fullscreen (macOS default: regular)
950  --tui-footer <mode>            Native TUI footer: full (default), context, hidden, or auto
951  --list-models [search]         List available models (with optional fuzzy search)
952  --offline                      Disable startup network operations (same as RPI_OFFLINE=1)
953  --export <file>                Export a JSONL session to HTML and exit
954  --approve, -a                  Force-enable current-project resources
955  --no-approve, -na              Disable current-project resources
956  --print, -p                    Non-interactive: process prompt(s) and exit
957  --mini                         Use an in-memory session and disable native durable execution
958  --continue, -c                 Continue the most recent session
959  --resume, -r                   Browse and select a session to resume
960  --session <id|path>            Resume by session file path under --session-dir
961                                 or by an unambiguous ID prefix or file name fragment
962  --session-id <id>              Use the exact session id, creating it if missing
963  --fork <id|path>               Fork a session into a new one and start in the fork
964                                 (unambiguous ID prefix, file name fragment, or any session file path)
965  --fork-entry <entryId>         With --fork: cut the new branch at this message
966                                 entry. The entry id must match exactly
967  --fork-position <at|before>    With --fork-entry: keep the selected message in the
968                                 new branch (at) or drop it (before). Default: before
969  --session-dir <dir>            Directory for session storage
970{session_preview}  --no-session                   Ephemeral mode (do not persist the session)
971  --name, -n <name>              Set the session display name
972  --tools, -t <list>             Comma-separated allowlist of tool names to enable
973  --exclude-tools, -xt <list>    Comma-separated denylist of tool names to disable
974  --no-tools, -nt                Disable all tools
975  --no-builtin-tools, -nbt       Disable the built-in tools (read, bash, edit, write, docs)
976  --no-native-durable            Temporary escape hatch: use legacy session behavior
977  --experimental-durable-epoch <id>
978                                With native durable enabled: bounded v2 ledger, explicit same epoch on reopen; no migration
979  --no-skills, -ns               Skip skill discovery (no <available_skills> block)
980  --no-prompt-templates, -np     Skip prompt-template discovery (/expand templates)
981  --no-context-files, -nc        Skip AGENTS.md/CLAUDE.md discovery (no <project_context>)
982  --no-extensions, -ne           Skip Rust cdylib extension loading
983  --extensions-dir, -ed <dir>    Extra dir to scan for plugins (.dll/.so/.dylib); repeatable
984                                 (also via RPI_EXTENSIONS_DIR env: ';' on Windows, ':' on Unix)
985  --local-only                   Skip automatic extension discovery: load only
986                                 --extensions-dir / --extension paths (no project
987                                 .rpi/extensions, no global extensions)
988  --package-only, --project-only Load project skills/prompts/extensions/packages
989                                 from the active project; exclude global resources
990  --debug-system-prompt          Print the resolved system-prompt sections to stderr (verification)
991  --verbose                      Show startup warnings (e.g. ignored flags)
992  --help, -h                     Show this help
993  --version, -v                  Show version
994
995{u}Subcommands:{r}
996  host <command>                 Shared Host control: foreground serve; status/list/
997                                inspect; submit/receipt; optional profiles and
998                                administrative-* (Unix; authenticated IPC;
999                                see `rpi host --help`)
1000  update                       Update the rpi CLI from GitHub releases
1001                                (Homebrew installs use `brew upgrade rpi`)
1002  updates check --json          Report cached host/extension update state as JSON
1003  updates refresh --json        Check registries, then report update state as JSON
1004  auth login|check|logout        Manage persisted credentials in ~/.rpi/auth.json
1005                                (see `rpi auth --help`)
1006  events path|tail               Inspect the extension event journal (needs
1007                                RPI_EVENT_LOG=1; see `rpi events --help`)
1008  install <name>                 Install a published Agent package or Rust extension
1009                                (see `rpi install --help`)
1010  uninstall <crate>              Remove an installed Rust cdylib extension
1011  extension update [name]        Update project and global installed Rust extensions
1012                                (see `rpi extension update --help`)
1013  extension <command>            Manage local extension snapshots (see `rpi extension --help`)
1014  skill|skills <command>         Install published Skills and manage local snapshots (see `rpi skill --help`)
1015  run package NAME [options]               Start an installed agent package (JSONL RPC)
1016  package <command>              Manage published agent packages, local snapshots, and project links
1017                                (see `rpi package --help`)
1018  dev [options]                  Build, watch, and hot-reload a Rust extension
1019                                (see `rpi dev --help`)
1020  dev-local [options]            Debug only the current Rust extension
1021                                (shortcut for `rpi dev --local-only`)
1022
1023{u}Built-in Tools:{r}
1024  {builtin}  (enabled by default)
1025
1026{u}Examples:{r}
1027  # Interactive with an initial prompt
1028  {name} \"List all .rs files in src/\"
1029
1030  # Single-shot print mode
1031  {name} -p \"Summarize this project\"
1032
1033  # Include a file in the initial message
1034  {name} @README.md \"What does this project do?\"
1035
1036  # Continue the previous session
1037  {name} -c \"What did we discuss?\"
1038
1039  # Use a specific model + thinking level
1040  {name} --model claude-sonnet-5 --thinking high \"Refactor this\"
1041
1042  # JSON event stream (one JSON object per line on stdout)
1043  {name} --mode json -p \"Inspect the code\"
1044
1045  # Read-only: no file-modifying tools
1046  {name} --tools read,bash -p \"Review the code in src/\"
1047
1048{u}Environment:{r}
1049  ANTHROPIC_API_KEY              Anthropic API key (x-api-key) — fallback when no stored credential
1050  ANTHROPIC_AUTH_TOKEN           Bearer token (Authorization: Bearer) for third-party gateways
1051  ANTHROPIC_BASE_URL             Override the Anthropic endpoint (e.g. a compatible proxy)
1052  OPENAI_API_KEY                 Bearer token for openai-completions/responses
1053  RPI_OFFLINE                     Disable startup network operations when set to 1/true/yes
1054  RPI_CODING_AGENT_DIR           Override the ~/.rpi agent home (auth/models/settings/trust)
1055  RPI_SESSION_ID                 Session id served by a plugin (set by the host; also honored as an override)
1056
1057{u}Notes:{r}
1058  Supported HTTP protocols are Anthropic Messages and OpenAI Chat Completions.
1059  Define custom model catalogs and provider apiKey values in
1060  ~/.rpi/agent/models.json. The interactive TUI, Rust extensions, skills,
1061  prompt templates, themes, model cycling, session fork/export, and trust
1062  commands are available in the current build. OAuth, RPC, and full model
1063  cycling remain outside the current implementation.
1064",
1065        name = crate::APP_NAME,
1066        builtin = builtin,
1067        session_preview = if cfg!(unix) {
1068            "  --session-preview <uuid>       Read the recent saved transcript (standalone with --session-dir)\n"
1069        } else {
1070            ""
1071        },
1072        u = "\x1b[1m",
1073        r = "\x1b[0m",
1074    );
1075}
1076
1077/// Print the version line. Mirrors TS `--version` output (`pi <version>`).
1078pub fn print_version() {
1079    println!("{} {}", crate::APP_NAME, crate::VERSION);
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084    #[test]
1085    fn rpc_message_updates_selection_and_errors() {
1086        assert_eq!(
1087            super::Args::default().rpc_message_updates,
1088            super::RpcMessageUpdates::CompactDeltas
1089        );
1090        for (value, expected) in [
1091            ("snapshot", super::RpcMessageUpdates::Snapshot),
1092            ("compact-deltas", super::RpcMessageUpdates::CompactDeltas),
1093        ] {
1094            for args in [
1095                vec![
1096                    "--mode".into(),
1097                    "rpc".into(),
1098                    format!("--rpc-message-updates={value}"),
1099                ],
1100                vec!["--rpc-message-updates".into(), value.into()],
1101            ] {
1102                let parsed = super::parse_args(&args);
1103                assert!(parsed.errors.is_empty(), "{:?}", parsed.errors);
1104                assert_eq!(parsed.rpc_message_updates, expected);
1105                assert!(parsed.unknown_flags.is_empty());
1106            }
1107        }
1108        for args in [
1109            vec!["--rpc-message-updates".into()],
1110            vec!["--rpc-message-updates".into(), "--mode=json".into()],
1111            vec!["--rpc-message-updates=".into()],
1112            vec!["--rpc-message-updates=invalid".into()],
1113            vec!["--rpc-message-updates".into(), "invalid".into()],
1114        ] {
1115            let parsed = super::parse_args(&args);
1116            assert_eq!(parsed.errors.len(), 1);
1117            assert!(parsed.errors[0].contains("--rpc-message-updates"));
1118        }
1119        let parsed = super::parse_args(&[
1120            "--mode=json".into(),
1121            "--rpc-message-updates=snapshot".into(),
1122        ]);
1123        assert_eq!(parsed.mode, super::Mode::Json);
1124    }
1125
1126    use super::*;
1127
1128    struct RestoreOfflineEnv(Option<std::ffi::OsString>);
1129
1130    impl Drop for RestoreOfflineEnv {
1131        fn drop(&mut self) {
1132            match self.0.take() {
1133                Some(value) => std::env::set_var(RPI_OFFLINE_ENV, value),
1134                None => std::env::remove_var(RPI_OFFLINE_ENV),
1135            }
1136        }
1137    }
1138
1139    fn s(args: &[&str]) -> Vec<String> {
1140        args.iter().map(|a| a.to_string()).collect()
1141    }
1142
1143    #[test]
1144    fn parses_basic_prompt() {
1145        let a = parse_args(&s(&["hello", "world"]));
1146        assert_eq!(a.messages, vec!["hello".to_string(), "world".to_string()]);
1147        assert!(!a.help);
1148    }
1149
1150    #[test]
1151    fn parses_help_and_version() {
1152        let a = parse_args(&s(&["--help"]));
1153        assert!(a.help);
1154        let a = parse_args(&s(&["-v"]));
1155        assert!(a.version);
1156    }
1157
1158    #[test]
1159    fn print_consumes_following_positional() {
1160        let a = parse_args(&s(&["-p", "summarize"]));
1161        assert!(a.print);
1162        assert_eq!(a.messages, vec!["summarize".to_string()]);
1163    }
1164
1165    #[test]
1166    fn print_does_not_consume_file_or_flag() {
1167        let a = parse_args(&s(&["-p", "@file.md"]));
1168        assert!(a.print);
1169        assert!(a.messages.is_empty());
1170        assert_eq!(a.file_args, vec![PathBuf::from("file.md")]);
1171    }
1172
1173    #[test]
1174    fn model_and_thinking() {
1175        let a = parse_args(&s(&["--model", "claude-sonnet-5", "--thinking", "high"]));
1176        assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1177        assert_eq!(a.thinking, Some(ThinkingLevel::High));
1178    }
1179
1180    #[test]
1181    fn model_with_thinking_shorthand() {
1182        let a = parse_args(&s(&["--model", "claude-sonnet-5:high"]));
1183        // The model pattern keeps the `:high`; provider resolution splits it.
1184        assert_eq!(a.model.as_deref(), Some("claude-sonnet-5:high"));
1185    }
1186
1187    #[test]
1188    fn tools_split_csv() {
1189        let a = parse_args(&s(&["--tools", "read, bash ,write"]));
1190        assert_eq!(
1191            a.tools.as_deref(),
1192            Some(&["read".to_string(), "bash".to_string(), "write".to_string()][..])
1193        );
1194    }
1195
1196    #[test]
1197    fn native_durable_is_enabled_by_default_with_a_transition_escape_hatch() {
1198        assert!(parse_args(&s(&[])).native_durable);
1199        assert!(parse_args(&s(&["--native-durable"])).native_durable);
1200        assert!(!parse_args(&s(&["--no-native-durable"])).native_durable);
1201        assert!(parse_args(&s(&["--no-native-durable", "--native-durable"])).native_durable);
1202        assert!(!parse_args(&s(&["--native-durable", "--no-native-durable"])).native_durable);
1203    }
1204
1205    #[test]
1206    fn mini_always_disables_session_and_durable() {
1207        for argv in [
1208            ["--mini", "--native-durable", "hello"],
1209            ["--native-durable", "--mini", "hello"],
1210        ] {
1211            let args = parse_args(&s(&argv));
1212            assert!(args.mini && args.no_session && !args.native_durable);
1213            assert!(args.errors.is_empty(), "{:?}", args.errors);
1214            assert_eq!(args.messages, ["hello"]);
1215            assert_eq!(resolve_mode(&args, true, true), RunMode::Interactive);
1216        }
1217    }
1218
1219    #[test]
1220    fn mini_accepts_regular_modes_and_resource_flags() {
1221        let args = parse_args(&s(&[
1222            "--mini",
1223            "--mode",
1224            "rpc",
1225            "--tools",
1226            "read",
1227            "--extension",
1228            "extension.dylib",
1229        ]));
1230        assert!(args.errors.is_empty(), "{:?}", args.errors);
1231        assert_eq!(resolve_mode(&args, true, true), RunMode::Rpc);
1232        assert_eq!(args.tools.unwrap(), ["read"]);
1233        assert_eq!(args.extension, [PathBuf::from("extension.dylib")]);
1234    }
1235
1236    #[test]
1237    fn mini_rejects_session_and_durable_epoch_flags() {
1238        for (flags, expected) in [
1239            (&["--resume"][..], "--resume"),
1240            (&["--session-id", "saved"][..], "--session-id"),
1241            (&["--export", "session.jsonl"][..], "--export"),
1242            (
1243                &["--experimental-durable-epoch", "epoch"][..],
1244                "--experimental-durable-epoch",
1245            ),
1246        ] {
1247            let argv = ["--mini"]
1248                .into_iter()
1249                .chain(flags.iter().copied())
1250                .collect::<Vec<_>>();
1251            let args = parse_args(&s(&argv));
1252            assert!(
1253                args.errors.iter().any(|error| error.contains(expected)),
1254                "{:?}",
1255                args.errors
1256            );
1257        }
1258    }
1259
1260    #[test]
1261    fn unknown_short_flag_errors() {
1262        let a = parse_args(&s(&["-Z"]));
1263        assert!(!a.errors.is_empty());
1264    }
1265
1266    #[test]
1267    fn unknown_long_flag_is_retained_for_extensions() {
1268        let a = parse_args(&s(&["--frobnicate", "value"]));
1269        assert!(a.errors.is_empty());
1270        assert_eq!(
1271            a.unknown_flags.get("frobnicate"),
1272            Some(&serde_json::Value::String("value".into()))
1273        );
1274        assert!(a.ignored.is_empty());
1275    }
1276
1277    #[test]
1278    fn unknown_long_boolean_flag_is_retained() {
1279        let a = parse_args(&s(&["--server"]));
1280        assert_eq!(
1281            a.unknown_flags.get("server"),
1282            Some(&serde_json::Value::Bool(true))
1283        );
1284    }
1285
1286    #[test]
1287    fn unknown_long_flags_keep_string_and_equals_values() {
1288        let a = parse_args(&s(&["--port", "8080", "--bind=127.0.0.1"]));
1289        assert_eq!(
1290            a.unknown_flags.get("port"),
1291            Some(&serde_json::Value::String("8080".into()))
1292        );
1293        assert_eq!(
1294            a.unknown_flags.get("bind"),
1295            Some(&serde_json::Value::String("127.0.0.1".into()))
1296        );
1297    }
1298
1299    #[test]
1300    fn models_flag_parses_csv() {
1301        let a = parse_args(&s(&["--models", "a,b,c"]));
1302        assert!(a.errors.is_empty());
1303        assert!(a.ignored.is_empty(), "--models is implemented");
1304        assert_eq!(
1305            a.models.as_deref(),
1306            Some(&["a".to_string(), "b".to_string(), "c".to_string()][..])
1307        );
1308        // The value is consumed, not read as a message:
1309        assert!(a.messages.is_empty());
1310    }
1311
1312    #[test]
1313    fn list_models_accepts_bare_and_search_forms() {
1314        let bare = parse_args(&s(&["--list-models"]));
1315        assert_eq!(bare.list_models.as_deref(), Some(""));
1316        assert!(bare.ignored.is_empty());
1317        assert!(bare.messages.is_empty());
1318
1319        let search = parse_args(&s(&["--list-models", "claude"]));
1320        assert_eq!(search.list_models.as_deref(), Some("claude"));
1321        assert!(search.messages.is_empty());
1322
1323        let inline = parse_args(&s(&["--list-models=gpt"]));
1324        assert_eq!(inline.list_models.as_deref(), Some("gpt"));
1325    }
1326
1327    #[test]
1328    fn offline_flag_is_honored_without_warning() {
1329        let args = parse_args(&s(&["--offline"]));
1330        assert!(args.offline);
1331        assert!(args.ignored.is_empty());
1332    }
1333
1334    #[test]
1335    fn timeout_parses_seconds_in_separate_and_equals_forms() {
1336        let separate = parse_args(&s(&["--timeout", "45"]));
1337        assert!(separate.errors.is_empty());
1338        assert_eq!(separate.timeout, Some(Duration::from_secs(45)));
1339
1340        let inline = parse_args(&s(&["--timeout=90"]));
1341        assert!(inline.errors.is_empty());
1342        assert_eq!(inline.timeout, Some(Duration::from_secs(90)));
1343    }
1344
1345    #[test]
1346    fn timeout_rejects_zero_and_invalid_values() {
1347        for value in ["0", "1.5", "forever", "18446744073709551616"] {
1348            let args = parse_args(&s(&[&format!("--timeout={value}")]));
1349            assert_eq!(args.errors.len(), 1, "value: {value}");
1350            assert!(args.timeout.is_none(), "value: {value}");
1351        }
1352    }
1353
1354    #[test]
1355    fn stream_idle_timeout_accepts_both_forms_and_zero_but_rejects_invalid_values() {
1356        for (argv, seconds) in [
1357            (s(&["--stream-idle-timeout", "45"]), 45),
1358            (s(&["--stream-idle-timeout=90"]), 90),
1359            (s(&["--stream-idle-timeout=0"]), 0),
1360        ] {
1361            let args = parse_args(&argv);
1362            assert!(args.errors.is_empty(), "{:?}", args.errors);
1363            assert_eq!(args.stream_idle_timeout, Some(Duration::from_secs(seconds)));
1364            assert!(args.timeout.is_none());
1365        }
1366        for value in ["-1", "1.5", "no", "18446744073709551616"] {
1367            let args = parse_args(&s(&[&format!("--stream-idle-timeout={value}")]));
1368            assert!(!args.errors.is_empty(), "{value}");
1369            assert!(args.stream_idle_timeout.is_none());
1370        }
1371        assert!(!parse_args(&s(&["--stream-idle-timeout"])).errors.is_empty());
1372    }
1373
1374    #[test]
1375    fn native_pi_offline_truthy_values_are_case_insensitive() {
1376        for value in [
1377            Some("1"),
1378            Some("true"),
1379            Some("TRUE"),
1380            Some("Yes"),
1381            Some("yEs"),
1382        ] {
1383            assert!(is_truthy_env_flag(value), "value={value:?}");
1384        }
1385        for value in [
1386            None,
1387            Some(""),
1388            Some("0"),
1389            Some("false"),
1390            Some("no"),
1391            Some(" true "),
1392        ] {
1393            assert!(!is_truthy_env_flag(value), "value={value:?}");
1394        }
1395    }
1396
1397    #[test]
1398    fn pi_offline_env_and_cli_flag_share_one_normalized_gate() {
1399        let _guard = crate::config::test_support::env_lock().lock().unwrap();
1400        let _restore = RestoreOfflineEnv(std::env::var_os(RPI_OFFLINE_ENV));
1401
1402        std::env::set_var(RPI_OFFLINE_ENV, "YeS");
1403        assert!(parse_args(&[]).offline);
1404        assert!(normalize_offline_mode(&[]));
1405        assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
1406
1407        std::env::set_var(RPI_OFFLINE_ENV, "0");
1408        assert!(!parse_args(&[]).offline);
1409        let argv = s(&["--offline"]);
1410        assert!(normalize_offline_mode(&argv));
1411        assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
1412    }
1413
1414    #[test]
1415    fn project_trust_flags_are_honored_without_warning() {
1416        let approved = parse_args(&s(&["--approve"]));
1417        assert_eq!(approved.trust_override, Some(true));
1418        assert!(approved.ignored.is_empty());
1419        let denied = parse_args(&s(&["--no-approve"]));
1420        assert_eq!(denied.trust_override, Some(false));
1421        assert!(denied.ignored.is_empty());
1422    }
1423
1424    #[test]
1425    fn export_flag_captures_input_and_output_position() {
1426        let args = parse_args(&s(&["--export", "session.jsonl", "transcript.html"]));
1427        assert_eq!(args.export, Some(PathBuf::from("session.jsonl")));
1428        assert_eq!(args.messages, vec!["transcript.html".to_string()]);
1429        assert!(args.ignored.is_empty());
1430    }
1431
1432    #[test]
1433    fn session_id_and_fork_flags_parse() {
1434        let a = parse_args(&s(&["--session-id", "01abc", "--fork", "xyz"]));
1435        assert!(a.errors.is_empty());
1436        assert_eq!(a.session_id.as_deref(), Some("01abc"));
1437        assert_eq!(a.fork.as_deref(), Some("xyz"));
1438        assert_eq!(a.fork_entry, None);
1439        assert_eq!(
1440            a.fork_position, None,
1441            "an explicit entry must keep the harness default (before), not force a position"
1442        );
1443        let a = parse_args(&s(&[
1444            "--fork",
1445            "xyz",
1446            "--fork-entry",
1447            "message-2",
1448            "--fork-position",
1449            "before",
1450        ]));
1451        assert!(a.errors.is_empty());
1452        assert_eq!(a.fork_entry.as_deref(), Some("message-2"));
1453        assert_eq!(
1454            a.fork_position,
1455            Some(rpi_harness::session::types::ForkPosition::Before)
1456        );
1457        let a = parse_args(&s(&["--fork-position", "middle"]));
1458        assert_eq!(a.fork_position, None);
1459        assert_eq!(
1460            a.errors,
1461            vec!["Invalid --fork-position \"middle\". Expected at or before".to_string()]
1462        );
1463        let a = parse_args(&s(&[
1464            "-e",
1465            "plugin.dll",
1466            "--skill",
1467            "s",
1468            "--prompt-template",
1469            "t.md",
1470        ]));
1471        assert_eq!(a.extension.len(), 1);
1472        assert_eq!(a.skill.len(), 1);
1473        assert_eq!(a.prompt_template.len(), 1);
1474    }
1475
1476    #[test]
1477    fn fork_cut_flags_are_reserved_and_require_an_active_fork() {
1478        let args = parse_args(&s(&[
1479            "--fork-entry=entry-1",
1480            "--fork",
1481            "source",
1482            "--fork-position",
1483            "at",
1484            "--extension-option=keep",
1485        ]));
1486        assert!(args.errors.is_empty(), "{:?}", args.errors);
1487        assert_eq!(
1488            args.unknown_flags,
1489            BTreeMap::from([("extension-option".into(), serde_json::json!("keep"))])
1490        );
1491        for argv in [
1492            &["--fork-entry", "entry-1"][..],
1493            &["--fork", "source", "--fork-position", "at"],
1494            &[
1495                "--fork",
1496                "source",
1497                "--fork-entry",
1498                "entry-1",
1499                "--no-session",
1500            ],
1501            &["--fork", "source", "--fork-entry", "entry-1", "--resume"],
1502            &[
1503                "--fork",
1504                "source",
1505                "--fork-entry",
1506                "entry-1",
1507                "--fork-position=after",
1508            ],
1509            &[
1510                "--fork",
1511                "source",
1512                "--fork-entry=entry-1",
1513                "--fork-entry=entry-2",
1514            ],
1515            &["--fork", "source", "--fork-entry="],
1516        ] {
1517            assert!(!parse_args(&s(argv)).errors.is_empty(), "{argv:?}");
1518        }
1519    }
1520
1521    #[test]
1522    fn fork_position_is_case_insensitive() {
1523        use rpi_harness::session::types::ForkPosition;
1524        for (value, expected) in [
1525            ("at", ForkPosition::At),
1526            ("At", ForkPosition::At),
1527            ("AT", ForkPosition::At),
1528            ("before", ForkPosition::Before),
1529            ("Before", ForkPosition::Before),
1530            ("BEFORE", ForkPosition::Before),
1531        ] {
1532            let a = parse_args(&s(&[
1533                "--fork",
1534                "xyz",
1535                "--fork-entry",
1536                "message-2",
1537                "--fork-position",
1538                value,
1539            ]));
1540            assert!(a.errors.is_empty(), "{value}: {:?}", a.errors);
1541            assert_eq!(a.fork_position, Some(expected), "{value}");
1542        }
1543    }
1544
1545    /// `--fork-entry` is only read inside `SessionSelection::Fork`, and
1546    /// `--fork-position` only makes sense alongside an explicit entry: without
1547    /// one it reaches the harness as `entry_id: None, position: Some(Before)`
1548    /// and truncates the current leaf from the child.
1549    #[test]
1550    fn fork_cut_flags_require_fork() {
1551        let a = parse_args(&s(&["--fork-entry", "message-2", "--print", "hi"]));
1552        assert_eq!(a.errors, vec!["--fork-entry requires --fork".to_string()]);
1553
1554        // `--fork-position` alone is missing both prerequisites; the existing
1555        // rule stays, and the new entry rule is reported alongside it.
1556        let a = parse_args(&s(&["--fork-position", "before"]));
1557        assert_eq!(
1558            a.errors,
1559            vec![
1560                "--fork-position requires --fork".to_string(),
1561                "--fork-position requires --fork-entry".to_string(),
1562            ]
1563        );
1564
1565        // Both flags together report once each, in flag order.
1566        let a = parse_args(&s(&["--fork-position=at", "--fork-entry=message-2"]));
1567        assert_eq!(
1568            a.errors,
1569            vec![
1570                "--fork-entry requires --fork".to_string(),
1571                "--fork-position requires --fork".to_string(),
1572            ]
1573        );
1574
1575        // With `--fork` they parse cleanly.
1576        let a = parse_args(&s(&[
1577            "--fork",
1578            "xyz",
1579            "--fork-entry",
1580            "message-2",
1581            "--fork-position",
1582            "at",
1583        ]));
1584        assert!(a.errors.is_empty(), "{:?}", a.errors);
1585    }
1586
1587    /// The reviewer's P2: `--fork-position` without `--fork-entry` is not
1588    /// inert — the harness takes the current leaf as the implicit target and
1589    /// then applies `Before`, dropping it from the child. Cover both position
1590    /// values, both argv spellings, and the no-`--fork` combination.
1591    #[test]
1592    fn fork_position_requires_fork_entry() {
1593        for value in ["at", "before", "AT", "BEFORE"] {
1594            // Separate-value form.
1595            let a = parse_args(&s(&["--fork", "xyz", "--fork-position", value]));
1596            assert_eq!(
1597                a.errors,
1598                vec!["--fork-position requires --fork-entry".to_string()],
1599                "{value}: the flag is not inert"
1600            );
1601            assert!(a.fork_position.is_some(), "{value}");
1602
1603            // Inline `--flag=value` form.
1604            let flag = format!("--fork-position={value}");
1605            let a = parse_args(&s(&["--fork", "xyz", &flag]));
1606            assert_eq!(
1607                a.errors,
1608                vec!["--fork-position requires --fork-entry".to_string()],
1609                "{flag}: the flag is not inert"
1610            );
1611        }
1612
1613        // With --fork-entry present, both forms are accepted.
1614        let a = parse_args(&s(&[
1615            "--fork",
1616            "xyz",
1617            "--fork-entry",
1618            "message-2",
1619            "--fork-position=before",
1620        ]));
1621        assert!(a.errors.is_empty(), "{:?}", a.errors);
1622        assert_eq!(
1623            a.fork_position,
1624            Some(rpi_harness::session::types::ForkPosition::Before)
1625        );
1626    }
1627
1628    #[test]
1629    fn no_skills_flag_honored() {
1630        let a = parse_args(&s(&["-ns"]));
1631        assert!(a.errors.is_empty());
1632        assert!(a.no_skills);
1633        // Honored flags do NOT also warn-ignore themselves.
1634        assert!(a.ignored.is_empty());
1635    }
1636
1637    #[test]
1638    fn no_prompt_templates_flag_honored() {
1639        let a = parse_args(&s(&["--no-prompt-templates"]));
1640        assert!(a.no_prompt_templates);
1641        assert!(a.ignored.is_empty());
1642    }
1643
1644    #[test]
1645    fn no_context_files_flag_honored() {
1646        let a = parse_args(&s(&["-nc"]));
1647        assert!(a.no_context_files);
1648        assert!(a.ignored.is_empty());
1649    }
1650
1651    #[test]
1652    fn no_extensions_flag_honored() {
1653        // `--no-extensions` is parsed and disables both extension backends.
1654        let a = parse_args(&s(&["--no-extensions"]));
1655        assert!(a.no_extensions);
1656        assert!(a.ignored.is_empty());
1657    }
1658
1659    #[test]
1660    fn local_only_flag_is_honored_on_the_regular_parser() {
1661        // The plain `rpi --local-only` form sets the same scope `rpi dev
1662        // --local-only` uses, without the build/watch layer.
1663        let a = parse_args(&s(&["--local-only"]));
1664        assert!(a.errors.is_empty());
1665        assert!(a.dev_local_only);
1666        assert!(a.ignored.is_empty());
1667    }
1668
1669    #[test]
1670    fn project_only_aliases_are_honored() {
1671        for flag in ["--package-only", "--project-only"] {
1672            let a = parse_args(&s(&[flag]));
1673            assert!(a.errors.is_empty());
1674            assert!(a.project_only);
1675            assert!(a.ignored.is_empty());
1676        }
1677    }
1678
1679    #[test]
1680    fn extensions_dir_flag_collects_dirs() {
1681        let a = parse_args(&s(&["--extensions-dir", "/a/b", "-ed", "/c/d"]));
1682        assert_eq!(
1683            a.extensions_dir,
1684            vec![PathBuf::from("/a/b"), PathBuf::from("/c/d")]
1685        );
1686        assert!(a.ignored.is_empty());
1687    }
1688
1689    #[test]
1690    fn extensions_dir_inline_equals_form() {
1691        let a = parse_args(&s(&["--extensions-dir=/x/y"]));
1692        assert_eq!(a.extensions_dir, vec![PathBuf::from("/x/y")]);
1693    }
1694
1695    #[test]
1696    fn extensions_dir_env_is_merged() {
1697        // The env var contributes its split list. We can't fully control env in
1698        // a unit test without `set_var` (process-global + racy under parallel
1699        // tests), so this asserts the flag path only; the env path is exercised
1700        // by the B2 smoke. Keep the test green regardless of the host env by
1701        // NOT asserting emptiness — just confirm the flag appends after env.
1702        let a = parse_args(&s(&["--extensions-dir", "/flag/only"]));
1703        assert!(a
1704            .extensions_dir
1705            .iter()
1706            .any(|p| p == &PathBuf::from("/flag/only")));
1707    }
1708
1709    #[test]
1710    fn file_args_stripped() {
1711        let a = parse_args(&s(&["@a.txt", "@b.md", "hi"]));
1712        assert_eq!(
1713            a.file_args,
1714            vec![PathBuf::from("a.txt"), PathBuf::from("b.md")]
1715        );
1716        assert_eq!(a.messages, vec!["hi".to_string()]);
1717    }
1718
1719    #[test]
1720    fn equals_form_supported() {
1721        let a = parse_args(&s(&["--model=claude-sonnet-5", "--thinking=low"]));
1722        assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1723        assert_eq!(a.thinking, Some(ThinkingLevel::Low));
1724    }
1725
1726    #[test]
1727    fn theme_flag_is_honored() {
1728        let a = parse_args(&s(&["--theme", "ocean.json"]));
1729        assert_eq!(a.theme.as_deref(), Some("ocean.json"));
1730        assert!(a.ignored.is_empty());
1731    }
1732
1733    #[test]
1734    fn no_themes_is_honored() {
1735        let a = parse_args(&s(&["--no-themes"]));
1736        assert!(a.no_themes);
1737        assert!(a.ignored.is_empty());
1738    }
1739
1740    #[test]
1741    fn tui_mode_parses_and_validates() {
1742        assert_eq!(
1743            parse_args(&s(&["--tui-mode", "regular"])).tui_mode,
1744            TuiMode::Regular
1745        );
1746        assert_eq!(
1747            parse_args(&s(&["--tui-mode=fullscreen"])).tui_mode,
1748            TuiMode::Fullscreen
1749        );
1750        let invalid = parse_args(&s(&["--tui-mode", "split"]));
1751        assert!(!invalid.errors.is_empty());
1752    }
1753
1754    #[test]
1755    fn tui_footer_parses_and_validates() {
1756        assert_eq!(parse_args(&[]).tui_footer, TuiFooter::Full);
1757        for (value, mode) in [
1758            ("full", TuiFooter::Full),
1759            ("context", TuiFooter::Context),
1760            ("hidden", TuiFooter::Hidden),
1761            ("auto", TuiFooter::Auto),
1762        ] {
1763            let args = parse_args(&s(&["--host=work", &format!("--tui-footer={value}")]));
1764            assert!(args.errors.is_empty(), "{:?}", args.errors);
1765            assert_eq!(args.tui_footer, mode);
1766        }
1767        let args = parse_args(&s(&["--tui-footer", "hidden"]));
1768        assert!(args.errors.is_empty());
1769        assert_eq!(args.tui_footer, TuiFooter::Hidden);
1770        assert!(!parse_args(&s(&["--tui-footer=invalid"])).errors.is_empty());
1771        assert!(!parse_args(&s(&["--tui-footer"])).errors.is_empty());
1772    }
1773
1774    #[test]
1775    fn host_accepts_terminal_presentation_flags() {
1776        let args = parse_args(&s(&[
1777            "--host",
1778            "work",
1779            "--tui-mode",
1780            "regular",
1781            "--theme=light",
1782        ]));
1783        assert!(args.errors.is_empty(), "{:?}", args.errors);
1784        assert_eq!(args.host.as_deref(), Some("work"));
1785        assert_eq!(args.tui_mode, TuiMode::Regular);
1786        assert_eq!(args.theme.as_deref(), Some("light"));
1787
1788        let args = parse_args(&s(&["--no-themes", "--tui-mode=fullscreen", "--host=work"]));
1789        assert!(args.errors.is_empty(), "{:?}", args.errors);
1790        assert_eq!(args.tui_mode, TuiMode::Fullscreen);
1791        assert!(args.no_themes);
1792        assert!(!parse_args(&s(&["--host", "--provider", "fixture"]))
1793            .errors
1794            .is_empty());
1795    }
1796
1797    #[test]
1798    fn tui_mode_default_preserves_native_macos_scrollback() {
1799        assert_eq!(default_tui_mode_for(true), TuiMode::Regular);
1800        assert_eq!(default_tui_mode_for(false), TuiMode::Fullscreen);
1801    }
1802
1803    #[test]
1804    fn resolve_mode_interactive_when_tty() {
1805        let a = Args {
1806            print: true,
1807            ..Args::default()
1808        };
1809        assert_eq!(resolve_mode(&a, true, true), RunMode::Print);
1810        let a = Args::default();
1811        assert_eq!(resolve_mode(&a, true, true), RunMode::Interactive);
1812        let a = Args {
1813            mode: Mode::Json,
1814            ..Args::default()
1815        };
1816        assert_eq!(resolve_mode(&a, true, true), RunMode::Json);
1817        let a = Args {
1818            mode: Mode::Rpc,
1819            ..Args::default()
1820        };
1821        assert_eq!(resolve_mode(&a, true, true), RunMode::Rpc);
1822    }
1823
1824    #[test]
1825    fn piped_stdout_forces_print() {
1826        let a = Args::default();
1827        // stdout not a TTY ⇒ print even without -p (mirrors TS).
1828        assert_eq!(resolve_mode(&a, true, false), RunMode::Print);
1829    }
1830}