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