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>            Use a specific session (partial UUID or file)
933  --session-id <id>              Use the exact session id, creating it if missing
934  --fork <id|path>               Fork a session into a new one and start in the fork
935                                 (partial UUID, file name fragment, or file path)
936  --fork-entry <entryId>         With --fork: cut the new branch at this message
937                                 entry. The entry id must match exactly
938  --fork-position <at|before>    With --fork-entry: keep the selected message in the
939                                 new branch (at) or drop it (before). Default: before
940  --session-dir <dir>            Directory for session storage
941{session_preview}  --no-session                   Ephemeral mode (do not persist the session)
942  --name, -n <name>              Set the session display name
943  --tools, -t <list>             Comma-separated allowlist of tool names to enable
944  --exclude-tools, -xt <list>    Comma-separated denylist of tool names to disable
945  --no-tools, -nt                Disable all tools
946  --no-builtin-tools, -nbt       Disable the built-in tools (read, bash, edit, write, docs)
947  --no-native-durable            Temporary escape hatch: use legacy session behavior
948  --experimental-durable-epoch <id>
949                                With native durable enabled: bounded v2 ledger, explicit same epoch on reopen; no migration
950  --no-skills, -ns               Skip skill discovery (no <available_skills> block)
951  --no-prompt-templates, -np     Skip prompt-template discovery (/expand templates)
952  --no-context-files, -nc        Skip AGENTS.md/CLAUDE.md discovery (no <project_context>)
953  --no-extensions, -ne           Skip Rust cdylib extension loading
954  --extensions-dir, -ed <dir>    Extra dir to scan for plugins (.dll/.so/.dylib); repeatable
955                                 (also via RPI_EXTENSIONS_DIR env: ';' on Windows, ':' on Unix)
956  --local-only                   Skip automatic extension discovery: load only
957                                 --extensions-dir / --extension paths (no project
958                                 .rpi/extensions, no global extensions)
959  --package-only, --project-only Load project skills/prompts/extensions/packages
960                                 from the active project; exclude global resources
961  --debug-system-prompt          Print the resolved system-prompt sections to stderr (verification)
962  --verbose                      Show startup warnings (e.g. ignored flags)
963  --help, -h                     Show this help
964  --version, -v                  Show version
965
966{u}Subcommands:{r}
967  host <command>                 Shared Host control: foreground serve; status/list/
968                                inspect; submit/receipt; optional profiles and
969                                administrative-* (Unix; authenticated IPC;
970                                see `rpi host --help`)
971  update                       Update the rpi CLI from GitHub releases
972                                (Homebrew installs use `brew upgrade rpi`)
973  updates check --json          Report cached host/extension update state as JSON
974  updates refresh --json        Check registries, then report update state as JSON
975  auth login|check|logout        Manage persisted credentials in ~/.rpi/auth.json
976                                (see `rpi auth --help`)
977  events path|tail               Inspect the extension event journal (needs
978                                RPI_EVENT_LOG=1; see `rpi events --help`)
979  install <crate>                Install a prebuilt Rust extension (--build for source)
980                                (see `rpi install --help`)
981  uninstall <crate>              Remove an installed Rust cdylib extension
982  extension update [name]        Update project and global installed Rust extensions
983                                (see `rpi extension update --help`)
984  install package NAME [--version VERSION | --manifest URL]  Install a published agent package
985  update package NAME [--version VERSION | --manifest URL]   Update a published agent package
986  run package NAME [options]               Start an installed agent package (JSONL RPC)
987  package link|list|update|unlink Manage project-local Rust extension packages
988                                (update is a legacy alias; see `rpi package --help`)
989  dev [options]                  Build, watch, and hot-reload a Rust extension
990                                (see `rpi dev --help`)
991  dev-local [options]            Debug only the current Rust extension
992                                (shortcut for `rpi dev --local-only`)
993
994{u}Built-in Tools:{r}
995  {builtin}  (enabled by default)
996
997{u}Examples:{r}
998  # Interactive with an initial prompt
999  {name} \"List all .rs files in src/\"
1000
1001  # Single-shot print mode
1002  {name} -p \"Summarize this project\"
1003
1004  # Include a file in the initial message
1005  {name} @README.md \"What does this project do?\"
1006
1007  # Continue the previous session
1008  {name} -c \"What did we discuss?\"
1009
1010  # Use a specific model + thinking level
1011  {name} --model claude-sonnet-5 --thinking high \"Refactor this\"
1012
1013  # JSON event stream (one JSON object per line on stdout)
1014  {name} --mode json -p \"Inspect the code\"
1015
1016  # Read-only: no file-modifying tools
1017  {name} --tools read,bash -p \"Review the code in src/\"
1018
1019{u}Environment:{r}
1020  ANTHROPIC_API_KEY              Anthropic API key (x-api-key) — fallback when no stored credential
1021  ANTHROPIC_AUTH_TOKEN           Bearer token (Authorization: Bearer) for third-party gateways
1022  ANTHROPIC_BASE_URL             Override the Anthropic endpoint (e.g. a compatible proxy)
1023  OPENAI_API_KEY                 Bearer token for openai-completions/responses
1024  RPI_OFFLINE                     Disable startup network operations when set to 1/true/yes
1025  RPI_CODING_AGENT_DIR           Override the ~/.rpi agent home (auth/models/settings/trust)
1026  RPI_SESSION_ID                 Session id served by a plugin (set by the host; also honored as an override)
1027
1028{u}Notes:{r}
1029  Supported HTTP protocols are Anthropic Messages and OpenAI Chat Completions.
1030  Define custom model catalogs and provider apiKey values in
1031  ~/.rpi/agent/models.json. The interactive TUI, Rust extensions, skills,
1032  prompt templates, themes, model cycling, session fork/export, and trust
1033  commands are available in the current build. OAuth, RPC, and full model
1034  cycling remain outside the current implementation.
1035",
1036        name = crate::APP_NAME,
1037        builtin = builtin,
1038        session_preview = if cfg!(unix) {
1039            "  --session-preview <uuid>       Read the recent saved transcript (standalone with --session-dir)\n"
1040        } else {
1041            ""
1042        },
1043        u = "\x1b[1m",
1044        r = "\x1b[0m",
1045    );
1046}
1047
1048/// Print the version line. Mirrors TS `--version` output (`pi <version>`).
1049pub fn print_version() {
1050    println!("{} {}", crate::APP_NAME, crate::VERSION);
1051}
1052
1053#[cfg(test)]
1054mod tests {
1055    #[test]
1056    fn rpc_message_updates_selection_and_errors() {
1057        assert_eq!(
1058            super::Args::default().rpc_message_updates,
1059            super::RpcMessageUpdates::CompactDeltas
1060        );
1061        for (value, expected) in [
1062            ("snapshot", super::RpcMessageUpdates::Snapshot),
1063            ("compact-deltas", super::RpcMessageUpdates::CompactDeltas),
1064        ] {
1065            for args in [
1066                vec![
1067                    "--mode".into(),
1068                    "rpc".into(),
1069                    format!("--rpc-message-updates={value}"),
1070                ],
1071                vec!["--rpc-message-updates".into(), value.into()],
1072            ] {
1073                let parsed = super::parse_args(&args);
1074                assert!(parsed.errors.is_empty(), "{:?}", parsed.errors);
1075                assert_eq!(parsed.rpc_message_updates, expected);
1076                assert!(parsed.unknown_flags.is_empty());
1077            }
1078        }
1079        for args in [
1080            vec!["--rpc-message-updates".into()],
1081            vec!["--rpc-message-updates".into(), "--mode=json".into()],
1082            vec!["--rpc-message-updates=".into()],
1083            vec!["--rpc-message-updates=invalid".into()],
1084            vec!["--rpc-message-updates".into(), "invalid".into()],
1085        ] {
1086            let parsed = super::parse_args(&args);
1087            assert_eq!(parsed.errors.len(), 1);
1088            assert!(parsed.errors[0].contains("--rpc-message-updates"));
1089        }
1090        let parsed = super::parse_args(&[
1091            "--mode=json".into(),
1092            "--rpc-message-updates=snapshot".into(),
1093        ]);
1094        assert_eq!(parsed.mode, super::Mode::Json);
1095    }
1096
1097    use super::*;
1098
1099    struct RestoreOfflineEnv(Option<std::ffi::OsString>);
1100
1101    impl Drop for RestoreOfflineEnv {
1102        fn drop(&mut self) {
1103            match self.0.take() {
1104                Some(value) => std::env::set_var(RPI_OFFLINE_ENV, value),
1105                None => std::env::remove_var(RPI_OFFLINE_ENV),
1106            }
1107        }
1108    }
1109
1110    fn s(args: &[&str]) -> Vec<String> {
1111        args.iter().map(|a| a.to_string()).collect()
1112    }
1113
1114    #[test]
1115    fn parses_basic_prompt() {
1116        let a = parse_args(&s(&["hello", "world"]));
1117        assert_eq!(a.messages, vec!["hello".to_string(), "world".to_string()]);
1118        assert!(!a.help);
1119    }
1120
1121    #[test]
1122    fn parses_help_and_version() {
1123        let a = parse_args(&s(&["--help"]));
1124        assert!(a.help);
1125        let a = parse_args(&s(&["-v"]));
1126        assert!(a.version);
1127    }
1128
1129    #[test]
1130    fn print_consumes_following_positional() {
1131        let a = parse_args(&s(&["-p", "summarize"]));
1132        assert!(a.print);
1133        assert_eq!(a.messages, vec!["summarize".to_string()]);
1134    }
1135
1136    #[test]
1137    fn print_does_not_consume_file_or_flag() {
1138        let a = parse_args(&s(&["-p", "@file.md"]));
1139        assert!(a.print);
1140        assert!(a.messages.is_empty());
1141        assert_eq!(a.file_args, vec![PathBuf::from("file.md")]);
1142    }
1143
1144    #[test]
1145    fn model_and_thinking() {
1146        let a = parse_args(&s(&["--model", "claude-sonnet-5", "--thinking", "high"]));
1147        assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1148        assert_eq!(a.thinking, Some(ThinkingLevel::High));
1149    }
1150
1151    #[test]
1152    fn model_with_thinking_shorthand() {
1153        let a = parse_args(&s(&["--model", "claude-sonnet-5:high"]));
1154        // The model pattern keeps the `:high`; provider resolution splits it.
1155        assert_eq!(a.model.as_deref(), Some("claude-sonnet-5:high"));
1156    }
1157
1158    #[test]
1159    fn tools_split_csv() {
1160        let a = parse_args(&s(&["--tools", "read, bash ,write"]));
1161        assert_eq!(
1162            a.tools.as_deref(),
1163            Some(&["read".to_string(), "bash".to_string(), "write".to_string()][..])
1164        );
1165    }
1166
1167    #[test]
1168    fn native_durable_is_enabled_by_default_with_a_transition_escape_hatch() {
1169        assert!(parse_args(&s(&[])).native_durable);
1170        assert!(parse_args(&s(&["--native-durable"])).native_durable);
1171        assert!(!parse_args(&s(&["--no-native-durable"])).native_durable);
1172        assert!(parse_args(&s(&["--no-native-durable", "--native-durable"])).native_durable);
1173        assert!(!parse_args(&s(&["--native-durable", "--no-native-durable"])).native_durable);
1174    }
1175
1176    #[test]
1177    fn mini_always_disables_session_and_durable() {
1178        for argv in [
1179            ["--mini", "--native-durable", "hello"],
1180            ["--native-durable", "--mini", "hello"],
1181        ] {
1182            let args = parse_args(&s(&argv));
1183            assert!(args.mini && args.no_session && !args.native_durable);
1184            assert!(args.errors.is_empty(), "{:?}", args.errors);
1185            assert_eq!(args.messages, ["hello"]);
1186            assert_eq!(resolve_mode(&args, true, true), RunMode::Interactive);
1187        }
1188    }
1189
1190    #[test]
1191    fn mini_accepts_regular_modes_and_resource_flags() {
1192        let args = parse_args(&s(&[
1193            "--mini",
1194            "--mode",
1195            "rpc",
1196            "--tools",
1197            "read",
1198            "--extension",
1199            "extension.dylib",
1200        ]));
1201        assert!(args.errors.is_empty(), "{:?}", args.errors);
1202        assert_eq!(resolve_mode(&args, true, true), RunMode::Rpc);
1203        assert_eq!(args.tools.unwrap(), ["read"]);
1204        assert_eq!(args.extension, [PathBuf::from("extension.dylib")]);
1205    }
1206
1207    #[test]
1208    fn mini_rejects_session_and_durable_epoch_flags() {
1209        for (flags, expected) in [
1210            (&["--resume"][..], "--resume"),
1211            (&["--session-id", "saved"][..], "--session-id"),
1212            (&["--export", "session.jsonl"][..], "--export"),
1213            (
1214                &["--experimental-durable-epoch", "epoch"][..],
1215                "--experimental-durable-epoch",
1216            ),
1217        ] {
1218            let argv = ["--mini"]
1219                .into_iter()
1220                .chain(flags.iter().copied())
1221                .collect::<Vec<_>>();
1222            let args = parse_args(&s(&argv));
1223            assert!(
1224                args.errors.iter().any(|error| error.contains(expected)),
1225                "{:?}",
1226                args.errors
1227            );
1228        }
1229    }
1230
1231    #[test]
1232    fn unknown_short_flag_errors() {
1233        let a = parse_args(&s(&["-Z"]));
1234        assert!(!a.errors.is_empty());
1235    }
1236
1237    #[test]
1238    fn unknown_long_flag_is_retained_for_extensions() {
1239        let a = parse_args(&s(&["--frobnicate", "value"]));
1240        assert!(a.errors.is_empty());
1241        assert_eq!(
1242            a.unknown_flags.get("frobnicate"),
1243            Some(&serde_json::Value::String("value".into()))
1244        );
1245        assert!(a.ignored.is_empty());
1246    }
1247
1248    #[test]
1249    fn unknown_long_boolean_flag_is_retained() {
1250        let a = parse_args(&s(&["--server"]));
1251        assert_eq!(
1252            a.unknown_flags.get("server"),
1253            Some(&serde_json::Value::Bool(true))
1254        );
1255    }
1256
1257    #[test]
1258    fn unknown_long_flags_keep_string_and_equals_values() {
1259        let a = parse_args(&s(&["--port", "8080", "--bind=127.0.0.1"]));
1260        assert_eq!(
1261            a.unknown_flags.get("port"),
1262            Some(&serde_json::Value::String("8080".into()))
1263        );
1264        assert_eq!(
1265            a.unknown_flags.get("bind"),
1266            Some(&serde_json::Value::String("127.0.0.1".into()))
1267        );
1268    }
1269
1270    #[test]
1271    fn models_flag_parses_csv() {
1272        let a = parse_args(&s(&["--models", "a,b,c"]));
1273        assert!(a.errors.is_empty());
1274        assert!(a.ignored.is_empty(), "--models is implemented");
1275        assert_eq!(
1276            a.models.as_deref(),
1277            Some(&["a".to_string(), "b".to_string(), "c".to_string()][..])
1278        );
1279        // The value is consumed, not read as a message:
1280        assert!(a.messages.is_empty());
1281    }
1282
1283    #[test]
1284    fn list_models_accepts_bare_and_search_forms() {
1285        let bare = parse_args(&s(&["--list-models"]));
1286        assert_eq!(bare.list_models.as_deref(), Some(""));
1287        assert!(bare.ignored.is_empty());
1288        assert!(bare.messages.is_empty());
1289
1290        let search = parse_args(&s(&["--list-models", "claude"]));
1291        assert_eq!(search.list_models.as_deref(), Some("claude"));
1292        assert!(search.messages.is_empty());
1293
1294        let inline = parse_args(&s(&["--list-models=gpt"]));
1295        assert_eq!(inline.list_models.as_deref(), Some("gpt"));
1296    }
1297
1298    #[test]
1299    fn offline_flag_is_honored_without_warning() {
1300        let args = parse_args(&s(&["--offline"]));
1301        assert!(args.offline);
1302        assert!(args.ignored.is_empty());
1303    }
1304
1305    #[test]
1306    fn timeout_parses_seconds_in_separate_and_equals_forms() {
1307        let separate = parse_args(&s(&["--timeout", "45"]));
1308        assert!(separate.errors.is_empty());
1309        assert_eq!(separate.timeout, Some(Duration::from_secs(45)));
1310
1311        let inline = parse_args(&s(&["--timeout=90"]));
1312        assert!(inline.errors.is_empty());
1313        assert_eq!(inline.timeout, Some(Duration::from_secs(90)));
1314    }
1315
1316    #[test]
1317    fn timeout_rejects_zero_and_invalid_values() {
1318        for value in ["0", "1.5", "forever", "18446744073709551616"] {
1319            let args = parse_args(&s(&[&format!("--timeout={value}")]));
1320            assert_eq!(args.errors.len(), 1, "value: {value}");
1321            assert!(args.timeout.is_none(), "value: {value}");
1322        }
1323    }
1324
1325    #[test]
1326    fn stream_idle_timeout_accepts_both_forms_and_zero_but_rejects_invalid_values() {
1327        for (argv, seconds) in [
1328            (s(&["--stream-idle-timeout", "45"]), 45),
1329            (s(&["--stream-idle-timeout=90"]), 90),
1330            (s(&["--stream-idle-timeout=0"]), 0),
1331        ] {
1332            let args = parse_args(&argv);
1333            assert!(args.errors.is_empty(), "{:?}", args.errors);
1334            assert_eq!(args.stream_idle_timeout, Some(Duration::from_secs(seconds)));
1335            assert!(args.timeout.is_none());
1336        }
1337        for value in ["-1", "1.5", "no", "18446744073709551616"] {
1338            let args = parse_args(&s(&[&format!("--stream-idle-timeout={value}")]));
1339            assert!(!args.errors.is_empty(), "{value}");
1340            assert!(args.stream_idle_timeout.is_none());
1341        }
1342        assert!(!parse_args(&s(&["--stream-idle-timeout"])).errors.is_empty());
1343    }
1344
1345    #[test]
1346    fn native_pi_offline_truthy_values_are_case_insensitive() {
1347        for value in [
1348            Some("1"),
1349            Some("true"),
1350            Some("TRUE"),
1351            Some("Yes"),
1352            Some("yEs"),
1353        ] {
1354            assert!(is_truthy_env_flag(value), "value={value:?}");
1355        }
1356        for value in [
1357            None,
1358            Some(""),
1359            Some("0"),
1360            Some("false"),
1361            Some("no"),
1362            Some(" true "),
1363        ] {
1364            assert!(!is_truthy_env_flag(value), "value={value:?}");
1365        }
1366    }
1367
1368    #[test]
1369    fn pi_offline_env_and_cli_flag_share_one_normalized_gate() {
1370        let _guard = crate::config::test_support::env_lock().lock().unwrap();
1371        let _restore = RestoreOfflineEnv(std::env::var_os(RPI_OFFLINE_ENV));
1372
1373        std::env::set_var(RPI_OFFLINE_ENV, "YeS");
1374        assert!(parse_args(&[]).offline);
1375        assert!(normalize_offline_mode(&[]));
1376        assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
1377
1378        std::env::set_var(RPI_OFFLINE_ENV, "0");
1379        assert!(!parse_args(&[]).offline);
1380        let argv = s(&["--offline"]);
1381        assert!(normalize_offline_mode(&argv));
1382        assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
1383    }
1384
1385    #[test]
1386    fn project_trust_flags_are_honored_without_warning() {
1387        let approved = parse_args(&s(&["--approve"]));
1388        assert_eq!(approved.trust_override, Some(true));
1389        assert!(approved.ignored.is_empty());
1390        let denied = parse_args(&s(&["--no-approve"]));
1391        assert_eq!(denied.trust_override, Some(false));
1392        assert!(denied.ignored.is_empty());
1393    }
1394
1395    #[test]
1396    fn export_flag_captures_input_and_output_position() {
1397        let args = parse_args(&s(&["--export", "session.jsonl", "transcript.html"]));
1398        assert_eq!(args.export, Some(PathBuf::from("session.jsonl")));
1399        assert_eq!(args.messages, vec!["transcript.html".to_string()]);
1400        assert!(args.ignored.is_empty());
1401    }
1402
1403    #[test]
1404    fn session_id_and_fork_flags_parse() {
1405        let a = parse_args(&s(&["--session-id", "01abc", "--fork", "xyz"]));
1406        assert!(a.errors.is_empty());
1407        assert_eq!(a.session_id.as_deref(), Some("01abc"));
1408        assert_eq!(a.fork.as_deref(), Some("xyz"));
1409        assert_eq!(a.fork_entry, None);
1410        assert_eq!(
1411            a.fork_position, None,
1412            "an explicit entry must keep the harness default (before), not force a position"
1413        );
1414        let a = parse_args(&s(&[
1415            "--fork",
1416            "xyz",
1417            "--fork-entry",
1418            "message-2",
1419            "--fork-position",
1420            "before",
1421        ]));
1422        assert!(a.errors.is_empty());
1423        assert_eq!(a.fork_entry.as_deref(), Some("message-2"));
1424        assert_eq!(
1425            a.fork_position,
1426            Some(rpi_harness::session::types::ForkPosition::Before)
1427        );
1428        let a = parse_args(&s(&["--fork-position", "middle"]));
1429        assert_eq!(a.fork_position, None);
1430        assert_eq!(
1431            a.errors,
1432            vec!["Invalid --fork-position \"middle\". Expected at or before".to_string()]
1433        );
1434        let a = parse_args(&s(&[
1435            "-e",
1436            "plugin.dll",
1437            "--skill",
1438            "s",
1439            "--prompt-template",
1440            "t.md",
1441        ]));
1442        assert_eq!(a.extension.len(), 1);
1443        assert_eq!(a.skill.len(), 1);
1444        assert_eq!(a.prompt_template.len(), 1);
1445    }
1446
1447    #[test]
1448    fn fork_cut_flags_are_reserved_and_require_an_active_fork() {
1449        let args = parse_args(&s(&[
1450            "--fork-entry=entry-1",
1451            "--fork",
1452            "source",
1453            "--fork-position",
1454            "at",
1455            "--extension-option=keep",
1456        ]));
1457        assert!(args.errors.is_empty(), "{:?}", args.errors);
1458        assert_eq!(
1459            args.unknown_flags,
1460            BTreeMap::from([("extension-option".into(), serde_json::json!("keep"))])
1461        );
1462        for argv in [
1463            &["--fork-entry", "entry-1"][..],
1464            &["--fork", "source", "--fork-position", "at"],
1465            &[
1466                "--fork",
1467                "source",
1468                "--fork-entry",
1469                "entry-1",
1470                "--no-session",
1471            ],
1472            &["--fork", "source", "--fork-entry", "entry-1", "--resume"],
1473            &[
1474                "--fork",
1475                "source",
1476                "--fork-entry",
1477                "entry-1",
1478                "--fork-position=after",
1479            ],
1480            &[
1481                "--fork",
1482                "source",
1483                "--fork-entry=entry-1",
1484                "--fork-entry=entry-2",
1485            ],
1486            &["--fork", "source", "--fork-entry="],
1487        ] {
1488            assert!(!parse_args(&s(argv)).errors.is_empty(), "{argv:?}");
1489        }
1490    }
1491
1492    #[test]
1493    fn fork_position_is_case_insensitive() {
1494        use rpi_harness::session::types::ForkPosition;
1495        for (value, expected) in [
1496            ("at", ForkPosition::At),
1497            ("At", ForkPosition::At),
1498            ("AT", ForkPosition::At),
1499            ("before", ForkPosition::Before),
1500            ("Before", ForkPosition::Before),
1501            ("BEFORE", ForkPosition::Before),
1502        ] {
1503            let a = parse_args(&s(&[
1504                "--fork",
1505                "xyz",
1506                "--fork-entry",
1507                "message-2",
1508                "--fork-position",
1509                value,
1510            ]));
1511            assert!(a.errors.is_empty(), "{value}: {:?}", a.errors);
1512            assert_eq!(a.fork_position, Some(expected), "{value}");
1513        }
1514    }
1515
1516    /// `--fork-entry` is only read inside `SessionSelection::Fork`, and
1517    /// `--fork-position` only makes sense alongside an explicit entry: without
1518    /// one it reaches the harness as `entry_id: None, position: Some(Before)`
1519    /// and truncates the current leaf from the child.
1520    #[test]
1521    fn fork_cut_flags_require_fork() {
1522        let a = parse_args(&s(&["--fork-entry", "message-2", "--print", "hi"]));
1523        assert_eq!(a.errors, vec!["--fork-entry requires --fork".to_string()]);
1524
1525        // `--fork-position` alone is missing both prerequisites; the existing
1526        // rule stays, and the new entry rule is reported alongside it.
1527        let a = parse_args(&s(&["--fork-position", "before"]));
1528        assert_eq!(
1529            a.errors,
1530            vec![
1531                "--fork-position requires --fork".to_string(),
1532                "--fork-position requires --fork-entry".to_string(),
1533            ]
1534        );
1535
1536        // Both flags together report once each, in flag order.
1537        let a = parse_args(&s(&["--fork-position=at", "--fork-entry=message-2"]));
1538        assert_eq!(
1539            a.errors,
1540            vec![
1541                "--fork-entry requires --fork".to_string(),
1542                "--fork-position requires --fork".to_string(),
1543            ]
1544        );
1545
1546        // With `--fork` they parse cleanly.
1547        let a = parse_args(&s(&[
1548            "--fork",
1549            "xyz",
1550            "--fork-entry",
1551            "message-2",
1552            "--fork-position",
1553            "at",
1554        ]));
1555        assert!(a.errors.is_empty(), "{:?}", a.errors);
1556    }
1557
1558    /// The reviewer's P2: `--fork-position` without `--fork-entry` is not
1559    /// inert — the harness takes the current leaf as the implicit target and
1560    /// then applies `Before`, dropping it from the child. Cover both position
1561    /// values, both argv spellings, and the no-`--fork` combination.
1562    #[test]
1563    fn fork_position_requires_fork_entry() {
1564        for value in ["at", "before", "AT", "BEFORE"] {
1565            // Separate-value form.
1566            let a = parse_args(&s(&["--fork", "xyz", "--fork-position", value]));
1567            assert_eq!(
1568                a.errors,
1569                vec!["--fork-position requires --fork-entry".to_string()],
1570                "{value}: the flag is not inert"
1571            );
1572            assert!(a.fork_position.is_some(), "{value}");
1573
1574            // Inline `--flag=value` form.
1575            let flag = format!("--fork-position={value}");
1576            let a = parse_args(&s(&["--fork", "xyz", &flag]));
1577            assert_eq!(
1578                a.errors,
1579                vec!["--fork-position requires --fork-entry".to_string()],
1580                "{flag}: the flag is not inert"
1581            );
1582        }
1583
1584        // With --fork-entry present, both forms are accepted.
1585        let a = parse_args(&s(&[
1586            "--fork",
1587            "xyz",
1588            "--fork-entry",
1589            "message-2",
1590            "--fork-position=before",
1591        ]));
1592        assert!(a.errors.is_empty(), "{:?}", a.errors);
1593        assert_eq!(
1594            a.fork_position,
1595            Some(rpi_harness::session::types::ForkPosition::Before)
1596        );
1597    }
1598
1599    #[test]
1600    fn no_skills_flag_honored() {
1601        let a = parse_args(&s(&["-ns"]));
1602        assert!(a.errors.is_empty());
1603        assert!(a.no_skills);
1604        // Honored flags do NOT also warn-ignore themselves.
1605        assert!(a.ignored.is_empty());
1606    }
1607
1608    #[test]
1609    fn no_prompt_templates_flag_honored() {
1610        let a = parse_args(&s(&["--no-prompt-templates"]));
1611        assert!(a.no_prompt_templates);
1612        assert!(a.ignored.is_empty());
1613    }
1614
1615    #[test]
1616    fn no_context_files_flag_honored() {
1617        let a = parse_args(&s(&["-nc"]));
1618        assert!(a.no_context_files);
1619        assert!(a.ignored.is_empty());
1620    }
1621
1622    #[test]
1623    fn no_extensions_flag_honored() {
1624        // `--no-extensions` is parsed and disables both extension backends.
1625        let a = parse_args(&s(&["--no-extensions"]));
1626        assert!(a.no_extensions);
1627        assert!(a.ignored.is_empty());
1628    }
1629
1630    #[test]
1631    fn local_only_flag_is_honored_on_the_regular_parser() {
1632        // The plain `rpi --local-only` form sets the same scope `rpi dev
1633        // --local-only` uses, without the build/watch layer.
1634        let a = parse_args(&s(&["--local-only"]));
1635        assert!(a.errors.is_empty());
1636        assert!(a.dev_local_only);
1637        assert!(a.ignored.is_empty());
1638    }
1639
1640    #[test]
1641    fn project_only_aliases_are_honored() {
1642        for flag in ["--package-only", "--project-only"] {
1643            let a = parse_args(&s(&[flag]));
1644            assert!(a.errors.is_empty());
1645            assert!(a.project_only);
1646            assert!(a.ignored.is_empty());
1647        }
1648    }
1649
1650    #[test]
1651    fn extensions_dir_flag_collects_dirs() {
1652        let a = parse_args(&s(&["--extensions-dir", "/a/b", "-ed", "/c/d"]));
1653        assert_eq!(
1654            a.extensions_dir,
1655            vec![PathBuf::from("/a/b"), PathBuf::from("/c/d")]
1656        );
1657        assert!(a.ignored.is_empty());
1658    }
1659
1660    #[test]
1661    fn extensions_dir_inline_equals_form() {
1662        let a = parse_args(&s(&["--extensions-dir=/x/y"]));
1663        assert_eq!(a.extensions_dir, vec![PathBuf::from("/x/y")]);
1664    }
1665
1666    #[test]
1667    fn extensions_dir_env_is_merged() {
1668        // The env var contributes its split list. We can't fully control env in
1669        // a unit test without `set_var` (process-global + racy under parallel
1670        // tests), so this asserts the flag path only; the env path is exercised
1671        // by the B2 smoke. Keep the test green regardless of the host env by
1672        // NOT asserting emptiness — just confirm the flag appends after env.
1673        let a = parse_args(&s(&["--extensions-dir", "/flag/only"]));
1674        assert!(a
1675            .extensions_dir
1676            .iter()
1677            .any(|p| p == &PathBuf::from("/flag/only")));
1678    }
1679
1680    #[test]
1681    fn file_args_stripped() {
1682        let a = parse_args(&s(&["@a.txt", "@b.md", "hi"]));
1683        assert_eq!(
1684            a.file_args,
1685            vec![PathBuf::from("a.txt"), PathBuf::from("b.md")]
1686        );
1687        assert_eq!(a.messages, vec!["hi".to_string()]);
1688    }
1689
1690    #[test]
1691    fn equals_form_supported() {
1692        let a = parse_args(&s(&["--model=claude-sonnet-5", "--thinking=low"]));
1693        assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1694        assert_eq!(a.thinking, Some(ThinkingLevel::Low));
1695    }
1696
1697    #[test]
1698    fn theme_flag_is_honored() {
1699        let a = parse_args(&s(&["--theme", "ocean.json"]));
1700        assert_eq!(a.theme.as_deref(), Some("ocean.json"));
1701        assert!(a.ignored.is_empty());
1702    }
1703
1704    #[test]
1705    fn no_themes_is_honored() {
1706        let a = parse_args(&s(&["--no-themes"]));
1707        assert!(a.no_themes);
1708        assert!(a.ignored.is_empty());
1709    }
1710
1711    #[test]
1712    fn tui_mode_parses_and_validates() {
1713        assert_eq!(
1714            parse_args(&s(&["--tui-mode", "regular"])).tui_mode,
1715            TuiMode::Regular
1716        );
1717        assert_eq!(
1718            parse_args(&s(&["--tui-mode=fullscreen"])).tui_mode,
1719            TuiMode::Fullscreen
1720        );
1721        let invalid = parse_args(&s(&["--tui-mode", "split"]));
1722        assert!(!invalid.errors.is_empty());
1723    }
1724
1725    #[test]
1726    fn host_accepts_terminal_presentation_flags() {
1727        let args = parse_args(&s(&[
1728            "--host",
1729            "work",
1730            "--tui-mode",
1731            "regular",
1732            "--theme=light",
1733        ]));
1734        assert!(args.errors.is_empty(), "{:?}", args.errors);
1735        assert_eq!(args.host.as_deref(), Some("work"));
1736        assert_eq!(args.tui_mode, TuiMode::Regular);
1737        assert_eq!(args.theme.as_deref(), Some("light"));
1738
1739        let args = parse_args(&s(&["--no-themes", "--tui-mode=fullscreen", "--host=work"]));
1740        assert!(args.errors.is_empty(), "{:?}", args.errors);
1741        assert_eq!(args.tui_mode, TuiMode::Fullscreen);
1742        assert!(args.no_themes);
1743        assert!(!parse_args(&s(&["--host", "--provider", "fixture"]))
1744            .errors
1745            .is_empty());
1746    }
1747
1748    #[test]
1749    fn tui_mode_default_preserves_native_macos_scrollback() {
1750        assert_eq!(default_tui_mode_for(true), TuiMode::Regular);
1751        assert_eq!(default_tui_mode_for(false), TuiMode::Fullscreen);
1752    }
1753
1754    #[test]
1755    fn resolve_mode_interactive_when_tty() {
1756        let a = Args {
1757            print: true,
1758            ..Args::default()
1759        };
1760        assert_eq!(resolve_mode(&a, true, true), RunMode::Print);
1761        let a = Args::default();
1762        assert_eq!(resolve_mode(&a, true, true), RunMode::Interactive);
1763        let a = Args {
1764            mode: Mode::Json,
1765            ..Args::default()
1766        };
1767        assert_eq!(resolve_mode(&a, true, true), RunMode::Json);
1768        let a = Args {
1769            mode: Mode::Rpc,
1770            ..Args::default()
1771        };
1772        assert_eq!(resolve_mode(&a, true, true), RunMode::Rpc);
1773    }
1774
1775    #[test]
1776    fn piped_stdout_forces_print() {
1777        let a = Args::default();
1778        // stdout not a TTY ⇒ print even without -p (mirrors TS).
1779        assert_eq!(resolve_mode(&a, true, false), RunMode::Print);
1780    }
1781}