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