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