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 mini: bool,
146 pub mode: Mode,
147 pub rpc_message_updates: RpcMessageUpdates,
148 pub tui_mode: TuiMode,
152
153 pub list_models: Option<String>,
156 pub offline: bool,
158 pub export: Option<PathBuf>,
161 pub trust_override: Option<bool>,
164
165 pub continue_session: bool,
166 pub resume: bool,
167 pub session: Option<String>,
168 pub session_id: Option<String>,
172 pub fork: Option<String>,
175 pub fork_entry: Option<String>,
180 pub fork_position: Option<rpi_harness::session::types::ForkPosition>,
186 pub models: Option<Vec<String>>,
190 pub session_dir: Option<PathBuf>,
191 pub no_session: bool,
192 pub name: Option<String>,
193
194 pub tools: Option<Vec<String>>,
195 pub exclude_tools: Option<Vec<String>>,
196 pub no_tools: bool,
197 pub no_builtin_tools: bool,
198 pub native_durable: bool,
201 pub experimental_durable_epoch: Option<String>,
203
204 pub no_skills: bool,
207 pub no_prompt_templates: bool,
210 pub no_context_files: bool,
213 pub no_extensions: bool,
216 pub no_themes: bool,
219 pub extensions_dir: Vec<PathBuf>,
227 pub extension: Vec<PathBuf>,
230 pub skill: Vec<PathBuf>,
232 pub prompt_template: Vec<PathBuf>,
235
236 pub dev_local_only: bool,
238 pub project_only: bool,
241
242 pub verbose: bool,
243 pub help: bool,
244 pub version: bool,
245
246 pub debug_system_prompt: bool,
253
254 pub messages: Vec<String>,
256 pub file_args: Vec<PathBuf>,
259
260 pub unknown_flags: BTreeMap<String, serde_json::Value>,
264 pub ignored: Vec<String>,
267 pub errors: Vec<String>,
270}
271
272pub use rpi_runtime::thinking::VALID_THINKING_LEVELS;
275
276pub use rpi_runtime::thinking::parse_thinking_level;
278
279fn file_arg(arg: &str) -> Option<PathBuf> {
282 if let Some(rest) = arg.strip_prefix('@') {
283 if rest.is_empty() {
285 None
286 } else {
287 Some(PathBuf::from(rest))
288 }
289 } else {
290 None
291 }
292}
293
294pub fn parse_args(args: &[String]) -> Args {
300 let mut result = Args::default();
301 result.native_durable = true;
304 result.offline = offline_env_enabled();
305 let mut env_extension_dirs = Vec::new();
309 if let Ok(raw) = std::env::var("RPI_EXTENSIONS_DIR") {
310 if !raw.is_empty() {
311 let sep = if cfg!(windows) { ';' } else { ':' };
312 for part in raw.split(sep) {
313 let trimmed = part.trim();
314 if !trimmed.is_empty() {
315 env_extension_dirs.push(PathBuf::from(trimmed));
316 }
317 }
318 }
319 }
320 let mut i = 0;
321 while i < args.len() {
322 let arg = args[i].clone();
323 let (flag_key, inline) = if arg.starts_with("--") {
327 match arg.find('=') {
328 Some(eq) => (arg[..eq].to_string(), Some(arg[eq + 1..].to_string())),
329 None => (arg.clone(), None),
330 }
331 } else {
332 (arg.clone(), None)
333 };
334
335 let mut take_value = |result: &mut Args, _flag: &str| -> Option<String> {
339 if let Some(v) = inline.clone() {
340 return Some(v);
341 }
342 if i + 1 < args.len() {
343 let next = &args[i + 1];
344 if !next.starts_with('-') || next == "-" {
345 i += 1;
346 return Some(args[i].clone());
347 }
348 }
349 result.errors.push(format!("{flag_key} requires a value"));
350 None
351 };
352
353 match flag_key.as_str() {
354 "--help" | "-h" => result.help = true,
355 "--version" | "-v" => result.version = true,
356 "--print" | "-p" => {
357 result.print = true;
358 if i + 1 < args.len() {
363 let next = &args[i + 1];
364 if !next.starts_with('@') && !next.starts_with('-') {
365 i += 1;
366 result.messages.push(args[i].clone());
367 }
368 }
369 }
370 "--mode" => {
371 if let Some(v) = take_value(&mut result, "--mode") {
372 result.mode = match v.as_str() {
373 "text" => Mode::Text,
374 "json" => Mode::Json,
375 "rpc" => Mode::Rpc,
376 other => {
377 result.errors.push(format!(
378 "Invalid --mode \"{other}\". Valid: text, json, rpc"
379 ));
380 Mode::Text
381 }
382 };
383 }
384 }
385 "--rpc-message-updates" => {
386 if let Some(value) = take_value(&mut result, "--rpc-message-updates") {
387 match value.as_str() {
388 "snapshot" => result.rpc_message_updates = RpcMessageUpdates::Snapshot,
389 "compact-deltas" => result.rpc_message_updates = RpcMessageUpdates::CompactDeltas,
390 other => result.errors.push(format!(
391 "Invalid --rpc-message-updates \"{other}\". Valid: snapshot, compact-deltas"
392 )),
393 }
394 }
395 }
396 "--tui-mode" => {
397 if let Some(v) = take_value(&mut result, "--tui-mode") {
398 result.tui_mode = match v.to_ascii_lowercase().as_str() {
399 "regular" => TuiMode::Regular,
400 "fullscreen" => TuiMode::Fullscreen,
401 other => {
402 result.errors.push(format!(
403 "Invalid --tui-mode \"{other}\". Valid: regular, fullscreen"
404 ));
405 TuiMode::Fullscreen
406 }
407 };
408 }
409 }
410 "--continue" | "-c" => result.continue_session = true,
411 "--resume" | "-r" => result.resume = true,
412 "--mini" => {
413 result.mini = true;
414 if inline.is_some() {
415 result.errors.push("--mini does not take a value".into());
416 }
417 }
418 "--no-session" => result.no_session = true,
419 "--no-tools" | "-nt" => result.no_tools = true,
420 "--no-builtin-tools" | "-nbt" => result.no_builtin_tools = true,
421 "--native-durable" => result.native_durable = true,
424 "--no-native-durable" => result.native_durable = false,
425 "--experimental-durable-epoch" => {
426 if result.experimental_durable_epoch.is_some() {
427 result
428 .errors
429 .push("--experimental-durable-epoch may only be supplied once".into());
430 }
431 if let Some(epoch) = take_value(&mut result, "--experimental-durable-epoch") {
432 result.experimental_durable_epoch = Some(epoch);
433 }
434 }
435 "--no-skills" | "-ns" => result.no_skills = true,
436 "--no-prompt-templates" | "-np" => result.no_prompt_templates = true,
437 "--no-context-files" | "-nc" => result.no_context_files = true,
438 "--no-extensions" | "-ne" => result.no_extensions = true,
439 "--local-only" => result.dev_local_only = true,
440 "--package-only" | "--project-only" => result.project_only = true,
441 "--extensions-dir" | "-ed" => {
442 if let Some(v) = take_value(&mut result, &flag_key) {
443 result.extensions_dir.push(PathBuf::from(v));
444 }
445 }
446 "--verbose" => result.verbose = true,
447 "--debug-system-prompt" => result.debug_system_prompt = true,
448 "--provider" => result.provider = take_value(&mut result, "--provider"),
449 "--model" => result.model = take_value(&mut result, "--model"),
450 "--api-key" => result.api_key = take_value(&mut result, "--api-key"),
451 "--base-url" => result.base_url = take_value(&mut result, "--base-url"),
452 "--timeout" => {
453 if let Some(v) = take_value(&mut result, "--timeout") {
454 match v.parse::<u64>() {
455 Ok(seconds) if seconds > 0 => {
456 result.timeout = Some(Duration::from_secs(seconds));
457 }
458 _ => result.errors.push(format!(
459 "Invalid --timeout \"{v}\". Expected a positive integer number of seconds"
460 )),
461 }
462 }
463 }
464 "--stream-idle-timeout" => {
465 if let Some(v) = take_value(&mut result, "--stream-idle-timeout") {
466 match v.parse::<u64>() {
467 Ok(seconds) => result.stream_idle_timeout = Some(Duration::from_secs(seconds)),
468 Err(_) => result.errors.push(format!(
469 "Invalid --stream-idle-timeout \"{v}\". Expected a non-negative integer number of seconds (0 disables it)"
470 )),
471 }
472 }
473 }
474 "--resource-config" => {
475 result.resource_config =
476 take_value(&mut result, "--resource-config").map(PathBuf::from)
477 }
478 "--resource-transition" => {
479 result.resource_transition =
480 take_value(&mut result, "--resource-transition").map(PathBuf::from)
481 }
482 "--system-prompt" => result.system_prompt = take_value(&mut result, "--system-prompt"),
483 "--append-system-prompt" => {
484 if let Some(v) = take_value(&mut result, "--append-system-prompt") {
485 result.append_system_prompt.push(v);
486 }
487 }
488 "--name" | "-n" => result.name = take_value(&mut result, "--name"),
489 "--session" => result.session = take_value(&mut result, "--session"),
490 "--session-id" => result.session_id = take_value(&mut result, "--session-id"),
491 "--fork" => result.fork = take_value(&mut result, "--fork"),
492 "--fork-entry" => result.fork_entry = take_value(&mut result, "--fork-entry"),
493 "--fork-position" => {
494 if let Some(value) = take_value(&mut result, "--fork-position") {
495 if value.eq_ignore_ascii_case("at") {
498 result.fork_position = Some(rpi_harness::session::types::ForkPosition::At);
499 } else if value.eq_ignore_ascii_case("before") {
500 result.fork_position =
501 Some(rpi_harness::session::types::ForkPosition::Before);
502 } else {
503 result.errors.push(format!(
504 "Invalid --fork-position \"{value}\". Expected at or before"
505 ));
506 }
507 }
508 }
509 "--models" => {
510 if let Some(v) = take_value(&mut result, &flag_key) {
511 result.models = Some(split_csv(&v));
512 }
513 }
514 "--extension" | "-e" => {
515 if let Some(v) = take_value(&mut result, &flag_key) {
516 result.extension.push(PathBuf::from(v));
517 }
518 }
519 "--skill" => {
520 if let Some(v) = take_value(&mut result, &flag_key) {
521 result.skill.push(PathBuf::from(v));
522 }
523 }
524 "--prompt-template" => {
525 if let Some(v) = take_value(&mut result, &flag_key) {
526 result.prompt_template.push(PathBuf::from(v));
527 }
528 }
529 "--session-dir" => {
530 if let Some(v) = take_value(&mut result, "--session-dir") {
531 result.session_dir = Some(PathBuf::from(v));
532 }
533 }
534 "--thinking" => {
535 if let Some(v) = take_value(&mut result, "--thinking") {
536 match parse_thinking_level(&v) {
537 Some(lvl) => result.thinking = Some(lvl),
538 None => result.ignored.push(format!(
539 "Invalid --thinking \"{v}\". Valid: {}",
540 VALID_THINKING_LEVELS.join(", ")
541 )),
542 }
543 }
544 }
545 "--tools" | "-t" => {
546 if let Some(v) = take_value(&mut result, &flag_key) {
547 result.tools = Some(split_csv(&v));
548 }
549 }
550 "--exclude-tools" | "-xt" => {
551 if let Some(v) = take_value(&mut result, &flag_key) {
552 result.exclude_tools = Some(split_csv(&v));
553 }
554 }
555 "--list-models" => {
556 let mut search = inline.clone().unwrap_or_default();
559 if inline.is_none()
560 && i + 1 < args.len()
561 && !args[i + 1].starts_with('-')
562 && !args[i + 1].starts_with('@')
563 {
564 i += 1;
565 search = args[i].clone();
566 }
567 result.list_models = Some(search);
568 }
569 "--offline" => result.offline = true,
570 "--export" => {
571 if let Some(value) = take_value(&mut result, &flag_key) {
572 result.export = Some(PathBuf::from(value));
573 }
574 }
575 "--approve" | "-a" => result.trust_override = Some(true),
576 "--no-approve" | "-na" => result.trust_override = Some(false),
577 other if matches!(other, "--models") => {
588 if inline.is_none()
591 && i + 1 < args.len()
592 && !args[i + 1].starts_with('-')
593 && !args[i + 1].starts_with('@')
594 {
595 i += 1;
596 }
597 result
598 .ignored
599 .push(format!("{other} is not supported in v1 (ignored)"));
600 }
601 "--theme" => {
602 result.theme = take_value(&mut result, "--theme");
603 }
604 "--no-themes" => result.no_themes = true,
605 other if other.starts_with("--") => {
610 let name = &flag_key;
611 let value = if let Some(value) = inline {
612 serde_json::Value::String(value)
613 } else if i + 1 < args.len()
614 && !args[i + 1].starts_with('-')
615 && !args[i + 1].starts_with('@')
616 {
617 i += 1;
618 serde_json::Value::String(args[i].clone())
619 } else {
620 serde_json::Value::Bool(true)
621 };
622 result.unknown_flags.insert(name[2..].to_string(), value);
623 }
624 other if other.starts_with('-') && other.len() > 1 => {
626 result.errors.push(format!("Unknown option: {other}"));
627 }
628 other => {
629 if let Some(path) = file_arg(other) {
630 result.file_args.push(path);
631 } else {
632 result.messages.push(other.to_string());
633 }
634 }
635 }
636 i += 1;
637 }
638
639 if result.fork.is_none() {
645 if result.fork_entry.is_some() {
646 result
647 .errors
648 .push("--fork-entry requires --fork".to_string());
649 }
650 if result.fork_position.is_some() {
651 result
652 .errors
653 .push("--fork-position requires --fork".to_string());
654 }
655 }
656 if result.fork_entry.is_none() && result.fork_position.is_some() {
657 result
658 .errors
659 .push("--fork-position requires --fork-entry".to_string());
660 }
661
662 if result.mini {
663 result.no_session = true;
664 result.native_durable = false;
665 for (present, flag) in [
666 (result.continue_session, "--continue"),
667 (result.resume, "--resume"),
668 (result.session.is_some(), "--session"),
669 (result.session_id.is_some(), "--session-id"),
670 (result.session_dir.is_some(), "--session-dir"),
671 (result.fork.is_some(), "--fork"),
672 (result.name.is_some(), "--name"),
673 (
674 result.experimental_durable_epoch.is_some(),
675 "--experimental-durable-epoch",
676 ),
677 (result.mode != Mode::Text, "--mode json/rpc"),
678 (result.export.is_some(), "--export"),
679 (result.list_models.is_some(), "--list-models"),
680 (result.models.is_some(), "--models"),
681 (result.resource_config.is_some(), "--resource-config"),
682 (
683 result.resource_transition.is_some(),
684 "--resource-transition",
685 ),
686 (!result.extension.is_empty(), "--extension"),
687 (!result.extensions_dir.is_empty(), "--extensions-dir"),
688 (!result.skill.is_empty(), "--skill"),
689 (!result.prompt_template.is_empty(), "--prompt-template"),
690 (result.theme.is_some(), "--theme"),
691 ] {
692 if present {
693 result
694 .errors
695 .push(format!("--mini cannot be combined with {flag}"));
696 }
697 }
698 for flag in result.unknown_flags.keys() {
699 result
700 .errors
701 .push(format!("--mini does not support --{flag}"));
702 }
703 } else if result.resource_config.is_none() && result.resource_transition.is_none() {
704 env_extension_dirs.append(&mut result.extensions_dir);
706 result.extensions_dir = env_extension_dirs;
707 }
708 if !result.mini {
712 if let Err(error) = crate::native_durable::experimental_epoch::policy(&result) {
713 result.errors.push(error);
714 }
715 }
716 result
717}
718
719fn split_csv(v: &str) -> Vec<String> {
721 v.split(',')
722 .map(|s| s.trim().to_string())
723 .filter(|s| !s.is_empty())
724 .collect()
725}
726
727pub fn resolve_mode(parsed: &Args, stdin_is_tty: bool, stdout_is_tty: bool) -> RunMode {
732 if parsed.unknown_flags.contains_key("server") {
734 return RunMode::Rpc;
735 }
736 if parsed.mode == Mode::Rpc {
737 return RunMode::Rpc;
738 }
739 if parsed.mode == Mode::Json {
740 return RunMode::Json;
741 }
742 if parsed.print || !stdin_is_tty || !stdout_is_tty {
743 RunMode::Print
744 } else {
745 RunMode::Interactive
746 }
747}
748
749#[derive(Debug, Clone, Copy, PartialEq, Eq)]
754pub enum RunMode {
755 Interactive,
756 Print,
757 Json,
758 Rpc,
759}
760
761pub fn print_help() {
763 let builtin = "read, bash, edit, write, docs";
764 println!(
765 "{name} - AI coding assistant with read, bash, edit, write, docs tools
766
767{u}Usage:{r}
768 {name} [options] [@files...] [messages...]
769
770{u}Options:{r}
771 --provider <name> Provider name (built-in, installed package, or models.json id)
772 --model <pattern> Model pattern or ID (supports \"provider/id\" and optional \":<thinking>\")
773 --api-key <key> API key override for the selected provider
774 --base-url <url> Override the selected model endpoint
775 --timeout <seconds> LLM API request timeout (default: 600)
776 --stream-idle-timeout <seconds> Max silence between response bytes (default: 300; 0 disables)
777 --resource-capabilities Pure bounded JSON resource protocol profile (use alone; no startup)
778 --resource-session-read <file> Strict bounded nonexecuting saved-session read (standalone)
779 --resource-transition <file> Explicit same-session resource CAS (RPC only; see docs/resource-transition-rpc.md)
780 --resource-config <file> Exact versioned startup resources (RPC only; see docs/resource-selection-rpc.md)
781 --system-prompt <text> Replace the default system prompt
782 --append-system-prompt <text> Append text to the system prompt (repeatable)
783 --thinking <level> off, minimal, low, medium, high, xhigh, max
784 --mode <mode> Output mode: text (default), json, or rpc
785 --rpc-message-updates <mode> RPC updates: compact-deltas (default) or snapshot (legacy)
786 --server [--port <n>] [--bind <ip>]
787 Headless server: serve a remote-connectable agent (no TUI)
788 --connect <host:port> Remote client: connect to a `--server` instance and run the TUI
789 (no local provider/tools/session; all agent work is remote)
790 --token <token> Auth token for `--connect` (printed by `--server`; may also
791 be provided via the RPI_SERVER_TOKEN env var)
792 --tui-mode <mode> TUI buffer: regular or fullscreen (macOS default: regular)
793 --list-models [search] List available models (with optional fuzzy search)
794 --offline Disable startup network operations (same as RPI_OFFLINE=1)
795 --export <file> Export a JSONL session to HTML and exit
796 --approve, -a Force-enable current-project resources
797 --no-approve, -na Disable current-project resources
798 --print, -p Non-interactive: process prompt(s) and exit
799 --mini Low-memory text mode: no sessions, durable, or resource discovery
800 Enable built-in tools explicitly with --tools <list>
801 --continue, -c Continue the most recent session
802 --resume, -r Browse and select a session to resume
803 --session <id|path> Use a specific session (partial UUID or file)
804 --session-id <id> Use the exact session id, creating it if missing
805 --fork <id|path> Fork a session into a new one and start in the fork
806 (partial UUID, file name fragment, or file path)
807 --fork-entry <entryId> With --fork: cut the new branch at this message
808 entry. The entry id must match exactly
809 --fork-position <at|before> With --fork-entry: keep the selected message in the
810 new branch (at) or drop it (before). Default: before
811 --session-dir <dir> Directory for session storage
812 --no-session Ephemeral mode (do not persist the session)
813 --name, -n <name> Set the session display name
814 --tools, -t <list> Comma-separated allowlist of tool names to enable
815 --exclude-tools, -xt <list> Comma-separated denylist of tool names to disable
816 --no-tools, -nt Disable all tools
817 --no-builtin-tools, -nbt Disable the built-in tools (read, bash, edit, write, docs)
818 --no-native-durable Temporary escape hatch: use legacy session behavior
819 --experimental-durable-epoch <id>
820 With native durable enabled: bounded v2 ledger, explicit same epoch on reopen; no migration
821 --no-skills, -ns Skip skill discovery (no <available_skills> block)
822 --no-prompt-templates, -np Skip prompt-template discovery (/expand templates)
823 --no-context-files, -nc Skip AGENTS.md/CLAUDE.md discovery (no <project_context>)
824 --no-extensions, -ne Skip Rust cdylib extension loading
825 --extensions-dir, -ed <dir> Extra dir to scan for plugins (.dll/.so/.dylib); repeatable
826 (also via RPI_EXTENSIONS_DIR env: ';' on Windows, ':' on Unix)
827 --local-only Skip automatic extension discovery: load only
828 --extensions-dir / --extension paths (no project
829 .rpi/extensions, no global extensions)
830 --package-only, --project-only Load project skills/prompts/extensions/packages
831 from the active project; exclude global resources
832 --debug-system-prompt Print the resolved system-prompt sections to stderr (verification)
833 --verbose Show startup warnings (e.g. ignored flags)
834 --help, -h Show this help
835 --version, -v Show version
836
837{u}Subcommands:{r}
838 update Update the rpi CLI from GitHub releases
839 (Homebrew installs use `brew upgrade rpi`)
840 auth login|check|logout Manage persisted credentials in ~/.rpi/auth.json
841 (see `rpi auth --help`)
842 events path|tail Inspect the extension event journal (needs
843 RPI_EVENT_LOG=1; see `rpi events --help`)
844 install <crate> Install a prebuilt Rust extension (--build for source)
845 (see `rpi install --help`)
846 uninstall <crate> Remove an installed Rust cdylib extension
847 extension update [name] Update project and global installed Rust extensions
848 (see `rpi extension update --help`)
849 package link|list|update|unlink Manage project-local Rust extension packages
850 (update is a legacy alias; see `rpi package --help`)
851 dev [options] Build, watch, and hot-reload a Rust extension
852 (see `rpi dev --help`)
853 dev-local [options] Debug only the current Rust extension
854 (shortcut for `rpi dev --local-only`)
855
856{u}Built-in Tools:{r}
857 {builtin} (enabled by default)
858
859{u}Examples:{r}
860 # Interactive with an initial prompt
861 {name} \"List all .rs files in src/\"
862
863 # Single-shot print mode
864 {name} -p \"Summarize this project\"
865
866 # Include a file in the initial message
867 {name} @README.md \"What does this project do?\"
868
869 # Continue the previous session
870 {name} -c \"What did we discuss?\"
871
872 # Use a specific model + thinking level
873 {name} --model claude-sonnet-5 --thinking high \"Refactor this\"
874
875 # JSON event stream (one JSON object per line on stdout)
876 {name} --mode json -p \"Inspect the code\"
877
878 # Read-only: no file-modifying tools
879 {name} --tools read,bash -p \"Review the code in src/\"
880
881{u}Environment:{r}
882 ANTHROPIC_API_KEY Anthropic API key (x-api-key) — fallback when no stored credential
883 ANTHROPIC_AUTH_TOKEN Bearer token (Authorization: Bearer) for third-party gateways
884 ANTHROPIC_BASE_URL Override the Anthropic endpoint (e.g. a compatible proxy)
885 OPENAI_API_KEY Bearer token for openai-completions/responses
886 RPI_OFFLINE Disable startup network operations when set to 1/true/yes
887 RPI_CODING_AGENT_DIR Override the ~/.rpi agent home (auth/models/settings/trust)
888 RPI_SESSION_ID Session id served by a plugin (set by the host; also honored as an override)
889
890{u}Notes:{r}
891 Supported HTTP protocols are Anthropic Messages and OpenAI Chat Completions.
892 Define custom model catalogs and provider apiKey values in
893 ~/.rpi/agent/models.json. The interactive TUI, Rust extensions, skills,
894 prompt templates, themes, model cycling, session fork/export, and trust
895 commands are available in the current build. OAuth, RPC, and full model
896 cycling remain outside the current implementation.
897",
898 name = crate::APP_NAME,
899 builtin = builtin,
900 u = "\x1b[1m",
901 r = "\x1b[0m",
902 );
903}
904
905pub fn print_version() {
907 println!("{} {}", crate::APP_NAME, crate::VERSION);
908}
909
910#[cfg(test)]
911mod tests {
912 #[test]
913 fn rpc_message_updates_selection_and_errors() {
914 assert_eq!(
915 super::Args::default().rpc_message_updates,
916 super::RpcMessageUpdates::CompactDeltas
917 );
918 for (value, expected) in [
919 ("snapshot", super::RpcMessageUpdates::Snapshot),
920 ("compact-deltas", super::RpcMessageUpdates::CompactDeltas),
921 ] {
922 for args in [
923 vec![
924 "--mode".into(),
925 "rpc".into(),
926 format!("--rpc-message-updates={value}"),
927 ],
928 vec!["--rpc-message-updates".into(), value.into()],
929 ] {
930 let parsed = super::parse_args(&args);
931 assert!(parsed.errors.is_empty(), "{:?}", parsed.errors);
932 assert_eq!(parsed.rpc_message_updates, expected);
933 assert!(parsed.unknown_flags.is_empty());
934 }
935 }
936 for args in [
937 vec!["--rpc-message-updates".into()],
938 vec!["--rpc-message-updates".into(), "--mode=json".into()],
939 vec!["--rpc-message-updates=".into()],
940 vec!["--rpc-message-updates=invalid".into()],
941 vec!["--rpc-message-updates".into(), "invalid".into()],
942 ] {
943 let parsed = super::parse_args(&args);
944 assert_eq!(parsed.errors.len(), 1);
945 assert!(parsed.errors[0].contains("--rpc-message-updates"));
946 }
947 let parsed = super::parse_args(&[
948 "--mode=json".into(),
949 "--rpc-message-updates=snapshot".into(),
950 ]);
951 assert_eq!(parsed.mode, super::Mode::Json);
952 }
953
954 use super::*;
955
956 struct RestoreOfflineEnv(Option<std::ffi::OsString>);
957
958 impl Drop for RestoreOfflineEnv {
959 fn drop(&mut self) {
960 match self.0.take() {
961 Some(value) => std::env::set_var(RPI_OFFLINE_ENV, value),
962 None => std::env::remove_var(RPI_OFFLINE_ENV),
963 }
964 }
965 }
966
967 fn s(args: &[&str]) -> Vec<String> {
968 args.iter().map(|a| a.to_string()).collect()
969 }
970
971 #[test]
972 fn parses_basic_prompt() {
973 let a = parse_args(&s(&["hello", "world"]));
974 assert_eq!(a.messages, vec!["hello".to_string(), "world".to_string()]);
975 assert!(!a.help);
976 }
977
978 #[test]
979 fn parses_help_and_version() {
980 let a = parse_args(&s(&["--help"]));
981 assert!(a.help);
982 let a = parse_args(&s(&["-v"]));
983 assert!(a.version);
984 }
985
986 #[test]
987 fn print_consumes_following_positional() {
988 let a = parse_args(&s(&["-p", "summarize"]));
989 assert!(a.print);
990 assert_eq!(a.messages, vec!["summarize".to_string()]);
991 }
992
993 #[test]
994 fn print_does_not_consume_file_or_flag() {
995 let a = parse_args(&s(&["-p", "@file.md"]));
996 assert!(a.print);
997 assert!(a.messages.is_empty());
998 assert_eq!(a.file_args, vec![PathBuf::from("file.md")]);
999 }
1000
1001 #[test]
1002 fn model_and_thinking() {
1003 let a = parse_args(&s(&["--model", "claude-sonnet-5", "--thinking", "high"]));
1004 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1005 assert_eq!(a.thinking, Some(ThinkingLevel::High));
1006 }
1007
1008 #[test]
1009 fn model_with_thinking_shorthand() {
1010 let a = parse_args(&s(&["--model", "claude-sonnet-5:high"]));
1011 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5:high"));
1013 }
1014
1015 #[test]
1016 fn tools_split_csv() {
1017 let a = parse_args(&s(&["--tools", "read, bash ,write"]));
1018 assert_eq!(
1019 a.tools.as_deref(),
1020 Some(&["read".to_string(), "bash".to_string(), "write".to_string()][..])
1021 );
1022 }
1023
1024 #[test]
1025 fn native_durable_is_enabled_by_default_with_a_transition_escape_hatch() {
1026 assert!(parse_args(&s(&[])).native_durable);
1027 assert!(parse_args(&s(&["--native-durable"])).native_durable);
1028 assert!(!parse_args(&s(&["--no-native-durable"])).native_durable);
1029 assert!(parse_args(&s(&["--no-native-durable", "--native-durable"])).native_durable);
1030 assert!(!parse_args(&s(&["--native-durable", "--no-native-durable"])).native_durable);
1031 }
1032
1033 #[test]
1034 fn mini_always_disables_session_and_durable() {
1035 for argv in [
1036 ["--mini", "--native-durable", "hello"],
1037 ["--native-durable", "--mini", "hello"],
1038 ] {
1039 let args = parse_args(&s(&argv));
1040 assert!(args.mini && args.no_session && !args.native_durable);
1041 assert!(args.errors.is_empty(), "{:?}", args.errors);
1042 assert_eq!(args.messages, ["hello"]);
1043 }
1044 }
1045
1046 #[test]
1047 fn mini_rejects_session_and_durable_epoch_flags() {
1048 for (flags, expected) in [
1049 (&["--resume"][..], "--resume"),
1050 (&["--session-id", "saved"][..], "--session-id"),
1051 (&["--mode", "rpc"][..], "--mode json/rpc"),
1052 (
1053 &["--experimental-durable-epoch", "epoch"][..],
1054 "--experimental-durable-epoch",
1055 ),
1056 ] {
1057 let argv = ["--mini"]
1058 .into_iter()
1059 .chain(flags.iter().copied())
1060 .collect::<Vec<_>>();
1061 let args = parse_args(&s(&argv));
1062 assert!(
1063 args.errors.iter().any(|error| error.contains(expected)),
1064 "{:?}",
1065 args.errors
1066 );
1067 }
1068 }
1069
1070 #[test]
1071 fn unknown_short_flag_errors() {
1072 let a = parse_args(&s(&["-Z"]));
1073 assert!(!a.errors.is_empty());
1074 }
1075
1076 #[test]
1077 fn unknown_long_flag_is_retained_for_extensions() {
1078 let a = parse_args(&s(&["--frobnicate", "value"]));
1079 assert!(a.errors.is_empty());
1080 assert_eq!(
1081 a.unknown_flags.get("frobnicate"),
1082 Some(&serde_json::Value::String("value".into()))
1083 );
1084 assert!(a.ignored.is_empty());
1085 }
1086
1087 #[test]
1088 fn unknown_long_boolean_flag_is_retained() {
1089 let a = parse_args(&s(&["--server"]));
1090 assert_eq!(
1091 a.unknown_flags.get("server"),
1092 Some(&serde_json::Value::Bool(true))
1093 );
1094 }
1095
1096 #[test]
1097 fn unknown_long_flags_keep_string_and_equals_values() {
1098 let a = parse_args(&s(&["--port", "8080", "--bind=127.0.0.1"]));
1099 assert_eq!(
1100 a.unknown_flags.get("port"),
1101 Some(&serde_json::Value::String("8080".into()))
1102 );
1103 assert_eq!(
1104 a.unknown_flags.get("bind"),
1105 Some(&serde_json::Value::String("127.0.0.1".into()))
1106 );
1107 }
1108
1109 #[test]
1110 fn models_flag_parses_csv() {
1111 let a = parse_args(&s(&["--models", "a,b,c"]));
1112 assert!(a.errors.is_empty());
1113 assert!(a.ignored.is_empty(), "--models is implemented");
1114 assert_eq!(
1115 a.models.as_deref(),
1116 Some(&["a".to_string(), "b".to_string(), "c".to_string()][..])
1117 );
1118 assert!(a.messages.is_empty());
1120 }
1121
1122 #[test]
1123 fn list_models_accepts_bare_and_search_forms() {
1124 let bare = parse_args(&s(&["--list-models"]));
1125 assert_eq!(bare.list_models.as_deref(), Some(""));
1126 assert!(bare.ignored.is_empty());
1127 assert!(bare.messages.is_empty());
1128
1129 let search = parse_args(&s(&["--list-models", "claude"]));
1130 assert_eq!(search.list_models.as_deref(), Some("claude"));
1131 assert!(search.messages.is_empty());
1132
1133 let inline = parse_args(&s(&["--list-models=gpt"]));
1134 assert_eq!(inline.list_models.as_deref(), Some("gpt"));
1135 }
1136
1137 #[test]
1138 fn offline_flag_is_honored_without_warning() {
1139 let args = parse_args(&s(&["--offline"]));
1140 assert!(args.offline);
1141 assert!(args.ignored.is_empty());
1142 }
1143
1144 #[test]
1145 fn timeout_parses_seconds_in_separate_and_equals_forms() {
1146 let separate = parse_args(&s(&["--timeout", "45"]));
1147 assert!(separate.errors.is_empty());
1148 assert_eq!(separate.timeout, Some(Duration::from_secs(45)));
1149
1150 let inline = parse_args(&s(&["--timeout=90"]));
1151 assert!(inline.errors.is_empty());
1152 assert_eq!(inline.timeout, Some(Duration::from_secs(90)));
1153 }
1154
1155 #[test]
1156 fn timeout_rejects_zero_and_invalid_values() {
1157 for value in ["0", "1.5", "forever", "18446744073709551616"] {
1158 let args = parse_args(&s(&[&format!("--timeout={value}")]));
1159 assert_eq!(args.errors.len(), 1, "value: {value}");
1160 assert!(args.timeout.is_none(), "value: {value}");
1161 }
1162 }
1163
1164 #[test]
1165 fn stream_idle_timeout_accepts_both_forms_and_zero_but_rejects_invalid_values() {
1166 for (argv, seconds) in [
1167 (s(&["--stream-idle-timeout", "45"]), 45),
1168 (s(&["--stream-idle-timeout=90"]), 90),
1169 (s(&["--stream-idle-timeout=0"]), 0),
1170 ] {
1171 let args = parse_args(&argv);
1172 assert!(args.errors.is_empty(), "{:?}", args.errors);
1173 assert_eq!(args.stream_idle_timeout, Some(Duration::from_secs(seconds)));
1174 assert!(args.timeout.is_none());
1175 }
1176 for value in ["-1", "1.5", "no", "18446744073709551616"] {
1177 let args = parse_args(&s(&[&format!("--stream-idle-timeout={value}")]));
1178 assert!(!args.errors.is_empty(), "{value}");
1179 assert!(args.stream_idle_timeout.is_none());
1180 }
1181 assert!(!parse_args(&s(&["--stream-idle-timeout"])).errors.is_empty());
1182 }
1183
1184 #[test]
1185 fn native_pi_offline_truthy_values_are_case_insensitive() {
1186 for value in [
1187 Some("1"),
1188 Some("true"),
1189 Some("TRUE"),
1190 Some("Yes"),
1191 Some("yEs"),
1192 ] {
1193 assert!(is_truthy_env_flag(value), "value={value:?}");
1194 }
1195 for value in [
1196 None,
1197 Some(""),
1198 Some("0"),
1199 Some("false"),
1200 Some("no"),
1201 Some(" true "),
1202 ] {
1203 assert!(!is_truthy_env_flag(value), "value={value:?}");
1204 }
1205 }
1206
1207 #[test]
1208 fn pi_offline_env_and_cli_flag_share_one_normalized_gate() {
1209 let _guard = crate::config::test_support::env_lock().lock().unwrap();
1210 let _restore = RestoreOfflineEnv(std::env::var_os(RPI_OFFLINE_ENV));
1211
1212 std::env::set_var(RPI_OFFLINE_ENV, "YeS");
1213 assert!(parse_args(&[]).offline);
1214 assert!(normalize_offline_mode(&[]));
1215 assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
1216
1217 std::env::set_var(RPI_OFFLINE_ENV, "0");
1218 assert!(!parse_args(&[]).offline);
1219 let argv = s(&["--offline"]);
1220 assert!(normalize_offline_mode(&argv));
1221 assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
1222 }
1223
1224 #[test]
1225 fn project_trust_flags_are_honored_without_warning() {
1226 let approved = parse_args(&s(&["--approve"]));
1227 assert_eq!(approved.trust_override, Some(true));
1228 assert!(approved.ignored.is_empty());
1229 let denied = parse_args(&s(&["--no-approve"]));
1230 assert_eq!(denied.trust_override, Some(false));
1231 assert!(denied.ignored.is_empty());
1232 }
1233
1234 #[test]
1235 fn export_flag_captures_input_and_output_position() {
1236 let args = parse_args(&s(&["--export", "session.jsonl", "transcript.html"]));
1237 assert_eq!(args.export, Some(PathBuf::from("session.jsonl")));
1238 assert_eq!(args.messages, vec!["transcript.html".to_string()]);
1239 assert!(args.ignored.is_empty());
1240 }
1241
1242 #[test]
1243 fn session_id_and_fork_flags_parse() {
1244 let a = parse_args(&s(&["--session-id", "01abc", "--fork", "xyz"]));
1245 assert!(a.errors.is_empty());
1246 assert_eq!(a.session_id.as_deref(), Some("01abc"));
1247 assert_eq!(a.fork.as_deref(), Some("xyz"));
1248 assert_eq!(a.fork_entry, None);
1249 assert_eq!(
1250 a.fork_position, None,
1251 "an explicit entry must keep the harness default (before), not force a position"
1252 );
1253 let a = parse_args(&s(&[
1254 "--fork",
1255 "xyz",
1256 "--fork-entry",
1257 "message-2",
1258 "--fork-position",
1259 "before",
1260 ]));
1261 assert!(a.errors.is_empty());
1262 assert_eq!(a.fork_entry.as_deref(), Some("message-2"));
1263 assert_eq!(
1264 a.fork_position,
1265 Some(rpi_harness::session::types::ForkPosition::Before)
1266 );
1267 let a = parse_args(&s(&["--fork-position", "middle"]));
1268 assert_eq!(a.fork_position, None);
1269 assert_eq!(
1270 a.errors,
1271 vec!["Invalid --fork-position \"middle\". Expected at or before".to_string()]
1272 );
1273 let a = parse_args(&s(&[
1274 "-e",
1275 "plugin.dll",
1276 "--skill",
1277 "s",
1278 "--prompt-template",
1279 "t.md",
1280 ]));
1281 assert_eq!(a.extension.len(), 1);
1282 assert_eq!(a.skill.len(), 1);
1283 assert_eq!(a.prompt_template.len(), 1);
1284 }
1285
1286 #[test]
1287 fn fork_position_is_case_insensitive() {
1288 use rpi_harness::session::types::ForkPosition;
1289 for (value, expected) in [
1290 ("at", ForkPosition::At),
1291 ("At", ForkPosition::At),
1292 ("AT", ForkPosition::At),
1293 ("before", ForkPosition::Before),
1294 ("Before", ForkPosition::Before),
1295 ("BEFORE", ForkPosition::Before),
1296 ] {
1297 let a = parse_args(&s(&[
1298 "--fork",
1299 "xyz",
1300 "--fork-entry",
1301 "message-2",
1302 "--fork-position",
1303 value,
1304 ]));
1305 assert!(a.errors.is_empty(), "{value}: {:?}", a.errors);
1306 assert_eq!(a.fork_position, Some(expected), "{value}");
1307 }
1308 }
1309
1310 #[test]
1315 fn fork_cut_flags_require_fork() {
1316 let a = parse_args(&s(&["--fork-entry", "message-2", "--print", "hi"]));
1317 assert_eq!(a.errors, vec!["--fork-entry requires --fork".to_string()]);
1318
1319 let a = parse_args(&s(&["--fork-position", "before"]));
1322 assert_eq!(
1323 a.errors,
1324 vec![
1325 "--fork-position requires --fork".to_string(),
1326 "--fork-position requires --fork-entry".to_string(),
1327 ]
1328 );
1329
1330 let a = parse_args(&s(&["--fork-position=at", "--fork-entry=message-2"]));
1332 assert_eq!(
1333 a.errors,
1334 vec![
1335 "--fork-entry requires --fork".to_string(),
1336 "--fork-position requires --fork".to_string(),
1337 ]
1338 );
1339
1340 let a = parse_args(&s(&[
1342 "--fork",
1343 "xyz",
1344 "--fork-entry",
1345 "message-2",
1346 "--fork-position",
1347 "at",
1348 ]));
1349 assert!(a.errors.is_empty(), "{:?}", a.errors);
1350 }
1351
1352 #[test]
1357 fn fork_position_requires_fork_entry() {
1358 for value in ["at", "before", "AT", "BEFORE"] {
1359 let a = parse_args(&s(&["--fork", "xyz", "--fork-position", value]));
1361 assert_eq!(
1362 a.errors,
1363 vec!["--fork-position requires --fork-entry".to_string()],
1364 "{value}: the flag is not inert"
1365 );
1366 assert!(a.fork_position.is_some(), "{value}");
1367
1368 let flag = format!("--fork-position={value}");
1370 let a = parse_args(&s(&["--fork", "xyz", &flag]));
1371 assert_eq!(
1372 a.errors,
1373 vec!["--fork-position requires --fork-entry".to_string()],
1374 "{flag}: the flag is not inert"
1375 );
1376 }
1377
1378 let a = parse_args(&s(&[
1380 "--fork",
1381 "xyz",
1382 "--fork-entry",
1383 "message-2",
1384 "--fork-position=before",
1385 ]));
1386 assert!(a.errors.is_empty(), "{:?}", a.errors);
1387 assert_eq!(
1388 a.fork_position,
1389 Some(rpi_harness::session::types::ForkPosition::Before)
1390 );
1391 }
1392
1393 #[test]
1394 fn no_skills_flag_honored() {
1395 let a = parse_args(&s(&["-ns"]));
1396 assert!(a.errors.is_empty());
1397 assert!(a.no_skills);
1398 assert!(a.ignored.is_empty());
1400 }
1401
1402 #[test]
1403 fn no_prompt_templates_flag_honored() {
1404 let a = parse_args(&s(&["--no-prompt-templates"]));
1405 assert!(a.no_prompt_templates);
1406 assert!(a.ignored.is_empty());
1407 }
1408
1409 #[test]
1410 fn no_context_files_flag_honored() {
1411 let a = parse_args(&s(&["-nc"]));
1412 assert!(a.no_context_files);
1413 assert!(a.ignored.is_empty());
1414 }
1415
1416 #[test]
1417 fn no_extensions_flag_honored() {
1418 let a = parse_args(&s(&["--no-extensions"]));
1420 assert!(a.no_extensions);
1421 assert!(a.ignored.is_empty());
1422 }
1423
1424 #[test]
1425 fn local_only_flag_is_honored_on_the_regular_parser() {
1426 let a = parse_args(&s(&["--local-only"]));
1429 assert!(a.errors.is_empty());
1430 assert!(a.dev_local_only);
1431 assert!(a.ignored.is_empty());
1432 }
1433
1434 #[test]
1435 fn project_only_aliases_are_honored() {
1436 for flag in ["--package-only", "--project-only"] {
1437 let a = parse_args(&s(&[flag]));
1438 assert!(a.errors.is_empty());
1439 assert!(a.project_only);
1440 assert!(a.ignored.is_empty());
1441 }
1442 }
1443
1444 #[test]
1445 fn extensions_dir_flag_collects_dirs() {
1446 let a = parse_args(&s(&["--extensions-dir", "/a/b", "-ed", "/c/d"]));
1447 assert_eq!(
1448 a.extensions_dir,
1449 vec![PathBuf::from("/a/b"), PathBuf::from("/c/d")]
1450 );
1451 assert!(a.ignored.is_empty());
1452 }
1453
1454 #[test]
1455 fn extensions_dir_inline_equals_form() {
1456 let a = parse_args(&s(&["--extensions-dir=/x/y"]));
1457 assert_eq!(a.extensions_dir, vec![PathBuf::from("/x/y")]);
1458 }
1459
1460 #[test]
1461 fn extensions_dir_env_is_merged() {
1462 let a = parse_args(&s(&["--extensions-dir", "/flag/only"]));
1468 assert!(a
1469 .extensions_dir
1470 .iter()
1471 .any(|p| p == &PathBuf::from("/flag/only")));
1472 }
1473
1474 #[test]
1475 fn file_args_stripped() {
1476 let a = parse_args(&s(&["@a.txt", "@b.md", "hi"]));
1477 assert_eq!(
1478 a.file_args,
1479 vec![PathBuf::from("a.txt"), PathBuf::from("b.md")]
1480 );
1481 assert_eq!(a.messages, vec!["hi".to_string()]);
1482 }
1483
1484 #[test]
1485 fn equals_form_supported() {
1486 let a = parse_args(&s(&["--model=claude-sonnet-5", "--thinking=low"]));
1487 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1488 assert_eq!(a.thinking, Some(ThinkingLevel::Low));
1489 }
1490
1491 #[test]
1492 fn theme_flag_is_honored() {
1493 let a = parse_args(&s(&["--theme", "ocean.json"]));
1494 assert_eq!(a.theme.as_deref(), Some("ocean.json"));
1495 assert!(a.ignored.is_empty());
1496 }
1497
1498 #[test]
1499 fn no_themes_is_honored() {
1500 let a = parse_args(&s(&["--no-themes"]));
1501 assert!(a.no_themes);
1502 assert!(a.ignored.is_empty());
1503 }
1504
1505 #[test]
1506 fn tui_mode_parses_and_validates() {
1507 assert_eq!(
1508 parse_args(&s(&["--tui-mode", "regular"])).tui_mode,
1509 TuiMode::Regular
1510 );
1511 assert_eq!(
1512 parse_args(&s(&["--tui-mode=fullscreen"])).tui_mode,
1513 TuiMode::Fullscreen
1514 );
1515 let invalid = parse_args(&s(&["--tui-mode", "split"]));
1516 assert!(!invalid.errors.is_empty());
1517 }
1518
1519 #[test]
1520 fn tui_mode_default_preserves_native_macos_scrollback() {
1521 assert_eq!(default_tui_mode_for(true), TuiMode::Regular);
1522 assert_eq!(default_tui_mode_for(false), TuiMode::Fullscreen);
1523 }
1524
1525 #[test]
1526 fn resolve_mode_interactive_when_tty() {
1527 let a = Args {
1528 print: true,
1529 ..Args::default()
1530 };
1531 assert_eq!(resolve_mode(&a, true, true), RunMode::Print);
1532 let a = Args::default();
1533 assert_eq!(resolve_mode(&a, true, true), RunMode::Interactive);
1534 let a = Args {
1535 mode: Mode::Json,
1536 ..Args::default()
1537 };
1538 assert_eq!(resolve_mode(&a, true, true), RunMode::Json);
1539 let a = Args {
1540 mode: Mode::Rpc,
1541 ..Args::default()
1542 };
1543 assert_eq!(resolve_mode(&a, true, true), RunMode::Rpc);
1544 }
1545
1546 #[test]
1547 fn piped_stdout_forces_print() {
1548 let a = Args::default();
1549 assert_eq!(resolve_mode(&a, true, false), RunMode::Print);
1551 }
1552}