1use std::collections::BTreeMap;
26use std::path::PathBuf;
27use std::time::Duration;
28
29use rpi_ai::ThinkingLevel;
30
31pub(crate) const RPI_OFFLINE_ENV: &str = "RPI_OFFLINE";
35
36pub(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
53pub(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
64pub(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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
75pub enum Mode {
76 #[default]
77 Text,
78 Json,
79 Rpc,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum TuiMode {
86 Fullscreen,
87 Regular,
88}
89
90const fn default_tui_mode_for(is_macos: bool) -> TuiMode {
91 if is_macos {
92 TuiMode::Regular
93 } else {
94 TuiMode::Fullscreen
95 }
96}
97
98impl Default for TuiMode {
99 fn default() -> Self {
100 default_tui_mode_for(cfg!(target_os = "macos"))
101 }
102}
103
104#[derive(Debug, Clone, Default)]
107pub struct Args {
108 pub provider: Option<String>,
109 pub model: Option<String>,
110 pub api_key: Option<String>,
111 pub base_url: Option<String>,
114 pub timeout: Option<Duration>,
116 pub stream_idle_timeout: Option<Duration>,
118 pub system_prompt: Option<String>,
119 pub append_system_prompt: Vec<String>,
120 pub theme: Option<String>,
122 pub thinking: Option<ThinkingLevel>,
123
124 pub print: bool,
125 pub mode: Mode,
126 pub tui_mode: TuiMode,
130
131 pub list_models: Option<String>,
134 pub offline: bool,
136 pub export: Option<PathBuf>,
139 pub trust_override: Option<bool>,
142
143 pub continue_session: bool,
144 pub resume: bool,
145 pub session: Option<String>,
146 pub session_id: Option<String>,
150 pub fork: Option<String>,
153 pub models: Option<Vec<String>>,
157 pub session_dir: Option<PathBuf>,
158 pub no_session: bool,
159 pub name: Option<String>,
160
161 pub tools: Option<Vec<String>>,
162 pub exclude_tools: Option<Vec<String>>,
163 pub no_tools: bool,
164 pub no_builtin_tools: bool,
165
166 pub no_skills: bool,
169 pub no_prompt_templates: bool,
172 pub no_context_files: bool,
175 pub no_extensions: bool,
178 pub no_themes: bool,
181 pub extensions_dir: Vec<PathBuf>,
189 pub extension: Vec<PathBuf>,
192 pub skill: Vec<PathBuf>,
194 pub prompt_template: Vec<PathBuf>,
197
198 pub dev_local_only: bool,
200 pub project_only: bool,
203
204 pub verbose: bool,
205 pub help: bool,
206 pub version: bool,
207
208 pub debug_system_prompt: bool,
215
216 pub messages: Vec<String>,
218 pub file_args: Vec<PathBuf>,
221
222 pub unknown_flags: BTreeMap<String, serde_json::Value>,
226 pub ignored: Vec<String>,
229 pub errors: Vec<String>,
232}
233
234pub use rpi_runtime::thinking::VALID_THINKING_LEVELS;
237
238pub use rpi_runtime::thinking::parse_thinking_level;
240
241fn file_arg(arg: &str) -> Option<PathBuf> {
244 if let Some(rest) = arg.strip_prefix('@') {
245 if rest.is_empty() {
247 None
248 } else {
249 Some(PathBuf::from(rest))
250 }
251 } else {
252 None
253 }
254}
255
256pub fn parse_args(args: &[String]) -> Args {
262 let mut result = Args::default();
263 result.offline = offline_env_enabled();
264 if let Ok(raw) = std::env::var("RPI_EXTENSIONS_DIR") {
268 if !raw.is_empty() {
269 let sep = if cfg!(windows) { ';' } else { ':' };
270 for part in raw.split(sep) {
271 let trimmed = part.trim();
272 if !trimmed.is_empty() {
273 result.extensions_dir.push(PathBuf::from(trimmed));
274 }
275 }
276 }
277 }
278 let mut i = 0;
279 while i < args.len() {
280 let arg = args[i].clone();
281 let (flag_key, inline) = if arg.starts_with("--") {
285 match arg.find('=') {
286 Some(eq) => (arg[..eq].to_string(), Some(arg[eq + 1..].to_string())),
287 None => (arg.clone(), None),
288 }
289 } else {
290 (arg.clone(), None)
291 };
292
293 let mut take_value = |result: &mut Args, _flag: &str| -> Option<String> {
297 if let Some(v) = inline.clone() {
298 return Some(v);
299 }
300 if i + 1 < args.len() {
301 let next = &args[i + 1];
302 if !next.starts_with('-') || next == "-" {
303 i += 1;
304 return Some(args[i].clone());
305 }
306 }
307 result.errors.push(format!("{flag_key} requires a value"));
308 None
309 };
310
311 match flag_key.as_str() {
312 "--help" | "-h" => result.help = true,
313 "--version" | "-v" => result.version = true,
314 "--print" | "-p" => {
315 result.print = true;
316 if i + 1 < args.len() {
321 let next = &args[i + 1];
322 if !next.starts_with('@') && !next.starts_with('-') {
323 i += 1;
324 result.messages.push(args[i].clone());
325 }
326 }
327 }
328 "--mode" => {
329 if let Some(v) = take_value(&mut result, "--mode") {
330 result.mode = match v.as_str() {
331 "text" => Mode::Text,
332 "json" => Mode::Json,
333 "rpc" => Mode::Rpc,
334 other => {
335 result.errors.push(format!(
336 "Invalid --mode \"{other}\". Valid: text, json, rpc"
337 ));
338 Mode::Text
339 }
340 };
341 }
342 }
343 "--tui-mode" => {
344 if let Some(v) = take_value(&mut result, "--tui-mode") {
345 result.tui_mode = match v.to_ascii_lowercase().as_str() {
346 "regular" => TuiMode::Regular,
347 "fullscreen" => TuiMode::Fullscreen,
348 other => {
349 result.errors.push(format!(
350 "Invalid --tui-mode \"{other}\". Valid: regular, fullscreen"
351 ));
352 TuiMode::Fullscreen
353 }
354 };
355 }
356 }
357 "--continue" | "-c" => result.continue_session = true,
358 "--resume" | "-r" => result.resume = true,
359 "--no-session" => result.no_session = true,
360 "--no-tools" | "-nt" => result.no_tools = true,
361 "--no-builtin-tools" | "-nbt" => result.no_builtin_tools = true,
362 "--no-skills" | "-ns" => result.no_skills = true,
363 "--no-prompt-templates" | "-np" => result.no_prompt_templates = true,
364 "--no-context-files" | "-nc" => result.no_context_files = true,
365 "--no-extensions" | "-ne" => result.no_extensions = true,
366 "--local-only" => result.dev_local_only = true,
367 "--package-only" | "--project-only" => result.project_only = true,
368 "--extensions-dir" | "-ed" => {
369 if let Some(v) = take_value(&mut result, &flag_key) {
370 result.extensions_dir.push(PathBuf::from(v));
371 }
372 }
373 "--verbose" => result.verbose = true,
374 "--debug-system-prompt" => result.debug_system_prompt = true,
375 "--provider" => result.provider = take_value(&mut result, "--provider"),
376 "--model" => result.model = take_value(&mut result, "--model"),
377 "--api-key" => result.api_key = take_value(&mut result, "--api-key"),
378 "--base-url" => result.base_url = take_value(&mut result, "--base-url"),
379 "--timeout" => {
380 if let Some(v) = take_value(&mut result, "--timeout") {
381 match v.parse::<u64>() {
382 Ok(seconds) if seconds > 0 => {
383 result.timeout = Some(Duration::from_secs(seconds));
384 }
385 _ => result.errors.push(format!(
386 "Invalid --timeout \"{v}\". Expected a positive integer number of seconds"
387 )),
388 }
389 }
390 }
391 "--stream-idle-timeout" => {
392 if let Some(v) = take_value(&mut result, "--stream-idle-timeout") {
393 match v.parse::<u64>() {
394 Ok(seconds) => result.stream_idle_timeout = Some(Duration::from_secs(seconds)),
395 Err(_) => result.errors.push(format!(
396 "Invalid --stream-idle-timeout \"{v}\". Expected a non-negative integer number of seconds (0 disables it)"
397 )),
398 }
399 }
400 }
401 "--system-prompt" => result.system_prompt = take_value(&mut result, "--system-prompt"),
402 "--append-system-prompt" => {
403 if let Some(v) = take_value(&mut result, "--append-system-prompt") {
404 result.append_system_prompt.push(v);
405 }
406 }
407 "--name" | "-n" => result.name = take_value(&mut result, "--name"),
408 "--session" => result.session = take_value(&mut result, "--session"),
409 "--session-id" => result.session_id = take_value(&mut result, "--session-id"),
410 "--fork" => result.fork = take_value(&mut result, "--fork"),
411 "--models" => {
412 if let Some(v) = take_value(&mut result, &flag_key) {
413 result.models = Some(split_csv(&v));
414 }
415 }
416 "--extension" | "-e" => {
417 if let Some(v) = take_value(&mut result, &flag_key) {
418 result.extension.push(PathBuf::from(v));
419 }
420 }
421 "--skill" => {
422 if let Some(v) = take_value(&mut result, &flag_key) {
423 result.skill.push(PathBuf::from(v));
424 }
425 }
426 "--prompt-template" => {
427 if let Some(v) = take_value(&mut result, &flag_key) {
428 result.prompt_template.push(PathBuf::from(v));
429 }
430 }
431 "--session-dir" => {
432 if let Some(v) = take_value(&mut result, "--session-dir") {
433 result.session_dir = Some(PathBuf::from(v));
434 }
435 }
436 "--thinking" => {
437 if let Some(v) = take_value(&mut result, "--thinking") {
438 match parse_thinking_level(&v) {
439 Some(lvl) => result.thinking = Some(lvl),
440 None => result.ignored.push(format!(
441 "Invalid --thinking \"{v}\". Valid: {}",
442 VALID_THINKING_LEVELS.join(", ")
443 )),
444 }
445 }
446 }
447 "--tools" | "-t" => {
448 if let Some(v) = take_value(&mut result, &flag_key) {
449 result.tools = Some(split_csv(&v));
450 }
451 }
452 "--exclude-tools" | "-xt" => {
453 if let Some(v) = take_value(&mut result, &flag_key) {
454 result.exclude_tools = Some(split_csv(&v));
455 }
456 }
457 "--list-models" => {
458 let mut search = inline.clone().unwrap_or_default();
461 if inline.is_none()
462 && i + 1 < args.len()
463 && !args[i + 1].starts_with('-')
464 && !args[i + 1].starts_with('@')
465 {
466 i += 1;
467 search = args[i].clone();
468 }
469 result.list_models = Some(search);
470 }
471 "--offline" => result.offline = true,
472 "--export" => {
473 if let Some(value) = take_value(&mut result, &flag_key) {
474 result.export = Some(PathBuf::from(value));
475 }
476 }
477 "--approve" | "-a" => result.trust_override = Some(true),
478 "--no-approve" | "-na" => result.trust_override = Some(false),
479 other if matches!(other, "--models") => {
490 if inline.is_none()
493 && i + 1 < args.len()
494 && !args[i + 1].starts_with('-')
495 && !args[i + 1].starts_with('@')
496 {
497 i += 1;
498 }
499 result
500 .ignored
501 .push(format!("{other} is not supported in v1 (ignored)"));
502 }
503 "--theme" => {
504 result.theme = take_value(&mut result, "--theme");
505 }
506 "--no-themes" => result.no_themes = true,
507 other if other.starts_with("--") => {
512 let name = &flag_key;
513 let value = if let Some(value) = inline {
514 serde_json::Value::String(value)
515 } else if i + 1 < args.len()
516 && !args[i + 1].starts_with('-')
517 && !args[i + 1].starts_with('@')
518 {
519 i += 1;
520 serde_json::Value::String(args[i].clone())
521 } else {
522 serde_json::Value::Bool(true)
523 };
524 result.unknown_flags.insert(name[2..].to_string(), value);
525 }
526 other if other.starts_with('-') && other.len() > 1 => {
528 result.errors.push(format!("Unknown option: {other}"));
529 }
530 other => {
531 if let Some(path) = file_arg(other) {
532 result.file_args.push(path);
533 } else {
534 result.messages.push(other.to_string());
535 }
536 }
537 }
538 i += 1;
539 }
540
541 result
545}
546
547fn split_csv(v: &str) -> Vec<String> {
549 v.split(',')
550 .map(|s| s.trim().to_string())
551 .filter(|s| !s.is_empty())
552 .collect()
553}
554
555pub fn resolve_mode(parsed: &Args, stdin_is_tty: bool, stdout_is_tty: bool) -> RunMode {
560 if parsed.unknown_flags.contains_key("server") {
562 return RunMode::Rpc;
563 }
564 if parsed.mode == Mode::Rpc {
565 return RunMode::Rpc;
566 }
567 if parsed.mode == Mode::Json {
568 return RunMode::Json;
569 }
570 if parsed.print || !stdin_is_tty || !stdout_is_tty {
571 RunMode::Print
572 } else {
573 RunMode::Interactive
574 }
575}
576
577#[derive(Debug, Clone, Copy, PartialEq, Eq)]
582pub enum RunMode {
583 Interactive,
584 Print,
585 Json,
586 Rpc,
587}
588
589pub fn print_help() {
591 let builtin = "read, bash, edit, write, docs";
592 println!(
593 "{name} - AI coding assistant with read, bash, edit, write, docs tools
594
595{u}Usage:{r}
596 {name} [options] [@files...] [messages...]
597
598{u}Options:{r}
599 --provider <name> Provider name (built-in, installed package, or models.json id)
600 --model <pattern> Model pattern or ID (supports \"provider/id\" and optional \":<thinking>\")
601 --api-key <key> API key override for the selected provider
602 --base-url <url> Override the selected model endpoint
603 --timeout <seconds> LLM API request timeout (default: 600)
604 --stream-idle-timeout <seconds> Max silence between response bytes (default: 300; 0 disables)
605 --system-prompt <text> Replace the default system prompt
606 --append-system-prompt <text> Append text to the system prompt (repeatable)
607 --thinking <level> off, minimal, low, medium, high, xhigh, max
608 --mode <mode> Output mode: text (default), json, or rpc
609 --server [--port <n>] [--bind <ip>]
610 Headless server: serve a remote-connectable agent (no TUI)
611 --connect <host:port> Remote client: connect to a `--server` instance and run the TUI
612 (no local provider/tools/session; all agent work is remote)
613 --token <token> Auth token for `--connect` (printed by `--server`; may also
614 be provided via the RPI_SERVER_TOKEN env var)
615 --tui-mode <mode> TUI buffer: regular or fullscreen (macOS default: regular)
616 --list-models [search] List available models (with optional fuzzy search)
617 --offline Disable startup network operations (same as RPI_OFFLINE=1)
618 --export <file> Export a JSONL session to HTML and exit
619 --approve, -a Force-enable current-project resources
620 --no-approve, -na Disable current-project resources
621 --print, -p Non-interactive: process prompt(s) and exit
622 --continue, -c Continue the most recent session
623 --resume, -r Browse and select a session to resume
624 --session <id|path> Use a specific session (partial UUID or file)
625 --session-dir <dir> Directory for session storage
626 --no-session Ephemeral mode (do not persist the session)
627 --name, -n <name> Set the session display name
628 --tools, -t <list> Comma-separated allowlist of tool names to enable
629 --exclude-tools, -xt <list> Comma-separated denylist of tool names to disable
630 --no-tools, -nt Disable all tools
631 --no-builtin-tools, -nbt Disable the built-in tools (read, bash, edit, write, docs)
632 --no-skills, -ns Skip skill discovery (no <available_skills> block)
633 --no-prompt-templates, -np Skip prompt-template discovery (/expand templates)
634 --no-context-files, -nc Skip AGENTS.md/CLAUDE.md discovery (no <project_context>)
635 --no-extensions, -ne Skip Rust cdylib extension loading
636 --extensions-dir, -ed <dir> Extra dir to scan for plugins (.dll/.so/.dylib); repeatable
637 (also via RPI_EXTENSIONS_DIR env: ';' on Windows, ':' on Unix)
638 --local-only Skip automatic extension discovery: load only
639 --extensions-dir / --extension paths (no project
640 .rpi/extensions, no global extensions)
641 --package-only, --project-only Load project skills/prompts/extensions/packages
642 from the active project; exclude global resources
643 --debug-system-prompt Print the resolved system-prompt sections to stderr (verification)
644 --verbose Show startup warnings (e.g. ignored flags)
645 --help, -h Show this help
646 --version, -v Show version
647
648{u}Subcommands:{r}
649 update Update the rpi CLI from crates.io
650 auth login|check|logout Manage persisted credentials in ~/.rpi/auth.json
651 (see `rpi auth --help`)
652 events path|tail Inspect the extension event journal (needs
653 RPI_EVENT_LOG=1; see `rpi events --help`)
654 install <crate> Install a prebuilt Rust extension (--build for source)
655 (see `rpi install --help`)
656 uninstall <crate> Remove an installed Rust cdylib extension
657 package link|list|update|unlink Manage project-local Rust extension packages
658 (see `rpi package --help`)
659 dev [options] Build, watch, and hot-reload a Rust extension
660 (see `rpi dev --help`)
661 dev-local [options] Debug only the current Rust extension
662 (shortcut for `rpi dev --local-only`)
663
664{u}Built-in Tools:{r}
665 {builtin} (enabled by default)
666
667{u}Examples:{r}
668 # Interactive with an initial prompt
669 {name} \"List all .rs files in src/\"
670
671 # Single-shot print mode
672 {name} -p \"Summarize this project\"
673
674 # Include a file in the initial message
675 {name} @README.md \"What does this project do?\"
676
677 # Continue the previous session
678 {name} -c \"What did we discuss?\"
679
680 # Use a specific model + thinking level
681 {name} --model claude-sonnet-5 --thinking high \"Refactor this\"
682
683 # JSON event stream (one JSON object per line on stdout)
684 {name} --mode json -p \"Inspect the code\"
685
686 # Read-only: no file-modifying tools
687 {name} --tools read,bash -p \"Review the code in src/\"
688
689{u}Environment:{r}
690 ANTHROPIC_API_KEY Anthropic API key (x-api-key) — fallback when no stored credential
691 ANTHROPIC_AUTH_TOKEN Bearer token (Authorization: Bearer) for third-party gateways
692 ANTHROPIC_BASE_URL Override the Anthropic endpoint (e.g. a compatible proxy)
693 OPENAI_API_KEY Bearer token for openai-completions/responses
694 RPI_OFFLINE Disable startup network operations when set to 1/true/yes
695 RPI_CODING_AGENT_DIR Override the ~/.rpi config directory (auth.json + models.json)
696 RPI_SESSION_ID Session id served by a plugin (set by the host; also honored as an override)
697 RPI_NO_EMOJI Render the brand lockup without the crab (1/true/yes)
698
699{u}Notes:{r}
700 Supported HTTP protocols are Anthropic Messages and OpenAI Chat Completions.
701 Define custom model catalogs and provider apiKey values in
702 ~/.rpi/agent/models.json. The interactive TUI, Rust extensions, skills,
703 prompt templates, themes, model cycling, session fork/export, and trust
704 commands are available in the current build. OAuth, RPC, and full model
705 cycling remain outside the current implementation.
706",
707 name = crate::APP_NAME,
708 builtin = builtin,
709 u = "\x1b[1m",
710 r = "\x1b[0m",
711 );
712}
713
714pub fn print_version() {
716 println!("{} {}", crate::APP_NAME, crate::VERSION);
717}
718
719#[cfg(test)]
720mod tests {
721 use super::*;
722
723 struct RestoreOfflineEnv(Option<std::ffi::OsString>);
724
725 impl Drop for RestoreOfflineEnv {
726 fn drop(&mut self) {
727 match self.0.take() {
728 Some(value) => std::env::set_var(RPI_OFFLINE_ENV, value),
729 None => std::env::remove_var(RPI_OFFLINE_ENV),
730 }
731 }
732 }
733
734 fn s(args: &[&str]) -> Vec<String> {
735 args.iter().map(|a| a.to_string()).collect()
736 }
737
738 #[test]
739 fn parses_basic_prompt() {
740 let a = parse_args(&s(&["hello", "world"]));
741 assert_eq!(a.messages, vec!["hello".to_string(), "world".to_string()]);
742 assert!(!a.help);
743 }
744
745 #[test]
746 fn parses_help_and_version() {
747 let a = parse_args(&s(&["--help"]));
748 assert!(a.help);
749 let a = parse_args(&s(&["-v"]));
750 assert!(a.version);
751 }
752
753 #[test]
754 fn print_consumes_following_positional() {
755 let a = parse_args(&s(&["-p", "summarize"]));
756 assert!(a.print);
757 assert_eq!(a.messages, vec!["summarize".to_string()]);
758 }
759
760 #[test]
761 fn print_does_not_consume_file_or_flag() {
762 let a = parse_args(&s(&["-p", "@file.md"]));
763 assert!(a.print);
764 assert!(a.messages.is_empty());
765 assert_eq!(a.file_args, vec![PathBuf::from("file.md")]);
766 }
767
768 #[test]
769 fn model_and_thinking() {
770 let a = parse_args(&s(&["--model", "claude-sonnet-5", "--thinking", "high"]));
771 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
772 assert_eq!(a.thinking, Some(ThinkingLevel::High));
773 }
774
775 #[test]
776 fn model_with_thinking_shorthand() {
777 let a = parse_args(&s(&["--model", "claude-sonnet-5:high"]));
778 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5:high"));
780 }
781
782 #[test]
783 fn tools_split_csv() {
784 let a = parse_args(&s(&["--tools", "read, bash ,write"]));
785 assert_eq!(
786 a.tools.as_deref(),
787 Some(&["read".to_string(), "bash".to_string(), "write".to_string()][..])
788 );
789 }
790
791 #[test]
792 fn unknown_short_flag_errors() {
793 let a = parse_args(&s(&["-Z"]));
794 assert!(!a.errors.is_empty());
795 }
796
797 #[test]
798 fn unknown_long_flag_is_retained_for_extensions() {
799 let a = parse_args(&s(&["--frobnicate", "value"]));
800 assert!(a.errors.is_empty());
801 assert_eq!(
802 a.unknown_flags.get("frobnicate"),
803 Some(&serde_json::Value::String("value".into()))
804 );
805 assert!(a.ignored.is_empty());
806 }
807
808 #[test]
809 fn unknown_long_boolean_flag_is_retained() {
810 let a = parse_args(&s(&["--server"]));
811 assert_eq!(
812 a.unknown_flags.get("server"),
813 Some(&serde_json::Value::Bool(true))
814 );
815 }
816
817 #[test]
818 fn unknown_long_flags_keep_string_and_equals_values() {
819 let a = parse_args(&s(&["--port", "8080", "--bind=127.0.0.1"]));
820 assert_eq!(
821 a.unknown_flags.get("port"),
822 Some(&serde_json::Value::String("8080".into()))
823 );
824 assert_eq!(
825 a.unknown_flags.get("bind"),
826 Some(&serde_json::Value::String("127.0.0.1".into()))
827 );
828 }
829
830 #[test]
831 fn models_flag_parses_csv() {
832 let a = parse_args(&s(&["--models", "a,b,c"]));
833 assert!(a.errors.is_empty());
834 assert!(a.ignored.is_empty(), "--models is implemented");
835 assert_eq!(
836 a.models.as_deref(),
837 Some(&["a".to_string(), "b".to_string(), "c".to_string()][..])
838 );
839 assert!(a.messages.is_empty());
841 }
842
843 #[test]
844 fn list_models_accepts_bare_and_search_forms() {
845 let bare = parse_args(&s(&["--list-models"]));
846 assert_eq!(bare.list_models.as_deref(), Some(""));
847 assert!(bare.ignored.is_empty());
848 assert!(bare.messages.is_empty());
849
850 let search = parse_args(&s(&["--list-models", "claude"]));
851 assert_eq!(search.list_models.as_deref(), Some("claude"));
852 assert!(search.messages.is_empty());
853
854 let inline = parse_args(&s(&["--list-models=gpt"]));
855 assert_eq!(inline.list_models.as_deref(), Some("gpt"));
856 }
857
858 #[test]
859 fn offline_flag_is_honored_without_warning() {
860 let args = parse_args(&s(&["--offline"]));
861 assert!(args.offline);
862 assert!(args.ignored.is_empty());
863 }
864
865 #[test]
866 fn timeout_parses_seconds_in_separate_and_equals_forms() {
867 let separate = parse_args(&s(&["--timeout", "45"]));
868 assert!(separate.errors.is_empty());
869 assert_eq!(separate.timeout, Some(Duration::from_secs(45)));
870
871 let inline = parse_args(&s(&["--timeout=90"]));
872 assert!(inline.errors.is_empty());
873 assert_eq!(inline.timeout, Some(Duration::from_secs(90)));
874 }
875
876 #[test]
877 fn timeout_rejects_zero_and_invalid_values() {
878 for value in ["0", "1.5", "forever", "18446744073709551616"] {
879 let args = parse_args(&s(&[&format!("--timeout={value}")]));
880 assert_eq!(args.errors.len(), 1, "value: {value}");
881 assert!(args.timeout.is_none(), "value: {value}");
882 }
883 }
884
885 #[test]
886 fn stream_idle_timeout_accepts_both_forms_and_zero_but_rejects_invalid_values() {
887 for (argv, seconds) in [
888 (s(&["--stream-idle-timeout", "45"]), 45),
889 (s(&["--stream-idle-timeout=90"]), 90),
890 (s(&["--stream-idle-timeout=0"]), 0),
891 ] {
892 let args = parse_args(&argv);
893 assert!(args.errors.is_empty(), "{:?}", args.errors);
894 assert_eq!(args.stream_idle_timeout, Some(Duration::from_secs(seconds)));
895 assert!(args.timeout.is_none());
896 }
897 for value in ["-1", "1.5", "no", "18446744073709551616"] {
898 let args = parse_args(&s(&[&format!("--stream-idle-timeout={value}")]));
899 assert!(!args.errors.is_empty(), "{value}");
900 assert!(args.stream_idle_timeout.is_none());
901 }
902 assert!(!parse_args(&s(&["--stream-idle-timeout"])).errors.is_empty());
903 }
904
905 #[test]
906 fn native_pi_offline_truthy_values_are_case_insensitive() {
907 for value in [
908 Some("1"),
909 Some("true"),
910 Some("TRUE"),
911 Some("Yes"),
912 Some("yEs"),
913 ] {
914 assert!(is_truthy_env_flag(value), "value={value:?}");
915 }
916 for value in [
917 None,
918 Some(""),
919 Some("0"),
920 Some("false"),
921 Some("no"),
922 Some(" true "),
923 ] {
924 assert!(!is_truthy_env_flag(value), "value={value:?}");
925 }
926 }
927
928 #[test]
929 fn pi_offline_env_and_cli_flag_share_one_normalized_gate() {
930 let _guard = crate::config::test_support::env_lock().lock().unwrap();
931 let _restore = RestoreOfflineEnv(std::env::var_os(RPI_OFFLINE_ENV));
932
933 std::env::set_var(RPI_OFFLINE_ENV, "YeS");
934 assert!(parse_args(&[]).offline);
935 assert!(normalize_offline_mode(&[]));
936 assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
937
938 std::env::set_var(RPI_OFFLINE_ENV, "0");
939 assert!(!parse_args(&[]).offline);
940 let argv = s(&["--offline"]);
941 assert!(normalize_offline_mode(&argv));
942 assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
943 }
944
945 #[test]
946 fn project_trust_flags_are_honored_without_warning() {
947 let approved = parse_args(&s(&["--approve"]));
948 assert_eq!(approved.trust_override, Some(true));
949 assert!(approved.ignored.is_empty());
950 let denied = parse_args(&s(&["--no-approve"]));
951 assert_eq!(denied.trust_override, Some(false));
952 assert!(denied.ignored.is_empty());
953 }
954
955 #[test]
956 fn export_flag_captures_input_and_output_position() {
957 let args = parse_args(&s(&["--export", "session.jsonl", "transcript.html"]));
958 assert_eq!(args.export, Some(PathBuf::from("session.jsonl")));
959 assert_eq!(args.messages, vec!["transcript.html".to_string()]);
960 assert!(args.ignored.is_empty());
961 }
962
963 #[test]
964 fn session_id_and_fork_flags_parse() {
965 let a = parse_args(&s(&["--session-id", "01abc", "--fork", "xyz"]));
966 assert!(a.errors.is_empty());
967 assert_eq!(a.session_id.as_deref(), Some("01abc"));
968 assert_eq!(a.fork.as_deref(), Some("xyz"));
969 let a = parse_args(&s(&[
970 "-e",
971 "plugin.dll",
972 "--skill",
973 "s",
974 "--prompt-template",
975 "t.md",
976 ]));
977 assert_eq!(a.extension.len(), 1);
978 assert_eq!(a.skill.len(), 1);
979 assert_eq!(a.prompt_template.len(), 1);
980 }
981
982 #[test]
983 fn no_skills_flag_honored() {
984 let a = parse_args(&s(&["-ns"]));
985 assert!(a.errors.is_empty());
986 assert!(a.no_skills);
987 assert!(a.ignored.is_empty());
989 }
990
991 #[test]
992 fn no_prompt_templates_flag_honored() {
993 let a = parse_args(&s(&["--no-prompt-templates"]));
994 assert!(a.no_prompt_templates);
995 assert!(a.ignored.is_empty());
996 }
997
998 #[test]
999 fn no_context_files_flag_honored() {
1000 let a = parse_args(&s(&["-nc"]));
1001 assert!(a.no_context_files);
1002 assert!(a.ignored.is_empty());
1003 }
1004
1005 #[test]
1006 fn no_extensions_flag_honored() {
1007 let a = parse_args(&s(&["--no-extensions"]));
1009 assert!(a.no_extensions);
1010 assert!(a.ignored.is_empty());
1011 }
1012
1013 #[test]
1014 fn local_only_flag_is_honored_on_the_regular_parser() {
1015 let a = parse_args(&s(&["--local-only"]));
1018 assert!(a.errors.is_empty());
1019 assert!(a.dev_local_only);
1020 assert!(a.ignored.is_empty());
1021 }
1022
1023 #[test]
1024 fn project_only_aliases_are_honored() {
1025 for flag in ["--package-only", "--project-only"] {
1026 let a = parse_args(&s(&[flag]));
1027 assert!(a.errors.is_empty());
1028 assert!(a.project_only);
1029 assert!(a.ignored.is_empty());
1030 }
1031 }
1032
1033 #[test]
1034 fn extensions_dir_flag_collects_dirs() {
1035 let a = parse_args(&s(&["--extensions-dir", "/a/b", "-ed", "/c/d"]));
1036 assert_eq!(
1037 a.extensions_dir,
1038 vec![PathBuf::from("/a/b"), PathBuf::from("/c/d")]
1039 );
1040 assert!(a.ignored.is_empty());
1041 }
1042
1043 #[test]
1044 fn extensions_dir_inline_equals_form() {
1045 let a = parse_args(&s(&["--extensions-dir=/x/y"]));
1046 assert_eq!(a.extensions_dir, vec![PathBuf::from("/x/y")]);
1047 }
1048
1049 #[test]
1050 fn extensions_dir_env_is_merged() {
1051 let a = parse_args(&s(&["--extensions-dir", "/flag/only"]));
1057 assert!(a
1058 .extensions_dir
1059 .iter()
1060 .any(|p| p == &PathBuf::from("/flag/only")));
1061 }
1062
1063 #[test]
1064 fn file_args_stripped() {
1065 let a = parse_args(&s(&["@a.txt", "@b.md", "hi"]));
1066 assert_eq!(
1067 a.file_args,
1068 vec![PathBuf::from("a.txt"), PathBuf::from("b.md")]
1069 );
1070 assert_eq!(a.messages, vec!["hi".to_string()]);
1071 }
1072
1073 #[test]
1074 fn equals_form_supported() {
1075 let a = parse_args(&s(&["--model=claude-sonnet-5", "--thinking=low"]));
1076 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1077 assert_eq!(a.thinking, Some(ThinkingLevel::Low));
1078 }
1079
1080 #[test]
1081 fn theme_flag_is_honored() {
1082 let a = parse_args(&s(&["--theme", "ocean.json"]));
1083 assert_eq!(a.theme.as_deref(), Some("ocean.json"));
1084 assert!(a.ignored.is_empty());
1085 }
1086
1087 #[test]
1088 fn no_themes_is_honored() {
1089 let a = parse_args(&s(&["--no-themes"]));
1090 assert!(a.no_themes);
1091 assert!(a.ignored.is_empty());
1092 }
1093
1094 #[test]
1095 fn tui_mode_parses_and_validates() {
1096 assert_eq!(
1097 parse_args(&s(&["--tui-mode", "regular"])).tui_mode,
1098 TuiMode::Regular
1099 );
1100 assert_eq!(
1101 parse_args(&s(&["--tui-mode=fullscreen"])).tui_mode,
1102 TuiMode::Fullscreen
1103 );
1104 let invalid = parse_args(&s(&["--tui-mode", "split"]));
1105 assert!(!invalid.errors.is_empty());
1106 }
1107
1108 #[test]
1109 fn tui_mode_default_preserves_native_macos_scrollback() {
1110 assert_eq!(default_tui_mode_for(true), TuiMode::Regular);
1111 assert_eq!(default_tui_mode_for(false), TuiMode::Fullscreen);
1112 }
1113
1114 #[test]
1115 fn resolve_mode_interactive_when_tty() {
1116 let a = Args {
1117 print: true,
1118 ..Args::default()
1119 };
1120 assert_eq!(resolve_mode(&a, true, true), RunMode::Print);
1121 let a = Args::default();
1122 assert_eq!(resolve_mode(&a, true, true), RunMode::Interactive);
1123 let a = Args {
1124 mode: Mode::Json,
1125 ..Args::default()
1126 };
1127 assert_eq!(resolve_mode(&a, true, true), RunMode::Json);
1128 let a = Args {
1129 mode: Mode::Rpc,
1130 ..Args::default()
1131 };
1132 assert_eq!(resolve_mode(&a, true, true), RunMode::Rpc);
1133 }
1134
1135 #[test]
1136 fn piped_stdout_forces_print() {
1137 let a = Args::default();
1138 assert_eq!(resolve_mode(&a, true, false), RunMode::Print);
1140 }
1141}