Skip to main content

rpi_cli/
args.rs

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