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, 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#[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#[derive(Debug, Clone, Default)]
125pub struct Args {
126 pub provider: Option<String>,
127 pub model: Option<String>,
128 pub api_key: Option<String>,
129 pub base_url: Option<String>,
132 pub timeout: Option<Duration>,
134 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 pub theme: Option<String>,
142 pub thinking: Option<ThinkingLevel>,
143
144 pub print: bool,
145 pub mode: Mode,
146 pub rpc_message_updates: RpcMessageUpdates,
147 pub tui_mode: TuiMode,
151
152 pub list_models: Option<String>,
155 pub offline: bool,
157 pub export: Option<PathBuf>,
160 pub trust_override: Option<bool>,
163
164 pub continue_session: bool,
165 pub resume: bool,
166 pub session: Option<String>,
167 pub session_id: Option<String>,
171 pub fork: Option<String>,
174 pub models: Option<Vec<String>>,
178 pub session_dir: Option<PathBuf>,
179 pub no_session: bool,
180 pub name: Option<String>,
181
182 pub tools: Option<Vec<String>>,
183 pub exclude_tools: Option<Vec<String>>,
184 pub no_tools: bool,
185 pub no_builtin_tools: bool,
186 pub native_durable: bool,
189 pub experimental_durable_epoch: Option<String>,
191
192 pub no_skills: bool,
195 pub no_prompt_templates: bool,
198 pub no_context_files: bool,
201 pub no_extensions: bool,
204 pub no_themes: bool,
207 pub extensions_dir: Vec<PathBuf>,
215 pub extension: Vec<PathBuf>,
218 pub skill: Vec<PathBuf>,
220 pub prompt_template: Vec<PathBuf>,
223
224 pub dev_local_only: bool,
226 pub project_only: bool,
229
230 pub verbose: bool,
231 pub help: bool,
232 pub version: bool,
233
234 pub debug_system_prompt: bool,
241
242 pub messages: Vec<String>,
244 pub file_args: Vec<PathBuf>,
247
248 pub unknown_flags: BTreeMap<String, serde_json::Value>,
252 pub ignored: Vec<String>,
255 pub errors: Vec<String>,
258}
259
260pub use rpi_runtime::thinking::VALID_THINKING_LEVELS;
263
264pub use rpi_runtime::thinking::parse_thinking_level;
266
267fn file_arg(arg: &str) -> Option<PathBuf> {
270 if let Some(rest) = arg.strip_prefix('@') {
271 if rest.is_empty() {
273 None
274 } else {
275 Some(PathBuf::from(rest))
276 }
277 } else {
278 None
279 }
280}
281
282pub fn parse_args(args: &[String]) -> Args {
288 let mut result = Args::default();
289 result.native_durable = true;
292 result.offline = offline_env_enabled();
293 let mut env_extension_dirs = Vec::new();
297 if let Ok(raw) = std::env::var("RPI_EXTENSIONS_DIR") {
298 if !raw.is_empty() {
299 let sep = if cfg!(windows) { ';' } else { ':' };
300 for part in raw.split(sep) {
301 let trimmed = part.trim();
302 if !trimmed.is_empty() {
303 env_extension_dirs.push(PathBuf::from(trimmed));
304 }
305 }
306 }
307 }
308 let mut i = 0;
309 while i < args.len() {
310 let arg = args[i].clone();
311 let (flag_key, inline) = if arg.starts_with("--") {
315 match arg.find('=') {
316 Some(eq) => (arg[..eq].to_string(), Some(arg[eq + 1..].to_string())),
317 None => (arg.clone(), None),
318 }
319 } else {
320 (arg.clone(), None)
321 };
322
323 let mut take_value = |result: &mut Args, _flag: &str| -> Option<String> {
327 if let Some(v) = inline.clone() {
328 return Some(v);
329 }
330 if i + 1 < args.len() {
331 let next = &args[i + 1];
332 if !next.starts_with('-') || next == "-" {
333 i += 1;
334 return Some(args[i].clone());
335 }
336 }
337 result.errors.push(format!("{flag_key} requires a value"));
338 None
339 };
340
341 match flag_key.as_str() {
342 "--help" | "-h" => result.help = true,
343 "--version" | "-v" => result.version = true,
344 "--print" | "-p" => {
345 result.print = true;
346 if i + 1 < args.len() {
351 let next = &args[i + 1];
352 if !next.starts_with('@') && !next.starts_with('-') {
353 i += 1;
354 result.messages.push(args[i].clone());
355 }
356 }
357 }
358 "--mode" => {
359 if let Some(v) = take_value(&mut result, "--mode") {
360 result.mode = match v.as_str() {
361 "text" => Mode::Text,
362 "json" => Mode::Json,
363 "rpc" => Mode::Rpc,
364 other => {
365 result.errors.push(format!(
366 "Invalid --mode \"{other}\". Valid: text, json, rpc"
367 ));
368 Mode::Text
369 }
370 };
371 }
372 }
373 "--rpc-message-updates" => {
374 if let Some(value) = take_value(&mut result, "--rpc-message-updates") {
375 match value.as_str() {
376 "snapshot" => result.rpc_message_updates = RpcMessageUpdates::Snapshot,
377 "compact-deltas" => result.rpc_message_updates = RpcMessageUpdates::CompactDeltas,
378 other => result.errors.push(format!(
379 "Invalid --rpc-message-updates \"{other}\". Valid: snapshot, compact-deltas"
380 )),
381 }
382 }
383 }
384 "--tui-mode" => {
385 if let Some(v) = take_value(&mut result, "--tui-mode") {
386 result.tui_mode = match v.to_ascii_lowercase().as_str() {
387 "regular" => TuiMode::Regular,
388 "fullscreen" => TuiMode::Fullscreen,
389 other => {
390 result.errors.push(format!(
391 "Invalid --tui-mode \"{other}\". Valid: regular, fullscreen"
392 ));
393 TuiMode::Fullscreen
394 }
395 };
396 }
397 }
398 "--continue" | "-c" => result.continue_session = true,
399 "--resume" | "-r" => result.resume = true,
400 "--no-session" => result.no_session = true,
401 "--no-tools" | "-nt" => result.no_tools = true,
402 "--no-builtin-tools" | "-nbt" => result.no_builtin_tools = true,
403 "--native-durable" => result.native_durable = true,
406 "--no-native-durable" => result.native_durable = false,
407 "--experimental-durable-epoch" => {
408 if result.experimental_durable_epoch.is_some() {
409 result
410 .errors
411 .push("--experimental-durable-epoch may only be supplied once".into());
412 }
413 if let Some(epoch) = take_value(&mut result, "--experimental-durable-epoch") {
414 result.experimental_durable_epoch = Some(epoch);
415 }
416 }
417 "--no-skills" | "-ns" => result.no_skills = true,
418 "--no-prompt-templates" | "-np" => result.no_prompt_templates = true,
419 "--no-context-files" | "-nc" => result.no_context_files = true,
420 "--no-extensions" | "-ne" => result.no_extensions = true,
421 "--local-only" => result.dev_local_only = true,
422 "--package-only" | "--project-only" => result.project_only = true,
423 "--extensions-dir" | "-ed" => {
424 if let Some(v) = take_value(&mut result, &flag_key) {
425 result.extensions_dir.push(PathBuf::from(v));
426 }
427 }
428 "--verbose" => result.verbose = true,
429 "--debug-system-prompt" => result.debug_system_prompt = true,
430 "--provider" => result.provider = take_value(&mut result, "--provider"),
431 "--model" => result.model = take_value(&mut result, "--model"),
432 "--api-key" => result.api_key = take_value(&mut result, "--api-key"),
433 "--base-url" => result.base_url = take_value(&mut result, "--base-url"),
434 "--timeout" => {
435 if let Some(v) = take_value(&mut result, "--timeout") {
436 match v.parse::<u64>() {
437 Ok(seconds) if seconds > 0 => {
438 result.timeout = Some(Duration::from_secs(seconds));
439 }
440 _ => result.errors.push(format!(
441 "Invalid --timeout \"{v}\". Expected a positive integer number of seconds"
442 )),
443 }
444 }
445 }
446 "--stream-idle-timeout" => {
447 if let Some(v) = take_value(&mut result, "--stream-idle-timeout") {
448 match v.parse::<u64>() {
449 Ok(seconds) => result.stream_idle_timeout = Some(Duration::from_secs(seconds)),
450 Err(_) => result.errors.push(format!(
451 "Invalid --stream-idle-timeout \"{v}\". Expected a non-negative integer number of seconds (0 disables it)"
452 )),
453 }
454 }
455 }
456 "--resource-config" => {
457 result.resource_config =
458 take_value(&mut result, "--resource-config").map(PathBuf::from)
459 }
460 "--resource-transition" => {
461 result.resource_transition =
462 take_value(&mut result, "--resource-transition").map(PathBuf::from)
463 }
464 "--system-prompt" => result.system_prompt = take_value(&mut result, "--system-prompt"),
465 "--append-system-prompt" => {
466 if let Some(v) = take_value(&mut result, "--append-system-prompt") {
467 result.append_system_prompt.push(v);
468 }
469 }
470 "--name" | "-n" => result.name = take_value(&mut result, "--name"),
471 "--session" => result.session = take_value(&mut result, "--session"),
472 "--session-id" => result.session_id = take_value(&mut result, "--session-id"),
473 "--fork" => result.fork = take_value(&mut result, "--fork"),
474 "--models" => {
475 if let Some(v) = take_value(&mut result, &flag_key) {
476 result.models = Some(split_csv(&v));
477 }
478 }
479 "--extension" | "-e" => {
480 if let Some(v) = take_value(&mut result, &flag_key) {
481 result.extension.push(PathBuf::from(v));
482 }
483 }
484 "--skill" => {
485 if let Some(v) = take_value(&mut result, &flag_key) {
486 result.skill.push(PathBuf::from(v));
487 }
488 }
489 "--prompt-template" => {
490 if let Some(v) = take_value(&mut result, &flag_key) {
491 result.prompt_template.push(PathBuf::from(v));
492 }
493 }
494 "--session-dir" => {
495 if let Some(v) = take_value(&mut result, "--session-dir") {
496 result.session_dir = Some(PathBuf::from(v));
497 }
498 }
499 "--thinking" => {
500 if let Some(v) = take_value(&mut result, "--thinking") {
501 match parse_thinking_level(&v) {
502 Some(lvl) => result.thinking = Some(lvl),
503 None => result.ignored.push(format!(
504 "Invalid --thinking \"{v}\". Valid: {}",
505 VALID_THINKING_LEVELS.join(", ")
506 )),
507 }
508 }
509 }
510 "--tools" | "-t" => {
511 if let Some(v) = take_value(&mut result, &flag_key) {
512 result.tools = Some(split_csv(&v));
513 }
514 }
515 "--exclude-tools" | "-xt" => {
516 if let Some(v) = take_value(&mut result, &flag_key) {
517 result.exclude_tools = Some(split_csv(&v));
518 }
519 }
520 "--list-models" => {
521 let mut search = inline.clone().unwrap_or_default();
524 if inline.is_none()
525 && i + 1 < args.len()
526 && !args[i + 1].starts_with('-')
527 && !args[i + 1].starts_with('@')
528 {
529 i += 1;
530 search = args[i].clone();
531 }
532 result.list_models = Some(search);
533 }
534 "--offline" => result.offline = true,
535 "--export" => {
536 if let Some(value) = take_value(&mut result, &flag_key) {
537 result.export = Some(PathBuf::from(value));
538 }
539 }
540 "--approve" | "-a" => result.trust_override = Some(true),
541 "--no-approve" | "-na" => result.trust_override = Some(false),
542 other if matches!(other, "--models") => {
553 if inline.is_none()
556 && i + 1 < args.len()
557 && !args[i + 1].starts_with('-')
558 && !args[i + 1].starts_with('@')
559 {
560 i += 1;
561 }
562 result
563 .ignored
564 .push(format!("{other} is not supported in v1 (ignored)"));
565 }
566 "--theme" => {
567 result.theme = take_value(&mut result, "--theme");
568 }
569 "--no-themes" => result.no_themes = true,
570 other if other.starts_with("--") => {
575 let name = &flag_key;
576 let value = if let Some(value) = inline {
577 serde_json::Value::String(value)
578 } else if i + 1 < args.len()
579 && !args[i + 1].starts_with('-')
580 && !args[i + 1].starts_with('@')
581 {
582 i += 1;
583 serde_json::Value::String(args[i].clone())
584 } else {
585 serde_json::Value::Bool(true)
586 };
587 result.unknown_flags.insert(name[2..].to_string(), value);
588 }
589 other if other.starts_with('-') && other.len() > 1 => {
591 result.errors.push(format!("Unknown option: {other}"));
592 }
593 other => {
594 if let Some(path) = file_arg(other) {
595 result.file_args.push(path);
596 } else {
597 result.messages.push(other.to_string());
598 }
599 }
600 }
601 i += 1;
602 }
603
604 if result.resource_config.is_none() && result.resource_transition.is_none() {
606 env_extension_dirs.append(&mut result.extensions_dir);
607 result.extensions_dir = env_extension_dirs;
608 }
609 if let Err(error) = crate::native_durable::experimental_epoch::policy(&result) {
613 result.errors.push(error);
614 }
615 result
616}
617
618fn split_csv(v: &str) -> Vec<String> {
620 v.split(',')
621 .map(|s| s.trim().to_string())
622 .filter(|s| !s.is_empty())
623 .collect()
624}
625
626pub fn resolve_mode(parsed: &Args, stdin_is_tty: bool, stdout_is_tty: bool) -> RunMode {
631 if parsed.unknown_flags.contains_key("server") {
633 return RunMode::Rpc;
634 }
635 if parsed.mode == Mode::Rpc {
636 return RunMode::Rpc;
637 }
638 if parsed.mode == Mode::Json {
639 return RunMode::Json;
640 }
641 if parsed.print || !stdin_is_tty || !stdout_is_tty {
642 RunMode::Print
643 } else {
644 RunMode::Interactive
645 }
646}
647
648#[derive(Debug, Clone, Copy, PartialEq, Eq)]
653pub enum RunMode {
654 Interactive,
655 Print,
656 Json,
657 Rpc,
658}
659
660pub fn print_help() {
662 let builtin = "read, bash, edit, write, docs";
663 println!(
664 "{name} - AI coding assistant with read, bash, edit, write, docs tools
665
666{u}Usage:{r}
667 {name} [options] [@files...] [messages...]
668
669{u}Options:{r}
670 --provider <name> Provider name (built-in, installed package, or models.json id)
671 --model <pattern> Model pattern or ID (supports \"provider/id\" and optional \":<thinking>\")
672 --api-key <key> API key override for the selected provider
673 --base-url <url> Override the selected model endpoint
674 --timeout <seconds> LLM API request timeout (default: 600)
675 --stream-idle-timeout <seconds> Max silence between response bytes (default: 300; 0 disables)
676 --resource-capabilities Pure bounded JSON resource protocol profile (use alone; no startup)
677 --resource-session-read <file> Strict bounded nonexecuting saved-session read (standalone)
678 --resource-transition <file> Explicit same-session resource CAS (RPC only; see docs/resource-transition-rpc.md)
679 --resource-config <file> Exact versioned startup resources (RPC only; see docs/resource-selection-rpc.md)
680 --system-prompt <text> Replace the default system prompt
681 --append-system-prompt <text> Append text to the system prompt (repeatable)
682 --thinking <level> off, minimal, low, medium, high, xhigh, max
683 --mode <mode> Output mode: text (default), json, or rpc
684 --rpc-message-updates <mode> RPC updates: compact-deltas (default) or snapshot (legacy)
685 --server [--port <n>] [--bind <ip>]
686 Headless server: serve a remote-connectable agent (no TUI)
687 --connect <host:port> Remote client: connect to a `--server` instance and run the TUI
688 (no local provider/tools/session; all agent work is remote)
689 --token <token> Auth token for `--connect` (printed by `--server`; may also
690 be provided via the RPI_SERVER_TOKEN env var)
691 --tui-mode <mode> TUI buffer: regular or fullscreen (macOS default: regular)
692 --list-models [search] List available models (with optional fuzzy search)
693 --offline Disable startup network operations (same as RPI_OFFLINE=1)
694 --export <file> Export a JSONL session to HTML and exit
695 --approve, -a Force-enable current-project resources
696 --no-approve, -na Disable current-project resources
697 --print, -p Non-interactive: process prompt(s) and exit
698 --continue, -c Continue the most recent session
699 --resume, -r Browse and select a session to resume
700 --session <id|path> Use a specific session (partial UUID or file)
701 --session-dir <dir> Directory for session storage
702 --no-session Ephemeral mode (do not persist the session)
703 --name, -n <name> Set the session display name
704 --tools, -t <list> Comma-separated allowlist of tool names to enable
705 --exclude-tools, -xt <list> Comma-separated denylist of tool names to disable
706 --no-tools, -nt Disable all tools
707 --no-builtin-tools, -nbt Disable the built-in tools (read, bash, edit, write, docs)
708 --no-native-durable Temporary escape hatch: use legacy session behavior
709 --experimental-durable-epoch <id>
710 With native durable enabled: bounded v2 ledger, explicit same epoch on reopen; no migration
711 --no-skills, -ns Skip skill discovery (no <available_skills> block)
712 --no-prompt-templates, -np Skip prompt-template discovery (/expand templates)
713 --no-context-files, -nc Skip AGENTS.md/CLAUDE.md discovery (no <project_context>)
714 --no-extensions, -ne Skip Rust cdylib extension loading
715 --extensions-dir, -ed <dir> Extra dir to scan for plugins (.dll/.so/.dylib); repeatable
716 (also via RPI_EXTENSIONS_DIR env: ';' on Windows, ':' on Unix)
717 --local-only Skip automatic extension discovery: load only
718 --extensions-dir / --extension paths (no project
719 .rpi/extensions, no global extensions)
720 --package-only, --project-only Load project skills/prompts/extensions/packages
721 from the active project; exclude global resources
722 --debug-system-prompt Print the resolved system-prompt sections to stderr (verification)
723 --verbose Show startup warnings (e.g. ignored flags)
724 --help, -h Show this help
725 --version, -v Show version
726
727{u}Subcommands:{r}
728 update Update the rpi CLI from crates.io
729 auth login|check|logout Manage persisted credentials in ~/.rpi/auth.json
730 (see `rpi auth --help`)
731 events path|tail Inspect the extension event journal (needs
732 RPI_EVENT_LOG=1; see `rpi events --help`)
733 install <crate> Install a prebuilt Rust extension (--build for source)
734 (see `rpi install --help`)
735 uninstall <crate> Remove an installed Rust cdylib extension
736 extension update [name] Update project and global installed Rust extensions
737 (see `rpi extension update --help`)
738 package link|list|update|unlink Manage project-local Rust extension packages
739 (update is a legacy alias; see `rpi package --help`)
740 dev [options] Build, watch, and hot-reload a Rust extension
741 (see `rpi dev --help`)
742 dev-local [options] Debug only the current Rust extension
743 (shortcut for `rpi dev --local-only`)
744
745{u}Built-in Tools:{r}
746 {builtin} (enabled by default)
747
748{u}Examples:{r}
749 # Interactive with an initial prompt
750 {name} \"List all .rs files in src/\"
751
752 # Single-shot print mode
753 {name} -p \"Summarize this project\"
754
755 # Include a file in the initial message
756 {name} @README.md \"What does this project do?\"
757
758 # Continue the previous session
759 {name} -c \"What did we discuss?\"
760
761 # Use a specific model + thinking level
762 {name} --model claude-sonnet-5 --thinking high \"Refactor this\"
763
764 # JSON event stream (one JSON object per line on stdout)
765 {name} --mode json -p \"Inspect the code\"
766
767 # Read-only: no file-modifying tools
768 {name} --tools read,bash -p \"Review the code in src/\"
769
770{u}Environment:{r}
771 ANTHROPIC_API_KEY Anthropic API key (x-api-key) — fallback when no stored credential
772 ANTHROPIC_AUTH_TOKEN Bearer token (Authorization: Bearer) for third-party gateways
773 ANTHROPIC_BASE_URL Override the Anthropic endpoint (e.g. a compatible proxy)
774 OPENAI_API_KEY Bearer token for openai-completions/responses
775 RPI_OFFLINE Disable startup network operations when set to 1/true/yes
776 RPI_CODING_AGENT_DIR Override the ~/.rpi config directory (auth.json + models.json)
777 RPI_SESSION_ID Session id served by a plugin (set by the host; also honored as an override)
778 RPI_NO_EMOJI Render the brand lockup without the crab (1/true/yes)
779
780{u}Notes:{r}
781 Supported HTTP protocols are Anthropic Messages and OpenAI Chat Completions.
782 Define custom model catalogs and provider apiKey values in
783 ~/.rpi/agent/models.json. The interactive TUI, Rust extensions, skills,
784 prompt templates, themes, model cycling, session fork/export, and trust
785 commands are available in the current build. OAuth, RPC, and full model
786 cycling remain outside the current implementation.
787",
788 name = crate::APP_NAME,
789 builtin = builtin,
790 u = "\x1b[1m",
791 r = "\x1b[0m",
792 );
793}
794
795pub fn print_version() {
797 println!("{} {}", crate::APP_NAME, crate::VERSION);
798}
799
800#[cfg(test)]
801mod tests {
802 #[test]
803 fn rpc_message_updates_selection_and_errors() {
804 assert_eq!(
805 super::Args::default().rpc_message_updates,
806 super::RpcMessageUpdates::CompactDeltas
807 );
808 for (value, expected) in [
809 ("snapshot", super::RpcMessageUpdates::Snapshot),
810 ("compact-deltas", super::RpcMessageUpdates::CompactDeltas),
811 ] {
812 for args in [
813 vec![
814 "--mode".into(),
815 "rpc".into(),
816 format!("--rpc-message-updates={value}"),
817 ],
818 vec!["--rpc-message-updates".into(), value.into()],
819 ] {
820 let parsed = super::parse_args(&args);
821 assert!(parsed.errors.is_empty(), "{:?}", parsed.errors);
822 assert_eq!(parsed.rpc_message_updates, expected);
823 assert!(parsed.unknown_flags.is_empty());
824 }
825 }
826 for args in [
827 vec!["--rpc-message-updates".into()],
828 vec!["--rpc-message-updates".into(), "--mode=json".into()],
829 vec!["--rpc-message-updates=".into()],
830 vec!["--rpc-message-updates=invalid".into()],
831 vec!["--rpc-message-updates".into(), "invalid".into()],
832 ] {
833 let parsed = super::parse_args(&args);
834 assert_eq!(parsed.errors.len(), 1);
835 assert!(parsed.errors[0].contains("--rpc-message-updates"));
836 }
837 let parsed = super::parse_args(&[
838 "--mode=json".into(),
839 "--rpc-message-updates=snapshot".into(),
840 ]);
841 assert_eq!(parsed.mode, super::Mode::Json);
842 }
843
844 use super::*;
845
846 struct RestoreOfflineEnv(Option<std::ffi::OsString>);
847
848 impl Drop for RestoreOfflineEnv {
849 fn drop(&mut self) {
850 match self.0.take() {
851 Some(value) => std::env::set_var(RPI_OFFLINE_ENV, value),
852 None => std::env::remove_var(RPI_OFFLINE_ENV),
853 }
854 }
855 }
856
857 fn s(args: &[&str]) -> Vec<String> {
858 args.iter().map(|a| a.to_string()).collect()
859 }
860
861 #[test]
862 fn parses_basic_prompt() {
863 let a = parse_args(&s(&["hello", "world"]));
864 assert_eq!(a.messages, vec!["hello".to_string(), "world".to_string()]);
865 assert!(!a.help);
866 }
867
868 #[test]
869 fn parses_help_and_version() {
870 let a = parse_args(&s(&["--help"]));
871 assert!(a.help);
872 let a = parse_args(&s(&["-v"]));
873 assert!(a.version);
874 }
875
876 #[test]
877 fn print_consumes_following_positional() {
878 let a = parse_args(&s(&["-p", "summarize"]));
879 assert!(a.print);
880 assert_eq!(a.messages, vec!["summarize".to_string()]);
881 }
882
883 #[test]
884 fn print_does_not_consume_file_or_flag() {
885 let a = parse_args(&s(&["-p", "@file.md"]));
886 assert!(a.print);
887 assert!(a.messages.is_empty());
888 assert_eq!(a.file_args, vec![PathBuf::from("file.md")]);
889 }
890
891 #[test]
892 fn model_and_thinking() {
893 let a = parse_args(&s(&["--model", "claude-sonnet-5", "--thinking", "high"]));
894 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
895 assert_eq!(a.thinking, Some(ThinkingLevel::High));
896 }
897
898 #[test]
899 fn model_with_thinking_shorthand() {
900 let a = parse_args(&s(&["--model", "claude-sonnet-5:high"]));
901 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5:high"));
903 }
904
905 #[test]
906 fn tools_split_csv() {
907 let a = parse_args(&s(&["--tools", "read, bash ,write"]));
908 assert_eq!(
909 a.tools.as_deref(),
910 Some(&["read".to_string(), "bash".to_string(), "write".to_string()][..])
911 );
912 }
913
914 #[test]
915 fn native_durable_is_enabled_by_default_with_a_transition_escape_hatch() {
916 assert!(parse_args(&s(&[])).native_durable);
917 assert!(parse_args(&s(&["--native-durable"])).native_durable);
918 assert!(!parse_args(&s(&["--no-native-durable"])).native_durable);
919 assert!(parse_args(&s(&["--no-native-durable", "--native-durable"])).native_durable);
920 assert!(!parse_args(&s(&["--native-durable", "--no-native-durable"])).native_durable);
921 }
922
923 #[test]
924 fn unknown_short_flag_errors() {
925 let a = parse_args(&s(&["-Z"]));
926 assert!(!a.errors.is_empty());
927 }
928
929 #[test]
930 fn unknown_long_flag_is_retained_for_extensions() {
931 let a = parse_args(&s(&["--frobnicate", "value"]));
932 assert!(a.errors.is_empty());
933 assert_eq!(
934 a.unknown_flags.get("frobnicate"),
935 Some(&serde_json::Value::String("value".into()))
936 );
937 assert!(a.ignored.is_empty());
938 }
939
940 #[test]
941 fn unknown_long_boolean_flag_is_retained() {
942 let a = parse_args(&s(&["--server"]));
943 assert_eq!(
944 a.unknown_flags.get("server"),
945 Some(&serde_json::Value::Bool(true))
946 );
947 }
948
949 #[test]
950 fn unknown_long_flags_keep_string_and_equals_values() {
951 let a = parse_args(&s(&["--port", "8080", "--bind=127.0.0.1"]));
952 assert_eq!(
953 a.unknown_flags.get("port"),
954 Some(&serde_json::Value::String("8080".into()))
955 );
956 assert_eq!(
957 a.unknown_flags.get("bind"),
958 Some(&serde_json::Value::String("127.0.0.1".into()))
959 );
960 }
961
962 #[test]
963 fn models_flag_parses_csv() {
964 let a = parse_args(&s(&["--models", "a,b,c"]));
965 assert!(a.errors.is_empty());
966 assert!(a.ignored.is_empty(), "--models is implemented");
967 assert_eq!(
968 a.models.as_deref(),
969 Some(&["a".to_string(), "b".to_string(), "c".to_string()][..])
970 );
971 assert!(a.messages.is_empty());
973 }
974
975 #[test]
976 fn list_models_accepts_bare_and_search_forms() {
977 let bare = parse_args(&s(&["--list-models"]));
978 assert_eq!(bare.list_models.as_deref(), Some(""));
979 assert!(bare.ignored.is_empty());
980 assert!(bare.messages.is_empty());
981
982 let search = parse_args(&s(&["--list-models", "claude"]));
983 assert_eq!(search.list_models.as_deref(), Some("claude"));
984 assert!(search.messages.is_empty());
985
986 let inline = parse_args(&s(&["--list-models=gpt"]));
987 assert_eq!(inline.list_models.as_deref(), Some("gpt"));
988 }
989
990 #[test]
991 fn offline_flag_is_honored_without_warning() {
992 let args = parse_args(&s(&["--offline"]));
993 assert!(args.offline);
994 assert!(args.ignored.is_empty());
995 }
996
997 #[test]
998 fn timeout_parses_seconds_in_separate_and_equals_forms() {
999 let separate = parse_args(&s(&["--timeout", "45"]));
1000 assert!(separate.errors.is_empty());
1001 assert_eq!(separate.timeout, Some(Duration::from_secs(45)));
1002
1003 let inline = parse_args(&s(&["--timeout=90"]));
1004 assert!(inline.errors.is_empty());
1005 assert_eq!(inline.timeout, Some(Duration::from_secs(90)));
1006 }
1007
1008 #[test]
1009 fn timeout_rejects_zero_and_invalid_values() {
1010 for value in ["0", "1.5", "forever", "18446744073709551616"] {
1011 let args = parse_args(&s(&[&format!("--timeout={value}")]));
1012 assert_eq!(args.errors.len(), 1, "value: {value}");
1013 assert!(args.timeout.is_none(), "value: {value}");
1014 }
1015 }
1016
1017 #[test]
1018 fn stream_idle_timeout_accepts_both_forms_and_zero_but_rejects_invalid_values() {
1019 for (argv, seconds) in [
1020 (s(&["--stream-idle-timeout", "45"]), 45),
1021 (s(&["--stream-idle-timeout=90"]), 90),
1022 (s(&["--stream-idle-timeout=0"]), 0),
1023 ] {
1024 let args = parse_args(&argv);
1025 assert!(args.errors.is_empty(), "{:?}", args.errors);
1026 assert_eq!(args.stream_idle_timeout, Some(Duration::from_secs(seconds)));
1027 assert!(args.timeout.is_none());
1028 }
1029 for value in ["-1", "1.5", "no", "18446744073709551616"] {
1030 let args = parse_args(&s(&[&format!("--stream-idle-timeout={value}")]));
1031 assert!(!args.errors.is_empty(), "{value}");
1032 assert!(args.stream_idle_timeout.is_none());
1033 }
1034 assert!(!parse_args(&s(&["--stream-idle-timeout"])).errors.is_empty());
1035 }
1036
1037 #[test]
1038 fn native_pi_offline_truthy_values_are_case_insensitive() {
1039 for value in [
1040 Some("1"),
1041 Some("true"),
1042 Some("TRUE"),
1043 Some("Yes"),
1044 Some("yEs"),
1045 ] {
1046 assert!(is_truthy_env_flag(value), "value={value:?}");
1047 }
1048 for value in [
1049 None,
1050 Some(""),
1051 Some("0"),
1052 Some("false"),
1053 Some("no"),
1054 Some(" true "),
1055 ] {
1056 assert!(!is_truthy_env_flag(value), "value={value:?}");
1057 }
1058 }
1059
1060 #[test]
1061 fn pi_offline_env_and_cli_flag_share_one_normalized_gate() {
1062 let _guard = crate::config::test_support::env_lock().lock().unwrap();
1063 let _restore = RestoreOfflineEnv(std::env::var_os(RPI_OFFLINE_ENV));
1064
1065 std::env::set_var(RPI_OFFLINE_ENV, "YeS");
1066 assert!(parse_args(&[]).offline);
1067 assert!(normalize_offline_mode(&[]));
1068 assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
1069
1070 std::env::set_var(RPI_OFFLINE_ENV, "0");
1071 assert!(!parse_args(&[]).offline);
1072 let argv = s(&["--offline"]);
1073 assert!(normalize_offline_mode(&argv));
1074 assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
1075 }
1076
1077 #[test]
1078 fn project_trust_flags_are_honored_without_warning() {
1079 let approved = parse_args(&s(&["--approve"]));
1080 assert_eq!(approved.trust_override, Some(true));
1081 assert!(approved.ignored.is_empty());
1082 let denied = parse_args(&s(&["--no-approve"]));
1083 assert_eq!(denied.trust_override, Some(false));
1084 assert!(denied.ignored.is_empty());
1085 }
1086
1087 #[test]
1088 fn export_flag_captures_input_and_output_position() {
1089 let args = parse_args(&s(&["--export", "session.jsonl", "transcript.html"]));
1090 assert_eq!(args.export, Some(PathBuf::from("session.jsonl")));
1091 assert_eq!(args.messages, vec!["transcript.html".to_string()]);
1092 assert!(args.ignored.is_empty());
1093 }
1094
1095 #[test]
1096 fn session_id_and_fork_flags_parse() {
1097 let a = parse_args(&s(&["--session-id", "01abc", "--fork", "xyz"]));
1098 assert!(a.errors.is_empty());
1099 assert_eq!(a.session_id.as_deref(), Some("01abc"));
1100 assert_eq!(a.fork.as_deref(), Some("xyz"));
1101 let a = parse_args(&s(&[
1102 "-e",
1103 "plugin.dll",
1104 "--skill",
1105 "s",
1106 "--prompt-template",
1107 "t.md",
1108 ]));
1109 assert_eq!(a.extension.len(), 1);
1110 assert_eq!(a.skill.len(), 1);
1111 assert_eq!(a.prompt_template.len(), 1);
1112 }
1113
1114 #[test]
1115 fn no_skills_flag_honored() {
1116 let a = parse_args(&s(&["-ns"]));
1117 assert!(a.errors.is_empty());
1118 assert!(a.no_skills);
1119 assert!(a.ignored.is_empty());
1121 }
1122
1123 #[test]
1124 fn no_prompt_templates_flag_honored() {
1125 let a = parse_args(&s(&["--no-prompt-templates"]));
1126 assert!(a.no_prompt_templates);
1127 assert!(a.ignored.is_empty());
1128 }
1129
1130 #[test]
1131 fn no_context_files_flag_honored() {
1132 let a = parse_args(&s(&["-nc"]));
1133 assert!(a.no_context_files);
1134 assert!(a.ignored.is_empty());
1135 }
1136
1137 #[test]
1138 fn no_extensions_flag_honored() {
1139 let a = parse_args(&s(&["--no-extensions"]));
1141 assert!(a.no_extensions);
1142 assert!(a.ignored.is_empty());
1143 }
1144
1145 #[test]
1146 fn local_only_flag_is_honored_on_the_regular_parser() {
1147 let a = parse_args(&s(&["--local-only"]));
1150 assert!(a.errors.is_empty());
1151 assert!(a.dev_local_only);
1152 assert!(a.ignored.is_empty());
1153 }
1154
1155 #[test]
1156 fn project_only_aliases_are_honored() {
1157 for flag in ["--package-only", "--project-only"] {
1158 let a = parse_args(&s(&[flag]));
1159 assert!(a.errors.is_empty());
1160 assert!(a.project_only);
1161 assert!(a.ignored.is_empty());
1162 }
1163 }
1164
1165 #[test]
1166 fn extensions_dir_flag_collects_dirs() {
1167 let a = parse_args(&s(&["--extensions-dir", "/a/b", "-ed", "/c/d"]));
1168 assert_eq!(
1169 a.extensions_dir,
1170 vec![PathBuf::from("/a/b"), PathBuf::from("/c/d")]
1171 );
1172 assert!(a.ignored.is_empty());
1173 }
1174
1175 #[test]
1176 fn extensions_dir_inline_equals_form() {
1177 let a = parse_args(&s(&["--extensions-dir=/x/y"]));
1178 assert_eq!(a.extensions_dir, vec![PathBuf::from("/x/y")]);
1179 }
1180
1181 #[test]
1182 fn extensions_dir_env_is_merged() {
1183 let a = parse_args(&s(&["--extensions-dir", "/flag/only"]));
1189 assert!(a
1190 .extensions_dir
1191 .iter()
1192 .any(|p| p == &PathBuf::from("/flag/only")));
1193 }
1194
1195 #[test]
1196 fn file_args_stripped() {
1197 let a = parse_args(&s(&["@a.txt", "@b.md", "hi"]));
1198 assert_eq!(
1199 a.file_args,
1200 vec![PathBuf::from("a.txt"), PathBuf::from("b.md")]
1201 );
1202 assert_eq!(a.messages, vec!["hi".to_string()]);
1203 }
1204
1205 #[test]
1206 fn equals_form_supported() {
1207 let a = parse_args(&s(&["--model=claude-sonnet-5", "--thinking=low"]));
1208 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1209 assert_eq!(a.thinking, Some(ThinkingLevel::Low));
1210 }
1211
1212 #[test]
1213 fn theme_flag_is_honored() {
1214 let a = parse_args(&s(&["--theme", "ocean.json"]));
1215 assert_eq!(a.theme.as_deref(), Some("ocean.json"));
1216 assert!(a.ignored.is_empty());
1217 }
1218
1219 #[test]
1220 fn no_themes_is_honored() {
1221 let a = parse_args(&s(&["--no-themes"]));
1222 assert!(a.no_themes);
1223 assert!(a.ignored.is_empty());
1224 }
1225
1226 #[test]
1227 fn tui_mode_parses_and_validates() {
1228 assert_eq!(
1229 parse_args(&s(&["--tui-mode", "regular"])).tui_mode,
1230 TuiMode::Regular
1231 );
1232 assert_eq!(
1233 parse_args(&s(&["--tui-mode=fullscreen"])).tui_mode,
1234 TuiMode::Fullscreen
1235 );
1236 let invalid = parse_args(&s(&["--tui-mode", "split"]));
1237 assert!(!invalid.errors.is_empty());
1238 }
1239
1240 #[test]
1241 fn tui_mode_default_preserves_native_macos_scrollback() {
1242 assert_eq!(default_tui_mode_for(true), TuiMode::Regular);
1243 assert_eq!(default_tui_mode_for(false), TuiMode::Fullscreen);
1244 }
1245
1246 #[test]
1247 fn resolve_mode_interactive_when_tty() {
1248 let a = Args {
1249 print: true,
1250 ..Args::default()
1251 };
1252 assert_eq!(resolve_mode(&a, true, true), RunMode::Print);
1253 let a = Args::default();
1254 assert_eq!(resolve_mode(&a, true, true), RunMode::Interactive);
1255 let a = Args {
1256 mode: Mode::Json,
1257 ..Args::default()
1258 };
1259 assert_eq!(resolve_mode(&a, true, true), RunMode::Json);
1260 let a = Args {
1261 mode: Mode::Rpc,
1262 ..Args::default()
1263 };
1264 assert_eq!(resolve_mode(&a, true, true), RunMode::Rpc);
1265 }
1266
1267 #[test]
1268 fn piped_stdout_forces_print() {
1269 let a = Args::default();
1270 assert_eq!(resolve_mode(&a, true, false), RunMode::Print);
1272 }
1273}