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, Copy, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
124#[serde(rename_all = "kebab-case")]
125pub enum TuiFooter {
126 #[default]
127 Full,
128 Context,
129 Hidden,
130 Auto,
131}
132
133#[derive(Debug, Clone, Default)]
136pub struct Args {
137 pub provider: Option<String>,
138 pub model: Option<String>,
139 pub api_key: Option<String>,
140 pub base_url: Option<String>,
143 pub timeout: Option<Duration>,
145 pub stream_idle_timeout: Option<Duration>,
147 pub resource_config: Option<PathBuf>,
148 pub resource_transition: Option<PathBuf>,
149 pub system_prompt: Option<String>,
150 pub append_system_prompt: Vec<String>,
151 pub theme: Option<String>,
153 pub thinking: Option<ThinkingLevel>,
154
155 pub print: bool,
156 pub mini: bool,
158 pub host: Option<String>,
160 pub mode: Mode,
161 pub rpc_message_updates: RpcMessageUpdates,
162 pub tui_mode: TuiMode,
166 pub tui_footer: TuiFooter,
168
169 pub list_models: Option<String>,
172 pub offline: bool,
174 pub export: Option<PathBuf>,
177 pub trust_override: Option<bool>,
180
181 pub continue_session: bool,
182 pub resume: bool,
183 pub session: Option<String>,
184 pub session_id: Option<String>,
188 pub fork: Option<String>,
191 pub fork_entry: Option<String>,
196 pub fork_position: Option<rpi_harness::session::types::ForkPosition>,
202 pub models: Option<Vec<String>>,
206 pub session_dir: Option<PathBuf>,
207 pub no_session: bool,
208 pub name: Option<String>,
209
210 pub tools: Option<Vec<String>>,
211 pub exclude_tools: Option<Vec<String>>,
212 pub no_tools: bool,
213 pub no_builtin_tools: bool,
214 pub native_durable: bool,
217 pub experimental_durable_epoch: Option<String>,
219
220 pub no_skills: bool,
223 pub no_prompt_templates: bool,
226 pub no_context_files: bool,
229 pub no_extensions: bool,
232 pub no_themes: bool,
235 pub extensions_dir: Vec<PathBuf>,
243 pub extension: Vec<PathBuf>,
246 pub skill: Vec<PathBuf>,
248 pub prompt_template: Vec<PathBuf>,
251
252 pub dev_local_only: bool,
254 pub project_only: bool,
257
258 pub verbose: bool,
259 pub help: bool,
260 pub version: bool,
261
262 pub debug_system_prompt: bool,
269
270 pub messages: Vec<String>,
272 pub file_args: Vec<PathBuf>,
275
276 pub unknown_flags: BTreeMap<String, serde_json::Value>,
280 pub ignored: Vec<String>,
283 pub errors: Vec<String>,
286}
287
288impl Args {
289 pub(crate) fn fork_cut_errors(&self) -> Vec<&'static str> {
290 let mut errors = Vec::new();
291 if self.fork.is_none() {
292 if self.fork_entry.is_some() {
293 errors.push("--fork-entry requires --fork");
294 }
295 if self.fork_position.is_some() {
296 errors.push("--fork-position requires --fork");
297 }
298 } else if (self.fork_entry.is_some() || self.fork_position.is_some())
299 && (self.fork.as_deref() == Some("")
300 || self.no_session
301 || self.continue_session
302 || self.resume)
303 {
304 errors.push("--fork cut flags require an active --fork selection");
305 }
306 if self
307 .fork_entry
308 .as_deref()
309 .is_some_and(|id| id.trim().is_empty())
310 {
311 errors.push("--fork-entry requires a nonempty entry ID");
312 }
313 if self.fork_entry.is_none() && self.fork_position.is_some() {
315 errors.push("--fork-position requires --fork-entry");
316 }
317 errors
318 }
319}
320
321pub use rpi_runtime::thinking::VALID_THINKING_LEVELS;
324
325pub use rpi_runtime::thinking::parse_thinking_level;
327
328fn file_arg(arg: &str) -> Option<PathBuf> {
331 if let Some(rest) = arg.strip_prefix('@') {
332 if rest.is_empty() {
334 None
335 } else {
336 Some(PathBuf::from(rest))
337 }
338 } else {
339 None
340 }
341}
342
343pub fn parse_args(args: &[String]) -> Args {
349 parse_startup_args(args, false)
350}
351
352pub(crate) fn parse_startup_args(args: &[String], package: bool) -> Args {
353 let mut result = Args {
356 native_durable: true,
357 offline: offline_env_enabled(),
358 ..Args::default()
359 };
360 let mut env_extension_dirs = Vec::new();
364 if let Ok(raw) = std::env::var("RPI_EXTENSIONS_DIR") {
365 if !raw.is_empty() {
366 let sep = if cfg!(windows) { ';' } else { ':' };
367 for part in raw.split(sep) {
368 let trimmed = part.trim();
369 if !trimmed.is_empty() {
370 env_extension_dirs.push(PathBuf::from(trimmed));
371 }
372 }
373 }
374 }
375 let mut i = 0;
376 let mut host_arg_count = 0;
377 let mut host_tui_arg_count = 0;
378 let mut unsupported_host_rpc_flag = None;
379 while i < args.len() {
380 let arg = args[i].clone();
381 let (flag_key, inline) = if arg.starts_with("--") {
385 match arg.find('=') {
386 Some(eq) => (arg[..eq].to_string(), Some(arg[eq + 1..].to_string())),
387 None => (arg.clone(), None),
388 }
389 } else {
390 (arg.clone(), None)
391 };
392
393 if !matches!(
397 flag_key.as_str(),
398 "--host"
399 | "--mode"
400 | "--session"
401 | "-s"
402 | "--session-id"
403 | "--session-dir"
404 | "--fork"
405 | "--fork-entry"
406 | "--fork-position"
407 | "--provider"
408 | "--model"
409 | "--resource-config"
410 | "--resource-transition"
411 | "--permission-gate"
412 | "--bypass"
413 | "--approve"
414 | "-a"
415 | "--no-approve"
416 | "-na"
417 | "--offline"
418 | "--no-native-durable"
419 | "--no-session"
420 | "--rpc-message-updates"
421 | "--help"
422 | "-h"
423 | "--version"
424 | "-v"
425 ) && flag_key.starts_with('-')
426 {
427 unsupported_host_rpc_flag.get_or_insert_with(|| flag_key.clone());
428 }
429
430 let mut take_value = |result: &mut Args, _flag: &str| -> Option<String> {
431 if let Some(v) = inline.clone() {
432 return Some(v);
433 }
434 if i + 1 < args.len() {
435 let next = &args[i + 1];
436 if !next.starts_with('-') || next == "-" {
437 i += 1;
438 return Some(args[i].clone());
439 }
440 }
441 result.errors.push(format!("{flag_key} requires a value"));
442 None
443 };
444
445 match flag_key.as_str() {
446 "--help" | "-h" => result.help = true,
447 "--version" | "-v" => result.version = true,
448 "--print" | "-p" => {
449 result.print = true;
450 if i + 1 < args.len() {
455 let next = &args[i + 1];
456 if !next.starts_with('@') && !next.starts_with('-') {
457 i += 1;
458 result.messages.push(args[i].clone());
459 }
460 }
461 }
462 "--mode" => {
463 if let Some(v) = take_value(&mut result, "--mode") {
464 result.mode = match v.as_str() {
465 "text" => Mode::Text,
466 "json" => Mode::Json,
467 "rpc" => Mode::Rpc,
468 other => {
469 result.errors.push(format!(
470 "Invalid --mode \"{other}\". Valid: text, json, rpc"
471 ));
472 Mode::Text
473 }
474 };
475 }
476 }
477 "--rpc-message-updates" => {
478 if let Some(value) = take_value(&mut result, "--rpc-message-updates") {
479 match value.as_str() {
480 "snapshot" => result.rpc_message_updates = RpcMessageUpdates::Snapshot,
481 "compact-deltas" => result.rpc_message_updates = RpcMessageUpdates::CompactDeltas,
482 other => result.errors.push(format!(
483 "Invalid --rpc-message-updates \"{other}\". Valid: snapshot, compact-deltas"
484 )),
485 }
486 }
487 }
488 "--tui-mode" => {
489 if let Some(v) = take_value(&mut result, "--tui-mode") {
490 host_tui_arg_count += if inline.is_some() { 1 } else { 2 };
491 result.tui_mode = match v.to_ascii_lowercase().as_str() {
492 "regular" => TuiMode::Regular,
493 "fullscreen" => TuiMode::Fullscreen,
494 other => {
495 result.errors.push(format!(
496 "Invalid --tui-mode \"{other}\". Valid: regular, fullscreen"
497 ));
498 TuiMode::Fullscreen
499 }
500 };
501 }
502 }
503 "--tui-footer" => {
504 if let Some(value) = take_value(&mut result, "--tui-footer") {
505 host_tui_arg_count += if inline.is_some() { 1 } else { 2 };
506 match value.as_str() {
507 "full" => result.tui_footer = TuiFooter::Full,
508 "context" => result.tui_footer = TuiFooter::Context,
509 "hidden" => result.tui_footer = TuiFooter::Hidden,
510 "auto" => result.tui_footer = TuiFooter::Auto,
511 other => result.errors.push(format!(
512 "Invalid --tui-footer \"{other}\". Valid: full, context, hidden, auto"
513 )),
514 }
515 }
516 }
517 "--continue" | "-c" => result.continue_session = true,
518 "--resume" | "-r" => result.resume = true,
519 "--host" => {
520 if result.host.is_some() {
521 result
522 .errors
523 .push("--host may only be supplied once".into());
524 }
525 let area = if let Some(area) = inline {
526 if area.is_empty() {
527 result.errors.push("--host= requires an area name".into());
528 }
529 area
530 } else if let Some(next) = args.get(i + 1).filter(|next| {
531 !next.starts_with('-') && !next.starts_with('@') && !next.is_empty()
532 }) {
533 i += 1;
534 host_arg_count += 1;
535 next.clone()
536 } else {
537 String::new()
538 };
539 host_arg_count += 1;
540 result.host = Some(area);
541 }
542 "--mini" => {
543 result.mini = true;
544 if inline.is_some() {
545 result.errors.push("--mini does not take a value".into());
546 }
547 }
548 "--no-session" => result.no_session = true,
549 "--no-tools" | "-nt" => result.no_tools = true,
550 "--no-builtin-tools" | "-nbt" => result.no_builtin_tools = true,
551 "--native-durable" => result.native_durable = true,
554 "--no-native-durable" => result.native_durable = false,
555 "--experimental-durable-epoch" => {
556 if result.experimental_durable_epoch.is_some() {
557 result
558 .errors
559 .push("--experimental-durable-epoch may only be supplied once".into());
560 }
561 if let Some(epoch) = take_value(&mut result, "--experimental-durable-epoch") {
562 result.experimental_durable_epoch = Some(epoch);
563 }
564 }
565 "--no-skills" | "-ns" => result.no_skills = true,
566 "--no-prompt-templates" | "-np" => result.no_prompt_templates = true,
567 "--no-context-files" | "-nc" => result.no_context_files = true,
568 "--no-extensions" | "-ne" => result.no_extensions = true,
569 "--local-only" => result.dev_local_only = true,
570 "--package-only" | "--project-only" => result.project_only = true,
571 "--extensions-dir" | "-ed" => {
572 if let Some(v) = take_value(&mut result, &flag_key) {
573 result.extensions_dir.push(PathBuf::from(v));
574 }
575 }
576 "--verbose" => result.verbose = true,
577 "--debug-system-prompt" => result.debug_system_prompt = true,
578 "--provider" => result.provider = take_value(&mut result, "--provider"),
579 "--model" => result.model = take_value(&mut result, "--model"),
580 "--api-key" => result.api_key = take_value(&mut result, "--api-key"),
581 "--base-url" => result.base_url = take_value(&mut result, "--base-url"),
582 "--timeout" => {
583 if let Some(v) = take_value(&mut result, "--timeout") {
584 match v.parse::<u64>() {
585 Ok(seconds) if seconds > 0 => {
586 result.timeout = Some(Duration::from_secs(seconds));
587 }
588 _ => result.errors.push(format!(
589 "Invalid --timeout \"{v}\". Expected a positive integer number of seconds"
590 )),
591 }
592 }
593 }
594 "--stream-idle-timeout" => {
595 if let Some(v) = take_value(&mut result, "--stream-idle-timeout") {
596 match v.parse::<u64>() {
597 Ok(seconds) => result.stream_idle_timeout = Some(Duration::from_secs(seconds)),
598 Err(_) => result.errors.push(format!(
599 "Invalid --stream-idle-timeout \"{v}\". Expected a non-negative integer number of seconds (0 disables it)"
600 )),
601 }
602 }
603 }
604 "--resource-config" => {
605 result.resource_config =
606 take_value(&mut result, "--resource-config").map(PathBuf::from)
607 }
608 "--resource-transition" => {
609 result.resource_transition =
610 take_value(&mut result, "--resource-transition").map(PathBuf::from)
611 }
612 "--system-prompt" => result.system_prompt = take_value(&mut result, "--system-prompt"),
613 "--append-system-prompt" => {
614 if let Some(v) = take_value(&mut result, "--append-system-prompt") {
615 result.append_system_prompt.push(v);
616 }
617 }
618 "--name" | "-n" => result.name = take_value(&mut result, "--name"),
619 "--session" => result.session = take_value(&mut result, "--session"),
620 "--session-id" => result.session_id = take_value(&mut result, "--session-id"),
621 "--fork" => result.fork = take_value(&mut result, "--fork"),
622 "--fork-entry" => {
623 if let Some(value) = take_value(&mut result, "--fork-entry") {
624 if value.trim().is_empty() {
625 result
626 .errors
627 .push("--fork-entry requires a nonempty entry ID".into());
628 } else if result.fork_entry.replace(value).is_some() {
629 result.errors.push("duplicate --fork-entry".into());
630 }
631 }
632 }
633 "--fork-position" => {
634 if let Some(value) = take_value(&mut result, "--fork-position") {
635 if result.fork_position.is_some() {
638 result.errors.push("duplicate --fork-position".into());
639 } else if value.eq_ignore_ascii_case("at") {
640 result.fork_position = Some(rpi_harness::session::types::ForkPosition::At);
641 } else if value.eq_ignore_ascii_case("before") {
642 result.fork_position =
643 Some(rpi_harness::session::types::ForkPosition::Before);
644 } else {
645 result.errors.push(format!(
646 "Invalid --fork-position \"{value}\". Expected at or before"
647 ));
648 }
649 }
650 }
651 "--models" => {
652 if let Some(v) = take_value(&mut result, &flag_key) {
653 result.models = Some(split_csv(&v));
654 }
655 }
656 "--extension" | "-e" => {
657 if let Some(v) = take_value(&mut result, &flag_key) {
658 result.extension.push(PathBuf::from(v));
659 }
660 }
661 "--skill" => {
662 if let Some(v) = take_value(&mut result, &flag_key) {
663 result.skill.push(PathBuf::from(v));
664 }
665 }
666 "--prompt-template" => {
667 if let Some(v) = take_value(&mut result, &flag_key) {
668 result.prompt_template.push(PathBuf::from(v));
669 }
670 }
671 "--session-dir" => {
672 if let Some(v) = take_value(&mut result, "--session-dir") {
673 result.session_dir = Some(PathBuf::from(v));
674 }
675 }
676 "--thinking" => {
677 if let Some(v) = take_value(&mut result, "--thinking") {
678 match parse_thinking_level(&v) {
679 Some(lvl) => result.thinking = Some(lvl),
680 None => result.ignored.push(format!(
681 "Invalid --thinking \"{v}\". Valid: {}",
682 VALID_THINKING_LEVELS.join(", ")
683 )),
684 }
685 }
686 }
687 "--tools" | "-t" => {
688 if let Some(v) = take_value(&mut result, &flag_key) {
689 result.tools = Some(split_csv(&v));
690 }
691 }
692 "--exclude-tools" | "-xt" => {
693 if let Some(v) = take_value(&mut result, &flag_key) {
694 result.exclude_tools = Some(split_csv(&v));
695 }
696 }
697 "--list-models" => {
698 let mut search = inline.clone().unwrap_or_default();
701 if inline.is_none()
702 && i + 1 < args.len()
703 && !args[i + 1].starts_with('-')
704 && !args[i + 1].starts_with('@')
705 {
706 i += 1;
707 search = args[i].clone();
708 }
709 result.list_models = Some(search);
710 }
711 "--offline" => result.offline = true,
712 "--export" => {
713 if let Some(value) = take_value(&mut result, &flag_key) {
714 result.export = Some(PathBuf::from(value));
715 }
716 }
717 "--approve" | "-a" => result.trust_override = Some(true),
718 "--no-approve" | "-na" => result.trust_override = Some(false),
719 other if matches!(other, "--models") => {
730 if inline.is_none()
733 && i + 1 < args.len()
734 && !args[i + 1].starts_with('-')
735 && !args[i + 1].starts_with('@')
736 {
737 i += 1;
738 }
739 result
740 .ignored
741 .push(format!("{other} is not supported in v1 (ignored)"));
742 }
743 "--theme" => {
744 result.theme = take_value(&mut result, "--theme");
745 if result.theme.is_some() {
746 host_tui_arg_count += if inline.is_some() { 1 } else { 2 };
747 }
748 }
749 "--no-themes" => {
750 host_tui_arg_count += 1;
751 result.no_themes = true;
752 }
753 other if other.starts_with("--") => {
758 let name = &flag_key;
759 let value = if let Some(value) = inline {
760 serde_json::Value::String(value)
761 } else if i + 1 < args.len()
762 && !args[i + 1].starts_with('-')
763 && !args[i + 1].starts_with('@')
764 {
765 i += 1;
766 serde_json::Value::String(args[i].clone())
767 } else {
768 serde_json::Value::Bool(true)
769 };
770 result.unknown_flags.insert(name[2..].to_string(), value);
771 }
772 other if other.starts_with('-') && other.len() > 1 => {
774 result.errors.push(format!("Unknown option: {other}"));
775 }
776 other => {
777 if let Some(path) = file_arg(other) {
778 result.file_args.push(path);
779 } else {
780 result.messages.push(other.to_string());
781 }
782 }
783 }
784 i += 1;
785 }
786
787 let fork_errors = result.fork_cut_errors();
788 result
789 .errors
790 .extend(fork_errors.into_iter().map(str::to_owned));
791
792 if result.host.is_some()
793 && !result.mini
794 && result.mode != Mode::Rpc
795 && args.len() != host_arg_count + host_tui_arg_count
796 {
797 result.errors.push(
798 "Host TUI accepts --tui-mode, --tui-footer, --theme and --no-themes; prompt options require --mini"
799 .into(),
800 );
801 }
802
803 if result.host.is_some() && !result.mini && result.mode == Mode::Rpc {
804 if let Some(flag) = unsupported_host_rpc_flag {
805 result
806 .errors
807 .push(format!("{flag} is not supported by Host RPC"));
808 }
809 }
810
811 if result.mini {
812 result.no_session = true;
813 result.native_durable = false;
814 for (present, flag) in [
815 (result.continue_session, "--continue"),
816 (result.resume, "--resume"),
817 (result.session.is_some(), "--session"),
818 (result.session_id.is_some(), "--session-id"),
819 (result.session_dir.is_some(), "--session-dir"),
820 (result.fork.is_some(), "--fork"),
821 (result.export.is_some(), "--export"),
822 ] {
823 if present {
824 result
825 .errors
826 .push(format!("--mini cannot be combined with {flag}"));
827 }
828 }
829 }
830 if result.host.is_some() && result.mini {
831 for (present, flag) in [
832 (result.name.is_some(), "--name"),
833 (result.mode != Mode::Text, "--mode json/rpc"),
834 (result.list_models.is_some(), "--list-models"),
835 (result.models.is_some(), "--models"),
836 (result.resource_config.is_some(), "--resource-config"),
837 (
838 result.resource_transition.is_some(),
839 "--resource-transition",
840 ),
841 (!result.extension.is_empty(), "--extension"),
842 (!result.extensions_dir.is_empty(), "--extensions-dir"),
843 (!result.skill.is_empty(), "--skill"),
844 (!result.prompt_template.is_empty(), "--prompt-template"),
845 (result.theme.is_some(), "--theme"),
846 ] {
847 if present {
848 result
849 .errors
850 .push(format!("--mini cannot be combined with {flag}"));
851 }
852 }
853 for flag in result.unknown_flags.keys() {
854 result
855 .errors
856 .push(format!("--mini does not support --{flag}"));
857 }
858 }
859 if !package && result.resource_config.is_none() && result.resource_transition.is_none() {
860 env_extension_dirs.append(&mut result.extensions_dir);
862 result.extensions_dir = env_extension_dirs;
863 }
864 if let Err(error) = crate::native_durable::experimental_epoch::policy(&result) {
868 result.errors.push(error);
869 }
870 result
871}
872
873fn split_csv(v: &str) -> Vec<String> {
875 v.split(',')
876 .map(|s| s.trim().to_string())
877 .filter(|s| !s.is_empty())
878 .collect()
879}
880
881pub fn resolve_mode(parsed: &Args, stdin_is_tty: bool, stdout_is_tty: bool) -> RunMode {
886 if parsed.unknown_flags.contains_key("server") {
888 return RunMode::Rpc;
889 }
890 if parsed.mode == Mode::Rpc {
891 return RunMode::Rpc;
892 }
893 if parsed.mode == Mode::Json {
894 return RunMode::Json;
895 }
896 if parsed.print || !stdin_is_tty || !stdout_is_tty {
897 RunMode::Print
898 } else {
899 RunMode::Interactive
900 }
901}
902
903#[derive(Debug, Clone, Copy, PartialEq, Eq)]
908pub enum RunMode {
909 Interactive,
910 Print,
911 Json,
912 Rpc,
913}
914
915pub fn print_help() {
917 let builtin = "read, bash, edit, write, docs";
918 println!(
919 "{name} - AI coding assistant with read, bash, edit, write, docs tools
920
921{u}Usage:{r}
922 {name} [options] [@files...] [messages...]
923
924{u}Options:{r}
925 --provider <name> Provider name (built-in, installed package, or models.json id)
926 --model <pattern> Model pattern or ID (supports \"provider/id\" and optional \":<thinking>\")
927 --api-key <key> API key override for the selected provider
928 --base-url <url> Override the selected model endpoint
929 --timeout <seconds> LLM API request timeout (default: 600)
930 --stream-idle-timeout <seconds> Max silence between response bytes (default: 300; 0 disables)
931 --resource-capabilities Pure bounded JSON resource protocol profile (use alone; no startup)
932 --resource-session-read <file> Strict bounded nonexecuting saved-session read (standalone)
933 --resource-transition <file> Explicit same-session resource CAS (RPC only; see docs/resource-transition-rpc.md)
934 --resource-config <file> Exact versioned startup resources (RPC only; see docs/resource-selection-rpc.md)
935 --system-prompt <text> Replace the default system prompt
936 --append-system-prompt <text> Append text to the system prompt (repeatable)
937 --thinking <level> off, minimal, low, medium, high, xhigh, max
938 --mode <mode> Output mode: text (default), json, or rpc
939 --rpc-message-updates <mode> RPC updates: compact-deltas (default) or snapshot (legacy)
940 --host [area] Run in a shared local Host area (Unix), in TUI, RPC, or --mini mode
941 --host[=area] --mini [prompt] Run a one-shot text prompt in that Host
942 --server [--port <n>] [--bind <ip>]
943 Headless server: serve a remote-connectable agent (no TUI)
944 --native-host [area] Join or start a persistent Host area (macOS)
945 --connect <host:port> Remote client: connect to a `--server` instance and run the TUI
946 (no local provider/tools/session; all agent work is remote)
947 --token <token> Auth token for `--connect` (printed by `--server`; may also
948 be provided via the RPI_SERVER_TOKEN env var)
949 --tui-mode <mode> TUI buffer: regular or fullscreen (macOS default: regular)
950 --tui-footer <mode> Native TUI footer: full (default), context, hidden, or auto
951 --list-models [search] List available models (with optional fuzzy search)
952 --offline Disable startup network operations (same as RPI_OFFLINE=1)
953 --export <file> Export a JSONL session to HTML and exit
954 --approve, -a Force-enable current-project resources
955 --no-approve, -na Disable current-project resources
956 --print, -p Non-interactive: process prompt(s) and exit
957 --mini Use an in-memory session and disable native durable execution
958 --continue, -c Continue the most recent session
959 --resume, -r Browse and select a session to resume
960 --session <id|path> Resume by session file path under --session-dir
961 or by an unambiguous ID prefix or file name fragment
962 --session-id <id> Use the exact session id, creating it if missing
963 --fork <id|path> Fork a session into a new one and start in the fork
964 (unambiguous ID prefix, file name fragment, or any session file path)
965 --fork-entry <entryId> With --fork: cut the new branch at this message
966 entry. The entry id must match exactly
967 --fork-position <at|before> With --fork-entry: keep the selected message in the
968 new branch (at) or drop it (before). Default: before
969 --session-dir <dir> Directory for session storage
970{session_preview} --no-session Ephemeral mode (do not persist the session)
971 --name, -n <name> Set the session display name
972 --tools, -t <list> Comma-separated allowlist of tool names to enable
973 --exclude-tools, -xt <list> Comma-separated denylist of tool names to disable
974 --no-tools, -nt Disable all tools
975 --no-builtin-tools, -nbt Disable the built-in tools (read, bash, edit, write, docs)
976 --no-native-durable Temporary escape hatch: use legacy session behavior
977 --experimental-durable-epoch <id>
978 With native durable enabled: bounded v2 ledger, explicit same epoch on reopen; no migration
979 --no-skills, -ns Skip skill discovery (no <available_skills> block)
980 --no-prompt-templates, -np Skip prompt-template discovery (/expand templates)
981 --no-context-files, -nc Skip AGENTS.md/CLAUDE.md discovery (no <project_context>)
982 --no-extensions, -ne Skip Rust cdylib extension loading
983 --extensions-dir, -ed <dir> Extra dir to scan for plugins (.dll/.so/.dylib); repeatable
984 (also via RPI_EXTENSIONS_DIR env: ';' on Windows, ':' on Unix)
985 --local-only Skip automatic extension discovery: load only
986 --extensions-dir / --extension paths (no project
987 .rpi/extensions, no global extensions)
988 --package-only, --project-only Load project skills/prompts/extensions/packages
989 from the active project; exclude global resources
990 --debug-system-prompt Print the resolved system-prompt sections to stderr (verification)
991 --verbose Show startup warnings (e.g. ignored flags)
992 --help, -h Show this help
993 --version, -v Show version
994
995{u}Subcommands:{r}
996 host <command> Shared Host control: foreground serve; status/list/
997 inspect; submit/receipt; optional profiles and
998 administrative-* (Unix; authenticated IPC;
999 see `rpi host --help`)
1000 update Update the rpi CLI from GitHub releases
1001 (Homebrew installs use `brew upgrade rpi`)
1002 updates check --json Report cached host/extension update state as JSON
1003 updates refresh --json Check registries, then report update state as JSON
1004 auth login|check|logout Manage persisted credentials in ~/.rpi/auth.json
1005 (see `rpi auth --help`)
1006 events path|tail Inspect the extension event journal (needs
1007 RPI_EVENT_LOG=1; see `rpi events --help`)
1008 install <name> Install a published Agent package or Rust extension
1009 (see `rpi install --help`)
1010 uninstall <crate> Remove an installed Rust cdylib extension
1011 extension update [name] Update project and global installed Rust extensions
1012 (see `rpi extension update --help`)
1013 extension <command> Manage local extension snapshots (see `rpi extension --help`)
1014 skill|skills <command> Manage local skill snapshots (see `rpi skill --help`)
1015 run package NAME [options] Start an installed agent package (JSONL RPC)
1016 package <command> Manage published agent packages, local snapshots, and project links
1017 (see `rpi package --help`)
1018 dev [options] Build, watch, and hot-reload a Rust extension
1019 (see `rpi dev --help`)
1020 dev-local [options] Debug only the current Rust extension
1021 (shortcut for `rpi dev --local-only`)
1022
1023{u}Built-in Tools:{r}
1024 {builtin} (enabled by default)
1025
1026{u}Examples:{r}
1027 # Interactive with an initial prompt
1028 {name} \"List all .rs files in src/\"
1029
1030 # Single-shot print mode
1031 {name} -p \"Summarize this project\"
1032
1033 # Include a file in the initial message
1034 {name} @README.md \"What does this project do?\"
1035
1036 # Continue the previous session
1037 {name} -c \"What did we discuss?\"
1038
1039 # Use a specific model + thinking level
1040 {name} --model claude-sonnet-5 --thinking high \"Refactor this\"
1041
1042 # JSON event stream (one JSON object per line on stdout)
1043 {name} --mode json -p \"Inspect the code\"
1044
1045 # Read-only: no file-modifying tools
1046 {name} --tools read,bash -p \"Review the code in src/\"
1047
1048{u}Environment:{r}
1049 ANTHROPIC_API_KEY Anthropic API key (x-api-key) — fallback when no stored credential
1050 ANTHROPIC_AUTH_TOKEN Bearer token (Authorization: Bearer) for third-party gateways
1051 ANTHROPIC_BASE_URL Override the Anthropic endpoint (e.g. a compatible proxy)
1052 OPENAI_API_KEY Bearer token for openai-completions/responses
1053 RPI_OFFLINE Disable startup network operations when set to 1/true/yes
1054 RPI_CODING_AGENT_DIR Override the ~/.rpi agent home (auth/models/settings/trust)
1055 RPI_SESSION_ID Session id served by a plugin (set by the host; also honored as an override)
1056
1057{u}Notes:{r}
1058 Supported HTTP protocols are Anthropic Messages and OpenAI Chat Completions.
1059 Define custom model catalogs and provider apiKey values in
1060 ~/.rpi/agent/models.json. The interactive TUI, Rust extensions, skills,
1061 prompt templates, themes, model cycling, session fork/export, and trust
1062 commands are available in the current build. OAuth, RPC, and full model
1063 cycling remain outside the current implementation.
1064",
1065 name = crate::APP_NAME,
1066 builtin = builtin,
1067 session_preview = if cfg!(unix) {
1068 " --session-preview <uuid> Read the recent saved transcript (standalone with --session-dir)\n"
1069 } else {
1070 ""
1071 },
1072 u = "\x1b[1m",
1073 r = "\x1b[0m",
1074 );
1075}
1076
1077pub fn print_version() {
1079 println!("{} {}", crate::APP_NAME, crate::VERSION);
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084 #[test]
1085 fn rpc_message_updates_selection_and_errors() {
1086 assert_eq!(
1087 super::Args::default().rpc_message_updates,
1088 super::RpcMessageUpdates::CompactDeltas
1089 );
1090 for (value, expected) in [
1091 ("snapshot", super::RpcMessageUpdates::Snapshot),
1092 ("compact-deltas", super::RpcMessageUpdates::CompactDeltas),
1093 ] {
1094 for args in [
1095 vec![
1096 "--mode".into(),
1097 "rpc".into(),
1098 format!("--rpc-message-updates={value}"),
1099 ],
1100 vec!["--rpc-message-updates".into(), value.into()],
1101 ] {
1102 let parsed = super::parse_args(&args);
1103 assert!(parsed.errors.is_empty(), "{:?}", parsed.errors);
1104 assert_eq!(parsed.rpc_message_updates, expected);
1105 assert!(parsed.unknown_flags.is_empty());
1106 }
1107 }
1108 for args in [
1109 vec!["--rpc-message-updates".into()],
1110 vec!["--rpc-message-updates".into(), "--mode=json".into()],
1111 vec!["--rpc-message-updates=".into()],
1112 vec!["--rpc-message-updates=invalid".into()],
1113 vec!["--rpc-message-updates".into(), "invalid".into()],
1114 ] {
1115 let parsed = super::parse_args(&args);
1116 assert_eq!(parsed.errors.len(), 1);
1117 assert!(parsed.errors[0].contains("--rpc-message-updates"));
1118 }
1119 let parsed = super::parse_args(&[
1120 "--mode=json".into(),
1121 "--rpc-message-updates=snapshot".into(),
1122 ]);
1123 assert_eq!(parsed.mode, super::Mode::Json);
1124 }
1125
1126 use super::*;
1127
1128 struct RestoreOfflineEnv(Option<std::ffi::OsString>);
1129
1130 impl Drop for RestoreOfflineEnv {
1131 fn drop(&mut self) {
1132 match self.0.take() {
1133 Some(value) => std::env::set_var(RPI_OFFLINE_ENV, value),
1134 None => std::env::remove_var(RPI_OFFLINE_ENV),
1135 }
1136 }
1137 }
1138
1139 fn s(args: &[&str]) -> Vec<String> {
1140 args.iter().map(|a| a.to_string()).collect()
1141 }
1142
1143 #[test]
1144 fn parses_basic_prompt() {
1145 let a = parse_args(&s(&["hello", "world"]));
1146 assert_eq!(a.messages, vec!["hello".to_string(), "world".to_string()]);
1147 assert!(!a.help);
1148 }
1149
1150 #[test]
1151 fn parses_help_and_version() {
1152 let a = parse_args(&s(&["--help"]));
1153 assert!(a.help);
1154 let a = parse_args(&s(&["-v"]));
1155 assert!(a.version);
1156 }
1157
1158 #[test]
1159 fn print_consumes_following_positional() {
1160 let a = parse_args(&s(&["-p", "summarize"]));
1161 assert!(a.print);
1162 assert_eq!(a.messages, vec!["summarize".to_string()]);
1163 }
1164
1165 #[test]
1166 fn print_does_not_consume_file_or_flag() {
1167 let a = parse_args(&s(&["-p", "@file.md"]));
1168 assert!(a.print);
1169 assert!(a.messages.is_empty());
1170 assert_eq!(a.file_args, vec![PathBuf::from("file.md")]);
1171 }
1172
1173 #[test]
1174 fn model_and_thinking() {
1175 let a = parse_args(&s(&["--model", "claude-sonnet-5", "--thinking", "high"]));
1176 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1177 assert_eq!(a.thinking, Some(ThinkingLevel::High));
1178 }
1179
1180 #[test]
1181 fn model_with_thinking_shorthand() {
1182 let a = parse_args(&s(&["--model", "claude-sonnet-5:high"]));
1183 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5:high"));
1185 }
1186
1187 #[test]
1188 fn tools_split_csv() {
1189 let a = parse_args(&s(&["--tools", "read, bash ,write"]));
1190 assert_eq!(
1191 a.tools.as_deref(),
1192 Some(&["read".to_string(), "bash".to_string(), "write".to_string()][..])
1193 );
1194 }
1195
1196 #[test]
1197 fn native_durable_is_enabled_by_default_with_a_transition_escape_hatch() {
1198 assert!(parse_args(&s(&[])).native_durable);
1199 assert!(parse_args(&s(&["--native-durable"])).native_durable);
1200 assert!(!parse_args(&s(&["--no-native-durable"])).native_durable);
1201 assert!(parse_args(&s(&["--no-native-durable", "--native-durable"])).native_durable);
1202 assert!(!parse_args(&s(&["--native-durable", "--no-native-durable"])).native_durable);
1203 }
1204
1205 #[test]
1206 fn mini_always_disables_session_and_durable() {
1207 for argv in [
1208 ["--mini", "--native-durable", "hello"],
1209 ["--native-durable", "--mini", "hello"],
1210 ] {
1211 let args = parse_args(&s(&argv));
1212 assert!(args.mini && args.no_session && !args.native_durable);
1213 assert!(args.errors.is_empty(), "{:?}", args.errors);
1214 assert_eq!(args.messages, ["hello"]);
1215 assert_eq!(resolve_mode(&args, true, true), RunMode::Interactive);
1216 }
1217 }
1218
1219 #[test]
1220 fn mini_accepts_regular_modes_and_resource_flags() {
1221 let args = parse_args(&s(&[
1222 "--mini",
1223 "--mode",
1224 "rpc",
1225 "--tools",
1226 "read",
1227 "--extension",
1228 "extension.dylib",
1229 ]));
1230 assert!(args.errors.is_empty(), "{:?}", args.errors);
1231 assert_eq!(resolve_mode(&args, true, true), RunMode::Rpc);
1232 assert_eq!(args.tools.unwrap(), ["read"]);
1233 assert_eq!(args.extension, [PathBuf::from("extension.dylib")]);
1234 }
1235
1236 #[test]
1237 fn mini_rejects_session_and_durable_epoch_flags() {
1238 for (flags, expected) in [
1239 (&["--resume"][..], "--resume"),
1240 (&["--session-id", "saved"][..], "--session-id"),
1241 (&["--export", "session.jsonl"][..], "--export"),
1242 (
1243 &["--experimental-durable-epoch", "epoch"][..],
1244 "--experimental-durable-epoch",
1245 ),
1246 ] {
1247 let argv = ["--mini"]
1248 .into_iter()
1249 .chain(flags.iter().copied())
1250 .collect::<Vec<_>>();
1251 let args = parse_args(&s(&argv));
1252 assert!(
1253 args.errors.iter().any(|error| error.contains(expected)),
1254 "{:?}",
1255 args.errors
1256 );
1257 }
1258 }
1259
1260 #[test]
1261 fn unknown_short_flag_errors() {
1262 let a = parse_args(&s(&["-Z"]));
1263 assert!(!a.errors.is_empty());
1264 }
1265
1266 #[test]
1267 fn unknown_long_flag_is_retained_for_extensions() {
1268 let a = parse_args(&s(&["--frobnicate", "value"]));
1269 assert!(a.errors.is_empty());
1270 assert_eq!(
1271 a.unknown_flags.get("frobnicate"),
1272 Some(&serde_json::Value::String("value".into()))
1273 );
1274 assert!(a.ignored.is_empty());
1275 }
1276
1277 #[test]
1278 fn unknown_long_boolean_flag_is_retained() {
1279 let a = parse_args(&s(&["--server"]));
1280 assert_eq!(
1281 a.unknown_flags.get("server"),
1282 Some(&serde_json::Value::Bool(true))
1283 );
1284 }
1285
1286 #[test]
1287 fn unknown_long_flags_keep_string_and_equals_values() {
1288 let a = parse_args(&s(&["--port", "8080", "--bind=127.0.0.1"]));
1289 assert_eq!(
1290 a.unknown_flags.get("port"),
1291 Some(&serde_json::Value::String("8080".into()))
1292 );
1293 assert_eq!(
1294 a.unknown_flags.get("bind"),
1295 Some(&serde_json::Value::String("127.0.0.1".into()))
1296 );
1297 }
1298
1299 #[test]
1300 fn models_flag_parses_csv() {
1301 let a = parse_args(&s(&["--models", "a,b,c"]));
1302 assert!(a.errors.is_empty());
1303 assert!(a.ignored.is_empty(), "--models is implemented");
1304 assert_eq!(
1305 a.models.as_deref(),
1306 Some(&["a".to_string(), "b".to_string(), "c".to_string()][..])
1307 );
1308 assert!(a.messages.is_empty());
1310 }
1311
1312 #[test]
1313 fn list_models_accepts_bare_and_search_forms() {
1314 let bare = parse_args(&s(&["--list-models"]));
1315 assert_eq!(bare.list_models.as_deref(), Some(""));
1316 assert!(bare.ignored.is_empty());
1317 assert!(bare.messages.is_empty());
1318
1319 let search = parse_args(&s(&["--list-models", "claude"]));
1320 assert_eq!(search.list_models.as_deref(), Some("claude"));
1321 assert!(search.messages.is_empty());
1322
1323 let inline = parse_args(&s(&["--list-models=gpt"]));
1324 assert_eq!(inline.list_models.as_deref(), Some("gpt"));
1325 }
1326
1327 #[test]
1328 fn offline_flag_is_honored_without_warning() {
1329 let args = parse_args(&s(&["--offline"]));
1330 assert!(args.offline);
1331 assert!(args.ignored.is_empty());
1332 }
1333
1334 #[test]
1335 fn timeout_parses_seconds_in_separate_and_equals_forms() {
1336 let separate = parse_args(&s(&["--timeout", "45"]));
1337 assert!(separate.errors.is_empty());
1338 assert_eq!(separate.timeout, Some(Duration::from_secs(45)));
1339
1340 let inline = parse_args(&s(&["--timeout=90"]));
1341 assert!(inline.errors.is_empty());
1342 assert_eq!(inline.timeout, Some(Duration::from_secs(90)));
1343 }
1344
1345 #[test]
1346 fn timeout_rejects_zero_and_invalid_values() {
1347 for value in ["0", "1.5", "forever", "18446744073709551616"] {
1348 let args = parse_args(&s(&[&format!("--timeout={value}")]));
1349 assert_eq!(args.errors.len(), 1, "value: {value}");
1350 assert!(args.timeout.is_none(), "value: {value}");
1351 }
1352 }
1353
1354 #[test]
1355 fn stream_idle_timeout_accepts_both_forms_and_zero_but_rejects_invalid_values() {
1356 for (argv, seconds) in [
1357 (s(&["--stream-idle-timeout", "45"]), 45),
1358 (s(&["--stream-idle-timeout=90"]), 90),
1359 (s(&["--stream-idle-timeout=0"]), 0),
1360 ] {
1361 let args = parse_args(&argv);
1362 assert!(args.errors.is_empty(), "{:?}", args.errors);
1363 assert_eq!(args.stream_idle_timeout, Some(Duration::from_secs(seconds)));
1364 assert!(args.timeout.is_none());
1365 }
1366 for value in ["-1", "1.5", "no", "18446744073709551616"] {
1367 let args = parse_args(&s(&[&format!("--stream-idle-timeout={value}")]));
1368 assert!(!args.errors.is_empty(), "{value}");
1369 assert!(args.stream_idle_timeout.is_none());
1370 }
1371 assert!(!parse_args(&s(&["--stream-idle-timeout"])).errors.is_empty());
1372 }
1373
1374 #[test]
1375 fn native_pi_offline_truthy_values_are_case_insensitive() {
1376 for value in [
1377 Some("1"),
1378 Some("true"),
1379 Some("TRUE"),
1380 Some("Yes"),
1381 Some("yEs"),
1382 ] {
1383 assert!(is_truthy_env_flag(value), "value={value:?}");
1384 }
1385 for value in [
1386 None,
1387 Some(""),
1388 Some("0"),
1389 Some("false"),
1390 Some("no"),
1391 Some(" true "),
1392 ] {
1393 assert!(!is_truthy_env_flag(value), "value={value:?}");
1394 }
1395 }
1396
1397 #[test]
1398 fn pi_offline_env_and_cli_flag_share_one_normalized_gate() {
1399 let _guard = crate::config::test_support::env_lock().lock().unwrap();
1400 let _restore = RestoreOfflineEnv(std::env::var_os(RPI_OFFLINE_ENV));
1401
1402 std::env::set_var(RPI_OFFLINE_ENV, "YeS");
1403 assert!(parse_args(&[]).offline);
1404 assert!(normalize_offline_mode(&[]));
1405 assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
1406
1407 std::env::set_var(RPI_OFFLINE_ENV, "0");
1408 assert!(!parse_args(&[]).offline);
1409 let argv = s(&["--offline"]);
1410 assert!(normalize_offline_mode(&argv));
1411 assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
1412 }
1413
1414 #[test]
1415 fn project_trust_flags_are_honored_without_warning() {
1416 let approved = parse_args(&s(&["--approve"]));
1417 assert_eq!(approved.trust_override, Some(true));
1418 assert!(approved.ignored.is_empty());
1419 let denied = parse_args(&s(&["--no-approve"]));
1420 assert_eq!(denied.trust_override, Some(false));
1421 assert!(denied.ignored.is_empty());
1422 }
1423
1424 #[test]
1425 fn export_flag_captures_input_and_output_position() {
1426 let args = parse_args(&s(&["--export", "session.jsonl", "transcript.html"]));
1427 assert_eq!(args.export, Some(PathBuf::from("session.jsonl")));
1428 assert_eq!(args.messages, vec!["transcript.html".to_string()]);
1429 assert!(args.ignored.is_empty());
1430 }
1431
1432 #[test]
1433 fn session_id_and_fork_flags_parse() {
1434 let a = parse_args(&s(&["--session-id", "01abc", "--fork", "xyz"]));
1435 assert!(a.errors.is_empty());
1436 assert_eq!(a.session_id.as_deref(), Some("01abc"));
1437 assert_eq!(a.fork.as_deref(), Some("xyz"));
1438 assert_eq!(a.fork_entry, None);
1439 assert_eq!(
1440 a.fork_position, None,
1441 "an explicit entry must keep the harness default (before), not force a position"
1442 );
1443 let a = parse_args(&s(&[
1444 "--fork",
1445 "xyz",
1446 "--fork-entry",
1447 "message-2",
1448 "--fork-position",
1449 "before",
1450 ]));
1451 assert!(a.errors.is_empty());
1452 assert_eq!(a.fork_entry.as_deref(), Some("message-2"));
1453 assert_eq!(
1454 a.fork_position,
1455 Some(rpi_harness::session::types::ForkPosition::Before)
1456 );
1457 let a = parse_args(&s(&["--fork-position", "middle"]));
1458 assert_eq!(a.fork_position, None);
1459 assert_eq!(
1460 a.errors,
1461 vec!["Invalid --fork-position \"middle\". Expected at or before".to_string()]
1462 );
1463 let a = parse_args(&s(&[
1464 "-e",
1465 "plugin.dll",
1466 "--skill",
1467 "s",
1468 "--prompt-template",
1469 "t.md",
1470 ]));
1471 assert_eq!(a.extension.len(), 1);
1472 assert_eq!(a.skill.len(), 1);
1473 assert_eq!(a.prompt_template.len(), 1);
1474 }
1475
1476 #[test]
1477 fn fork_cut_flags_are_reserved_and_require_an_active_fork() {
1478 let args = parse_args(&s(&[
1479 "--fork-entry=entry-1",
1480 "--fork",
1481 "source",
1482 "--fork-position",
1483 "at",
1484 "--extension-option=keep",
1485 ]));
1486 assert!(args.errors.is_empty(), "{:?}", args.errors);
1487 assert_eq!(
1488 args.unknown_flags,
1489 BTreeMap::from([("extension-option".into(), serde_json::json!("keep"))])
1490 );
1491 for argv in [
1492 &["--fork-entry", "entry-1"][..],
1493 &["--fork", "source", "--fork-position", "at"],
1494 &[
1495 "--fork",
1496 "source",
1497 "--fork-entry",
1498 "entry-1",
1499 "--no-session",
1500 ],
1501 &["--fork", "source", "--fork-entry", "entry-1", "--resume"],
1502 &[
1503 "--fork",
1504 "source",
1505 "--fork-entry",
1506 "entry-1",
1507 "--fork-position=after",
1508 ],
1509 &[
1510 "--fork",
1511 "source",
1512 "--fork-entry=entry-1",
1513 "--fork-entry=entry-2",
1514 ],
1515 &["--fork", "source", "--fork-entry="],
1516 ] {
1517 assert!(!parse_args(&s(argv)).errors.is_empty(), "{argv:?}");
1518 }
1519 }
1520
1521 #[test]
1522 fn fork_position_is_case_insensitive() {
1523 use rpi_harness::session::types::ForkPosition;
1524 for (value, expected) in [
1525 ("at", ForkPosition::At),
1526 ("At", ForkPosition::At),
1527 ("AT", ForkPosition::At),
1528 ("before", ForkPosition::Before),
1529 ("Before", ForkPosition::Before),
1530 ("BEFORE", ForkPosition::Before),
1531 ] {
1532 let a = parse_args(&s(&[
1533 "--fork",
1534 "xyz",
1535 "--fork-entry",
1536 "message-2",
1537 "--fork-position",
1538 value,
1539 ]));
1540 assert!(a.errors.is_empty(), "{value}: {:?}", a.errors);
1541 assert_eq!(a.fork_position, Some(expected), "{value}");
1542 }
1543 }
1544
1545 #[test]
1550 fn fork_cut_flags_require_fork() {
1551 let a = parse_args(&s(&["--fork-entry", "message-2", "--print", "hi"]));
1552 assert_eq!(a.errors, vec!["--fork-entry requires --fork".to_string()]);
1553
1554 let a = parse_args(&s(&["--fork-position", "before"]));
1557 assert_eq!(
1558 a.errors,
1559 vec![
1560 "--fork-position requires --fork".to_string(),
1561 "--fork-position requires --fork-entry".to_string(),
1562 ]
1563 );
1564
1565 let a = parse_args(&s(&["--fork-position=at", "--fork-entry=message-2"]));
1567 assert_eq!(
1568 a.errors,
1569 vec![
1570 "--fork-entry requires --fork".to_string(),
1571 "--fork-position requires --fork".to_string(),
1572 ]
1573 );
1574
1575 let a = parse_args(&s(&[
1577 "--fork",
1578 "xyz",
1579 "--fork-entry",
1580 "message-2",
1581 "--fork-position",
1582 "at",
1583 ]));
1584 assert!(a.errors.is_empty(), "{:?}", a.errors);
1585 }
1586
1587 #[test]
1592 fn fork_position_requires_fork_entry() {
1593 for value in ["at", "before", "AT", "BEFORE"] {
1594 let a = parse_args(&s(&["--fork", "xyz", "--fork-position", value]));
1596 assert_eq!(
1597 a.errors,
1598 vec!["--fork-position requires --fork-entry".to_string()],
1599 "{value}: the flag is not inert"
1600 );
1601 assert!(a.fork_position.is_some(), "{value}");
1602
1603 let flag = format!("--fork-position={value}");
1605 let a = parse_args(&s(&["--fork", "xyz", &flag]));
1606 assert_eq!(
1607 a.errors,
1608 vec!["--fork-position requires --fork-entry".to_string()],
1609 "{flag}: the flag is not inert"
1610 );
1611 }
1612
1613 let a = parse_args(&s(&[
1615 "--fork",
1616 "xyz",
1617 "--fork-entry",
1618 "message-2",
1619 "--fork-position=before",
1620 ]));
1621 assert!(a.errors.is_empty(), "{:?}", a.errors);
1622 assert_eq!(
1623 a.fork_position,
1624 Some(rpi_harness::session::types::ForkPosition::Before)
1625 );
1626 }
1627
1628 #[test]
1629 fn no_skills_flag_honored() {
1630 let a = parse_args(&s(&["-ns"]));
1631 assert!(a.errors.is_empty());
1632 assert!(a.no_skills);
1633 assert!(a.ignored.is_empty());
1635 }
1636
1637 #[test]
1638 fn no_prompt_templates_flag_honored() {
1639 let a = parse_args(&s(&["--no-prompt-templates"]));
1640 assert!(a.no_prompt_templates);
1641 assert!(a.ignored.is_empty());
1642 }
1643
1644 #[test]
1645 fn no_context_files_flag_honored() {
1646 let a = parse_args(&s(&["-nc"]));
1647 assert!(a.no_context_files);
1648 assert!(a.ignored.is_empty());
1649 }
1650
1651 #[test]
1652 fn no_extensions_flag_honored() {
1653 let a = parse_args(&s(&["--no-extensions"]));
1655 assert!(a.no_extensions);
1656 assert!(a.ignored.is_empty());
1657 }
1658
1659 #[test]
1660 fn local_only_flag_is_honored_on_the_regular_parser() {
1661 let a = parse_args(&s(&["--local-only"]));
1664 assert!(a.errors.is_empty());
1665 assert!(a.dev_local_only);
1666 assert!(a.ignored.is_empty());
1667 }
1668
1669 #[test]
1670 fn project_only_aliases_are_honored() {
1671 for flag in ["--package-only", "--project-only"] {
1672 let a = parse_args(&s(&[flag]));
1673 assert!(a.errors.is_empty());
1674 assert!(a.project_only);
1675 assert!(a.ignored.is_empty());
1676 }
1677 }
1678
1679 #[test]
1680 fn extensions_dir_flag_collects_dirs() {
1681 let a = parse_args(&s(&["--extensions-dir", "/a/b", "-ed", "/c/d"]));
1682 assert_eq!(
1683 a.extensions_dir,
1684 vec![PathBuf::from("/a/b"), PathBuf::from("/c/d")]
1685 );
1686 assert!(a.ignored.is_empty());
1687 }
1688
1689 #[test]
1690 fn extensions_dir_inline_equals_form() {
1691 let a = parse_args(&s(&["--extensions-dir=/x/y"]));
1692 assert_eq!(a.extensions_dir, vec![PathBuf::from("/x/y")]);
1693 }
1694
1695 #[test]
1696 fn extensions_dir_env_is_merged() {
1697 let a = parse_args(&s(&["--extensions-dir", "/flag/only"]));
1703 assert!(a
1704 .extensions_dir
1705 .iter()
1706 .any(|p| p == &PathBuf::from("/flag/only")));
1707 }
1708
1709 #[test]
1710 fn file_args_stripped() {
1711 let a = parse_args(&s(&["@a.txt", "@b.md", "hi"]));
1712 assert_eq!(
1713 a.file_args,
1714 vec![PathBuf::from("a.txt"), PathBuf::from("b.md")]
1715 );
1716 assert_eq!(a.messages, vec!["hi".to_string()]);
1717 }
1718
1719 #[test]
1720 fn equals_form_supported() {
1721 let a = parse_args(&s(&["--model=claude-sonnet-5", "--thinking=low"]));
1722 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1723 assert_eq!(a.thinking, Some(ThinkingLevel::Low));
1724 }
1725
1726 #[test]
1727 fn theme_flag_is_honored() {
1728 let a = parse_args(&s(&["--theme", "ocean.json"]));
1729 assert_eq!(a.theme.as_deref(), Some("ocean.json"));
1730 assert!(a.ignored.is_empty());
1731 }
1732
1733 #[test]
1734 fn no_themes_is_honored() {
1735 let a = parse_args(&s(&["--no-themes"]));
1736 assert!(a.no_themes);
1737 assert!(a.ignored.is_empty());
1738 }
1739
1740 #[test]
1741 fn tui_mode_parses_and_validates() {
1742 assert_eq!(
1743 parse_args(&s(&["--tui-mode", "regular"])).tui_mode,
1744 TuiMode::Regular
1745 );
1746 assert_eq!(
1747 parse_args(&s(&["--tui-mode=fullscreen"])).tui_mode,
1748 TuiMode::Fullscreen
1749 );
1750 let invalid = parse_args(&s(&["--tui-mode", "split"]));
1751 assert!(!invalid.errors.is_empty());
1752 }
1753
1754 #[test]
1755 fn tui_footer_parses_and_validates() {
1756 assert_eq!(parse_args(&[]).tui_footer, TuiFooter::Full);
1757 for (value, mode) in [
1758 ("full", TuiFooter::Full),
1759 ("context", TuiFooter::Context),
1760 ("hidden", TuiFooter::Hidden),
1761 ("auto", TuiFooter::Auto),
1762 ] {
1763 let args = parse_args(&s(&["--host=work", &format!("--tui-footer={value}")]));
1764 assert!(args.errors.is_empty(), "{:?}", args.errors);
1765 assert_eq!(args.tui_footer, mode);
1766 }
1767 let args = parse_args(&s(&["--tui-footer", "hidden"]));
1768 assert!(args.errors.is_empty());
1769 assert_eq!(args.tui_footer, TuiFooter::Hidden);
1770 assert!(!parse_args(&s(&["--tui-footer=invalid"])).errors.is_empty());
1771 assert!(!parse_args(&s(&["--tui-footer"])).errors.is_empty());
1772 }
1773
1774 #[test]
1775 fn host_accepts_terminal_presentation_flags() {
1776 let args = parse_args(&s(&[
1777 "--host",
1778 "work",
1779 "--tui-mode",
1780 "regular",
1781 "--theme=light",
1782 ]));
1783 assert!(args.errors.is_empty(), "{:?}", args.errors);
1784 assert_eq!(args.host.as_deref(), Some("work"));
1785 assert_eq!(args.tui_mode, TuiMode::Regular);
1786 assert_eq!(args.theme.as_deref(), Some("light"));
1787
1788 let args = parse_args(&s(&["--no-themes", "--tui-mode=fullscreen", "--host=work"]));
1789 assert!(args.errors.is_empty(), "{:?}", args.errors);
1790 assert_eq!(args.tui_mode, TuiMode::Fullscreen);
1791 assert!(args.no_themes);
1792 assert!(!parse_args(&s(&["--host", "--provider", "fixture"]))
1793 .errors
1794 .is_empty());
1795 }
1796
1797 #[test]
1798 fn tui_mode_default_preserves_native_macos_scrollback() {
1799 assert_eq!(default_tui_mode_for(true), TuiMode::Regular);
1800 assert_eq!(default_tui_mode_for(false), TuiMode::Fullscreen);
1801 }
1802
1803 #[test]
1804 fn resolve_mode_interactive_when_tty() {
1805 let a = Args {
1806 print: true,
1807 ..Args::default()
1808 };
1809 assert_eq!(resolve_mode(&a, true, true), RunMode::Print);
1810 let a = Args::default();
1811 assert_eq!(resolve_mode(&a, true, true), RunMode::Interactive);
1812 let a = Args {
1813 mode: Mode::Json,
1814 ..Args::default()
1815 };
1816 assert_eq!(resolve_mode(&a, true, true), RunMode::Json);
1817 let a = Args {
1818 mode: Mode::Rpc,
1819 ..Args::default()
1820 };
1821 assert_eq!(resolve_mode(&a, true, true), RunMode::Rpc);
1822 }
1823
1824 #[test]
1825 fn piped_stdout_forces_print() {
1826 let a = Args::default();
1827 assert_eq!(resolve_mode(&a, true, false), RunMode::Print);
1829 }
1830}