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 --session-preview <uuid> Read the recent saved transcript (standalone with --session-dir)
813 --no-session Ephemeral mode (do not persist the session)
814 --name, -n <name> Set the session display name
815 --tools, -t <list> Comma-separated allowlist of tool names to enable
816 --exclude-tools, -xt <list> Comma-separated denylist of tool names to disable
817 --no-tools, -nt Disable all tools
818 --no-builtin-tools, -nbt Disable the built-in tools (read, bash, edit, write, docs)
819 --no-native-durable Temporary escape hatch: use legacy session behavior
820 --experimental-durable-epoch <id>
821 With native durable enabled: bounded v2 ledger, explicit same epoch on reopen; no migration
822 --no-skills, -ns Skip skill discovery (no <available_skills> block)
823 --no-prompt-templates, -np Skip prompt-template discovery (/expand templates)
824 --no-context-files, -nc Skip AGENTS.md/CLAUDE.md discovery (no <project_context>)
825 --no-extensions, -ne Skip Rust cdylib extension loading
826 --extensions-dir, -ed <dir> Extra dir to scan for plugins (.dll/.so/.dylib); repeatable
827 (also via RPI_EXTENSIONS_DIR env: ';' on Windows, ':' on Unix)
828 --local-only Skip automatic extension discovery: load only
829 --extensions-dir / --extension paths (no project
830 .rpi/extensions, no global extensions)
831 --package-only, --project-only Load project skills/prompts/extensions/packages
832 from the active project; exclude global resources
833 --debug-system-prompt Print the resolved system-prompt sections to stderr (verification)
834 --verbose Show startup warnings (e.g. ignored flags)
835 --help, -h Show this help
836 --version, -v Show version
837
838{u}Subcommands:{r}
839 update Update the rpi CLI from GitHub releases
840 (Homebrew installs use `brew upgrade rpi`)
841 auth login|check|logout Manage persisted credentials in ~/.rpi/auth.json
842 (see `rpi auth --help`)
843 events path|tail Inspect the extension event journal (needs
844 RPI_EVENT_LOG=1; see `rpi events --help`)
845 install <crate> Install a prebuilt Rust extension (--build for source)
846 (see `rpi install --help`)
847 uninstall <crate> Remove an installed Rust cdylib extension
848 extension update [name] Update project and global installed Rust extensions
849 (see `rpi extension update --help`)
850 package link|list|update|unlink Manage project-local Rust extension packages
851 (update is a legacy alias; see `rpi package --help`)
852 dev [options] Build, watch, and hot-reload a Rust extension
853 (see `rpi dev --help`)
854 dev-local [options] Debug only the current Rust extension
855 (shortcut for `rpi dev --local-only`)
856
857{u}Built-in Tools:{r}
858 {builtin} (enabled by default)
859
860{u}Examples:{r}
861 # Interactive with an initial prompt
862 {name} \"List all .rs files in src/\"
863
864 # Single-shot print mode
865 {name} -p \"Summarize this project\"
866
867 # Include a file in the initial message
868 {name} @README.md \"What does this project do?\"
869
870 # Continue the previous session
871 {name} -c \"What did we discuss?\"
872
873 # Use a specific model + thinking level
874 {name} --model claude-sonnet-5 --thinking high \"Refactor this\"
875
876 # JSON event stream (one JSON object per line on stdout)
877 {name} --mode json -p \"Inspect the code\"
878
879 # Read-only: no file-modifying tools
880 {name} --tools read,bash -p \"Review the code in src/\"
881
882{u}Environment:{r}
883 ANTHROPIC_API_KEY Anthropic API key (x-api-key) — fallback when no stored credential
884 ANTHROPIC_AUTH_TOKEN Bearer token (Authorization: Bearer) for third-party gateways
885 ANTHROPIC_BASE_URL Override the Anthropic endpoint (e.g. a compatible proxy)
886 OPENAI_API_KEY Bearer token for openai-completions/responses
887 RPI_OFFLINE Disable startup network operations when set to 1/true/yes
888 RPI_CODING_AGENT_DIR Override the ~/.rpi agent home (auth/models/settings/trust)
889 RPI_SESSION_ID Session id served by a plugin (set by the host; also honored as an override)
890
891{u}Notes:{r}
892 Supported HTTP protocols are Anthropic Messages and OpenAI Chat Completions.
893 Define custom model catalogs and provider apiKey values in
894 ~/.rpi/agent/models.json. The interactive TUI, Rust extensions, skills,
895 prompt templates, themes, model cycling, session fork/export, and trust
896 commands are available in the current build. OAuth, RPC, and full model
897 cycling remain outside the current implementation.
898",
899 name = crate::APP_NAME,
900 builtin = builtin,
901 u = "\x1b[1m",
902 r = "\x1b[0m",
903 );
904}
905
906pub fn print_version() {
908 println!("{} {}", crate::APP_NAME, crate::VERSION);
909}
910
911#[cfg(test)]
912mod tests {
913 #[test]
914 fn rpc_message_updates_selection_and_errors() {
915 assert_eq!(
916 super::Args::default().rpc_message_updates,
917 super::RpcMessageUpdates::CompactDeltas
918 );
919 for (value, expected) in [
920 ("snapshot", super::RpcMessageUpdates::Snapshot),
921 ("compact-deltas", super::RpcMessageUpdates::CompactDeltas),
922 ] {
923 for args in [
924 vec![
925 "--mode".into(),
926 "rpc".into(),
927 format!("--rpc-message-updates={value}"),
928 ],
929 vec!["--rpc-message-updates".into(), value.into()],
930 ] {
931 let parsed = super::parse_args(&args);
932 assert!(parsed.errors.is_empty(), "{:?}", parsed.errors);
933 assert_eq!(parsed.rpc_message_updates, expected);
934 assert!(parsed.unknown_flags.is_empty());
935 }
936 }
937 for args in [
938 vec!["--rpc-message-updates".into()],
939 vec!["--rpc-message-updates".into(), "--mode=json".into()],
940 vec!["--rpc-message-updates=".into()],
941 vec!["--rpc-message-updates=invalid".into()],
942 vec!["--rpc-message-updates".into(), "invalid".into()],
943 ] {
944 let parsed = super::parse_args(&args);
945 assert_eq!(parsed.errors.len(), 1);
946 assert!(parsed.errors[0].contains("--rpc-message-updates"));
947 }
948 let parsed = super::parse_args(&[
949 "--mode=json".into(),
950 "--rpc-message-updates=snapshot".into(),
951 ]);
952 assert_eq!(parsed.mode, super::Mode::Json);
953 }
954
955 use super::*;
956
957 struct RestoreOfflineEnv(Option<std::ffi::OsString>);
958
959 impl Drop for RestoreOfflineEnv {
960 fn drop(&mut self) {
961 match self.0.take() {
962 Some(value) => std::env::set_var(RPI_OFFLINE_ENV, value),
963 None => std::env::remove_var(RPI_OFFLINE_ENV),
964 }
965 }
966 }
967
968 fn s(args: &[&str]) -> Vec<String> {
969 args.iter().map(|a| a.to_string()).collect()
970 }
971
972 #[test]
973 fn parses_basic_prompt() {
974 let a = parse_args(&s(&["hello", "world"]));
975 assert_eq!(a.messages, vec!["hello".to_string(), "world".to_string()]);
976 assert!(!a.help);
977 }
978
979 #[test]
980 fn parses_help_and_version() {
981 let a = parse_args(&s(&["--help"]));
982 assert!(a.help);
983 let a = parse_args(&s(&["-v"]));
984 assert!(a.version);
985 }
986
987 #[test]
988 fn print_consumes_following_positional() {
989 let a = parse_args(&s(&["-p", "summarize"]));
990 assert!(a.print);
991 assert_eq!(a.messages, vec!["summarize".to_string()]);
992 }
993
994 #[test]
995 fn print_does_not_consume_file_or_flag() {
996 let a = parse_args(&s(&["-p", "@file.md"]));
997 assert!(a.print);
998 assert!(a.messages.is_empty());
999 assert_eq!(a.file_args, vec![PathBuf::from("file.md")]);
1000 }
1001
1002 #[test]
1003 fn model_and_thinking() {
1004 let a = parse_args(&s(&["--model", "claude-sonnet-5", "--thinking", "high"]));
1005 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1006 assert_eq!(a.thinking, Some(ThinkingLevel::High));
1007 }
1008
1009 #[test]
1010 fn model_with_thinking_shorthand() {
1011 let a = parse_args(&s(&["--model", "claude-sonnet-5:high"]));
1012 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5:high"));
1014 }
1015
1016 #[test]
1017 fn tools_split_csv() {
1018 let a = parse_args(&s(&["--tools", "read, bash ,write"]));
1019 assert_eq!(
1020 a.tools.as_deref(),
1021 Some(&["read".to_string(), "bash".to_string(), "write".to_string()][..])
1022 );
1023 }
1024
1025 #[test]
1026 fn native_durable_is_enabled_by_default_with_a_transition_escape_hatch() {
1027 assert!(parse_args(&s(&[])).native_durable);
1028 assert!(parse_args(&s(&["--native-durable"])).native_durable);
1029 assert!(!parse_args(&s(&["--no-native-durable"])).native_durable);
1030 assert!(parse_args(&s(&["--no-native-durable", "--native-durable"])).native_durable);
1031 assert!(!parse_args(&s(&["--native-durable", "--no-native-durable"])).native_durable);
1032 }
1033
1034 #[test]
1035 fn mini_always_disables_session_and_durable() {
1036 for argv in [
1037 ["--mini", "--native-durable", "hello"],
1038 ["--native-durable", "--mini", "hello"],
1039 ] {
1040 let args = parse_args(&s(&argv));
1041 assert!(args.mini && args.no_session && !args.native_durable);
1042 assert!(args.errors.is_empty(), "{:?}", args.errors);
1043 assert_eq!(args.messages, ["hello"]);
1044 }
1045 }
1046
1047 #[test]
1048 fn mini_rejects_session_and_durable_epoch_flags() {
1049 for (flags, expected) in [
1050 (&["--resume"][..], "--resume"),
1051 (&["--session-id", "saved"][..], "--session-id"),
1052 (&["--mode", "rpc"][..], "--mode json/rpc"),
1053 (
1054 &["--experimental-durable-epoch", "epoch"][..],
1055 "--experimental-durable-epoch",
1056 ),
1057 ] {
1058 let argv = ["--mini"]
1059 .into_iter()
1060 .chain(flags.iter().copied())
1061 .collect::<Vec<_>>();
1062 let args = parse_args(&s(&argv));
1063 assert!(
1064 args.errors.iter().any(|error| error.contains(expected)),
1065 "{:?}",
1066 args.errors
1067 );
1068 }
1069 }
1070
1071 #[test]
1072 fn unknown_short_flag_errors() {
1073 let a = parse_args(&s(&["-Z"]));
1074 assert!(!a.errors.is_empty());
1075 }
1076
1077 #[test]
1078 fn unknown_long_flag_is_retained_for_extensions() {
1079 let a = parse_args(&s(&["--frobnicate", "value"]));
1080 assert!(a.errors.is_empty());
1081 assert_eq!(
1082 a.unknown_flags.get("frobnicate"),
1083 Some(&serde_json::Value::String("value".into()))
1084 );
1085 assert!(a.ignored.is_empty());
1086 }
1087
1088 #[test]
1089 fn unknown_long_boolean_flag_is_retained() {
1090 let a = parse_args(&s(&["--server"]));
1091 assert_eq!(
1092 a.unknown_flags.get("server"),
1093 Some(&serde_json::Value::Bool(true))
1094 );
1095 }
1096
1097 #[test]
1098 fn unknown_long_flags_keep_string_and_equals_values() {
1099 let a = parse_args(&s(&["--port", "8080", "--bind=127.0.0.1"]));
1100 assert_eq!(
1101 a.unknown_flags.get("port"),
1102 Some(&serde_json::Value::String("8080".into()))
1103 );
1104 assert_eq!(
1105 a.unknown_flags.get("bind"),
1106 Some(&serde_json::Value::String("127.0.0.1".into()))
1107 );
1108 }
1109
1110 #[test]
1111 fn models_flag_parses_csv() {
1112 let a = parse_args(&s(&["--models", "a,b,c"]));
1113 assert!(a.errors.is_empty());
1114 assert!(a.ignored.is_empty(), "--models is implemented");
1115 assert_eq!(
1116 a.models.as_deref(),
1117 Some(&["a".to_string(), "b".to_string(), "c".to_string()][..])
1118 );
1119 assert!(a.messages.is_empty());
1121 }
1122
1123 #[test]
1124 fn list_models_accepts_bare_and_search_forms() {
1125 let bare = parse_args(&s(&["--list-models"]));
1126 assert_eq!(bare.list_models.as_deref(), Some(""));
1127 assert!(bare.ignored.is_empty());
1128 assert!(bare.messages.is_empty());
1129
1130 let search = parse_args(&s(&["--list-models", "claude"]));
1131 assert_eq!(search.list_models.as_deref(), Some("claude"));
1132 assert!(search.messages.is_empty());
1133
1134 let inline = parse_args(&s(&["--list-models=gpt"]));
1135 assert_eq!(inline.list_models.as_deref(), Some("gpt"));
1136 }
1137
1138 #[test]
1139 fn offline_flag_is_honored_without_warning() {
1140 let args = parse_args(&s(&["--offline"]));
1141 assert!(args.offline);
1142 assert!(args.ignored.is_empty());
1143 }
1144
1145 #[test]
1146 fn timeout_parses_seconds_in_separate_and_equals_forms() {
1147 let separate = parse_args(&s(&["--timeout", "45"]));
1148 assert!(separate.errors.is_empty());
1149 assert_eq!(separate.timeout, Some(Duration::from_secs(45)));
1150
1151 let inline = parse_args(&s(&["--timeout=90"]));
1152 assert!(inline.errors.is_empty());
1153 assert_eq!(inline.timeout, Some(Duration::from_secs(90)));
1154 }
1155
1156 #[test]
1157 fn timeout_rejects_zero_and_invalid_values() {
1158 for value in ["0", "1.5", "forever", "18446744073709551616"] {
1159 let args = parse_args(&s(&[&format!("--timeout={value}")]));
1160 assert_eq!(args.errors.len(), 1, "value: {value}");
1161 assert!(args.timeout.is_none(), "value: {value}");
1162 }
1163 }
1164
1165 #[test]
1166 fn stream_idle_timeout_accepts_both_forms_and_zero_but_rejects_invalid_values() {
1167 for (argv, seconds) in [
1168 (s(&["--stream-idle-timeout", "45"]), 45),
1169 (s(&["--stream-idle-timeout=90"]), 90),
1170 (s(&["--stream-idle-timeout=0"]), 0),
1171 ] {
1172 let args = parse_args(&argv);
1173 assert!(args.errors.is_empty(), "{:?}", args.errors);
1174 assert_eq!(args.stream_idle_timeout, Some(Duration::from_secs(seconds)));
1175 assert!(args.timeout.is_none());
1176 }
1177 for value in ["-1", "1.5", "no", "18446744073709551616"] {
1178 let args = parse_args(&s(&[&format!("--stream-idle-timeout={value}")]));
1179 assert!(!args.errors.is_empty(), "{value}");
1180 assert!(args.stream_idle_timeout.is_none());
1181 }
1182 assert!(!parse_args(&s(&["--stream-idle-timeout"])).errors.is_empty());
1183 }
1184
1185 #[test]
1186 fn native_pi_offline_truthy_values_are_case_insensitive() {
1187 for value in [
1188 Some("1"),
1189 Some("true"),
1190 Some("TRUE"),
1191 Some("Yes"),
1192 Some("yEs"),
1193 ] {
1194 assert!(is_truthy_env_flag(value), "value={value:?}");
1195 }
1196 for value in [
1197 None,
1198 Some(""),
1199 Some("0"),
1200 Some("false"),
1201 Some("no"),
1202 Some(" true "),
1203 ] {
1204 assert!(!is_truthy_env_flag(value), "value={value:?}");
1205 }
1206 }
1207
1208 #[test]
1209 fn pi_offline_env_and_cli_flag_share_one_normalized_gate() {
1210 let _guard = crate::config::test_support::env_lock().lock().unwrap();
1211 let _restore = RestoreOfflineEnv(std::env::var_os(RPI_OFFLINE_ENV));
1212
1213 std::env::set_var(RPI_OFFLINE_ENV, "YeS");
1214 assert!(parse_args(&[]).offline);
1215 assert!(normalize_offline_mode(&[]));
1216 assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
1217
1218 std::env::set_var(RPI_OFFLINE_ENV, "0");
1219 assert!(!parse_args(&[]).offline);
1220 let argv = s(&["--offline"]);
1221 assert!(normalize_offline_mode(&argv));
1222 assert_eq!(std::env::var(RPI_OFFLINE_ENV).as_deref(), Ok("1"));
1223 }
1224
1225 #[test]
1226 fn project_trust_flags_are_honored_without_warning() {
1227 let approved = parse_args(&s(&["--approve"]));
1228 assert_eq!(approved.trust_override, Some(true));
1229 assert!(approved.ignored.is_empty());
1230 let denied = parse_args(&s(&["--no-approve"]));
1231 assert_eq!(denied.trust_override, Some(false));
1232 assert!(denied.ignored.is_empty());
1233 }
1234
1235 #[test]
1236 fn export_flag_captures_input_and_output_position() {
1237 let args = parse_args(&s(&["--export", "session.jsonl", "transcript.html"]));
1238 assert_eq!(args.export, Some(PathBuf::from("session.jsonl")));
1239 assert_eq!(args.messages, vec!["transcript.html".to_string()]);
1240 assert!(args.ignored.is_empty());
1241 }
1242
1243 #[test]
1244 fn session_id_and_fork_flags_parse() {
1245 let a = parse_args(&s(&["--session-id", "01abc", "--fork", "xyz"]));
1246 assert!(a.errors.is_empty());
1247 assert_eq!(a.session_id.as_deref(), Some("01abc"));
1248 assert_eq!(a.fork.as_deref(), Some("xyz"));
1249 assert_eq!(a.fork_entry, None);
1250 assert_eq!(
1251 a.fork_position, None,
1252 "an explicit entry must keep the harness default (before), not force a position"
1253 );
1254 let a = parse_args(&s(&[
1255 "--fork",
1256 "xyz",
1257 "--fork-entry",
1258 "message-2",
1259 "--fork-position",
1260 "before",
1261 ]));
1262 assert!(a.errors.is_empty());
1263 assert_eq!(a.fork_entry.as_deref(), Some("message-2"));
1264 assert_eq!(
1265 a.fork_position,
1266 Some(rpi_harness::session::types::ForkPosition::Before)
1267 );
1268 let a = parse_args(&s(&["--fork-position", "middle"]));
1269 assert_eq!(a.fork_position, None);
1270 assert_eq!(
1271 a.errors,
1272 vec!["Invalid --fork-position \"middle\". Expected at or before".to_string()]
1273 );
1274 let a = parse_args(&s(&[
1275 "-e",
1276 "plugin.dll",
1277 "--skill",
1278 "s",
1279 "--prompt-template",
1280 "t.md",
1281 ]));
1282 assert_eq!(a.extension.len(), 1);
1283 assert_eq!(a.skill.len(), 1);
1284 assert_eq!(a.prompt_template.len(), 1);
1285 }
1286
1287 #[test]
1288 fn fork_position_is_case_insensitive() {
1289 use rpi_harness::session::types::ForkPosition;
1290 for (value, expected) in [
1291 ("at", ForkPosition::At),
1292 ("At", ForkPosition::At),
1293 ("AT", ForkPosition::At),
1294 ("before", ForkPosition::Before),
1295 ("Before", ForkPosition::Before),
1296 ("BEFORE", ForkPosition::Before),
1297 ] {
1298 let a = parse_args(&s(&[
1299 "--fork",
1300 "xyz",
1301 "--fork-entry",
1302 "message-2",
1303 "--fork-position",
1304 value,
1305 ]));
1306 assert!(a.errors.is_empty(), "{value}: {:?}", a.errors);
1307 assert_eq!(a.fork_position, Some(expected), "{value}");
1308 }
1309 }
1310
1311 #[test]
1316 fn fork_cut_flags_require_fork() {
1317 let a = parse_args(&s(&["--fork-entry", "message-2", "--print", "hi"]));
1318 assert_eq!(a.errors, vec!["--fork-entry requires --fork".to_string()]);
1319
1320 let a = parse_args(&s(&["--fork-position", "before"]));
1323 assert_eq!(
1324 a.errors,
1325 vec![
1326 "--fork-position requires --fork".to_string(),
1327 "--fork-position requires --fork-entry".to_string(),
1328 ]
1329 );
1330
1331 let a = parse_args(&s(&["--fork-position=at", "--fork-entry=message-2"]));
1333 assert_eq!(
1334 a.errors,
1335 vec![
1336 "--fork-entry requires --fork".to_string(),
1337 "--fork-position requires --fork".to_string(),
1338 ]
1339 );
1340
1341 let a = parse_args(&s(&[
1343 "--fork",
1344 "xyz",
1345 "--fork-entry",
1346 "message-2",
1347 "--fork-position",
1348 "at",
1349 ]));
1350 assert!(a.errors.is_empty(), "{:?}", a.errors);
1351 }
1352
1353 #[test]
1358 fn fork_position_requires_fork_entry() {
1359 for value in ["at", "before", "AT", "BEFORE"] {
1360 let a = parse_args(&s(&["--fork", "xyz", "--fork-position", value]));
1362 assert_eq!(
1363 a.errors,
1364 vec!["--fork-position requires --fork-entry".to_string()],
1365 "{value}: the flag is not inert"
1366 );
1367 assert!(a.fork_position.is_some(), "{value}");
1368
1369 let flag = format!("--fork-position={value}");
1371 let a = parse_args(&s(&["--fork", "xyz", &flag]));
1372 assert_eq!(
1373 a.errors,
1374 vec!["--fork-position requires --fork-entry".to_string()],
1375 "{flag}: the flag is not inert"
1376 );
1377 }
1378
1379 let a = parse_args(&s(&[
1381 "--fork",
1382 "xyz",
1383 "--fork-entry",
1384 "message-2",
1385 "--fork-position=before",
1386 ]));
1387 assert!(a.errors.is_empty(), "{:?}", a.errors);
1388 assert_eq!(
1389 a.fork_position,
1390 Some(rpi_harness::session::types::ForkPosition::Before)
1391 );
1392 }
1393
1394 #[test]
1395 fn no_skills_flag_honored() {
1396 let a = parse_args(&s(&["-ns"]));
1397 assert!(a.errors.is_empty());
1398 assert!(a.no_skills);
1399 assert!(a.ignored.is_empty());
1401 }
1402
1403 #[test]
1404 fn no_prompt_templates_flag_honored() {
1405 let a = parse_args(&s(&["--no-prompt-templates"]));
1406 assert!(a.no_prompt_templates);
1407 assert!(a.ignored.is_empty());
1408 }
1409
1410 #[test]
1411 fn no_context_files_flag_honored() {
1412 let a = parse_args(&s(&["-nc"]));
1413 assert!(a.no_context_files);
1414 assert!(a.ignored.is_empty());
1415 }
1416
1417 #[test]
1418 fn no_extensions_flag_honored() {
1419 let a = parse_args(&s(&["--no-extensions"]));
1421 assert!(a.no_extensions);
1422 assert!(a.ignored.is_empty());
1423 }
1424
1425 #[test]
1426 fn local_only_flag_is_honored_on_the_regular_parser() {
1427 let a = parse_args(&s(&["--local-only"]));
1430 assert!(a.errors.is_empty());
1431 assert!(a.dev_local_only);
1432 assert!(a.ignored.is_empty());
1433 }
1434
1435 #[test]
1436 fn project_only_aliases_are_honored() {
1437 for flag in ["--package-only", "--project-only"] {
1438 let a = parse_args(&s(&[flag]));
1439 assert!(a.errors.is_empty());
1440 assert!(a.project_only);
1441 assert!(a.ignored.is_empty());
1442 }
1443 }
1444
1445 #[test]
1446 fn extensions_dir_flag_collects_dirs() {
1447 let a = parse_args(&s(&["--extensions-dir", "/a/b", "-ed", "/c/d"]));
1448 assert_eq!(
1449 a.extensions_dir,
1450 vec![PathBuf::from("/a/b"), PathBuf::from("/c/d")]
1451 );
1452 assert!(a.ignored.is_empty());
1453 }
1454
1455 #[test]
1456 fn extensions_dir_inline_equals_form() {
1457 let a = parse_args(&s(&["--extensions-dir=/x/y"]));
1458 assert_eq!(a.extensions_dir, vec![PathBuf::from("/x/y")]);
1459 }
1460
1461 #[test]
1462 fn extensions_dir_env_is_merged() {
1463 let a = parse_args(&s(&["--extensions-dir", "/flag/only"]));
1469 assert!(a
1470 .extensions_dir
1471 .iter()
1472 .any(|p| p == &PathBuf::from("/flag/only")));
1473 }
1474
1475 #[test]
1476 fn file_args_stripped() {
1477 let a = parse_args(&s(&["@a.txt", "@b.md", "hi"]));
1478 assert_eq!(
1479 a.file_args,
1480 vec![PathBuf::from("a.txt"), PathBuf::from("b.md")]
1481 );
1482 assert_eq!(a.messages, vec!["hi".to_string()]);
1483 }
1484
1485 #[test]
1486 fn equals_form_supported() {
1487 let a = parse_args(&s(&["--model=claude-sonnet-5", "--thinking=low"]));
1488 assert_eq!(a.model.as_deref(), Some("claude-sonnet-5"));
1489 assert_eq!(a.thinking, Some(ThinkingLevel::Low));
1490 }
1491
1492 #[test]
1493 fn theme_flag_is_honored() {
1494 let a = parse_args(&s(&["--theme", "ocean.json"]));
1495 assert_eq!(a.theme.as_deref(), Some("ocean.json"));
1496 assert!(a.ignored.is_empty());
1497 }
1498
1499 #[test]
1500 fn no_themes_is_honored() {
1501 let a = parse_args(&s(&["--no-themes"]));
1502 assert!(a.no_themes);
1503 assert!(a.ignored.is_empty());
1504 }
1505
1506 #[test]
1507 fn tui_mode_parses_and_validates() {
1508 assert_eq!(
1509 parse_args(&s(&["--tui-mode", "regular"])).tui_mode,
1510 TuiMode::Regular
1511 );
1512 assert_eq!(
1513 parse_args(&s(&["--tui-mode=fullscreen"])).tui_mode,
1514 TuiMode::Fullscreen
1515 );
1516 let invalid = parse_args(&s(&["--tui-mode", "split"]));
1517 assert!(!invalid.errors.is_empty());
1518 }
1519
1520 #[test]
1521 fn tui_mode_default_preserves_native_macos_scrollback() {
1522 assert_eq!(default_tui_mode_for(true), TuiMode::Regular);
1523 assert_eq!(default_tui_mode_for(false), TuiMode::Fullscreen);
1524 }
1525
1526 #[test]
1527 fn resolve_mode_interactive_when_tty() {
1528 let a = Args {
1529 print: true,
1530 ..Args::default()
1531 };
1532 assert_eq!(resolve_mode(&a, true, true), RunMode::Print);
1533 let a = Args::default();
1534 assert_eq!(resolve_mode(&a, true, true), RunMode::Interactive);
1535 let a = Args {
1536 mode: Mode::Json,
1537 ..Args::default()
1538 };
1539 assert_eq!(resolve_mode(&a, true, true), RunMode::Json);
1540 let a = Args {
1541 mode: Mode::Rpc,
1542 ..Args::default()
1543 };
1544 assert_eq!(resolve_mode(&a, true, true), RunMode::Rpc);
1545 }
1546
1547 #[test]
1548 fn piped_stdout_forces_print() {
1549 let a = Args::default();
1550 assert_eq!(resolve_mode(&a, true, false), RunMode::Print);
1552 }
1553}