Skip to main content

rpi_cli/
app.rs

1//! CLI entry orchestrator. The `main(args)` function that:
2//!
3//! 1. Parses argv ([`crate::args::parse_args`]).
4//! 2. Handles `--help`/`--version` + parse errors + startup warnings.
5//! 3. Reads piped stdin (non-TTY ⇒ treat as the initial prompt text).
6//! 4. Expands `@file` attachments into an initial-message text block
7//!    ([`build_initial_message`]).
8//! 5. Resolves the provider + model + thinking level ([`crate::provider::resolve`]).
9//! 6. Builds the harness ([`crate::session::build`]).
10//! 7. Resolves the effective run mode ([`crate::args::resolve_mode`]) and
11//!    dispatches to [`crate::modes`] (`print`/`json`/`interactive`), mapping the
12//!    outcome to an exit code.
13//!
14//! `@file` expansion covers text files; images are detected but not attached to
15//! the prompt — the harness `prompt_text` accepts images, but this path does not
16//! yet wire an image processor. Binary/non-UTF-8 files error.
17//!
18use std::io::{IsTerminal, Read};
19use std::path::Path;
20
21use rpi_ai::types::{ImageContent, ImageContentType};
22
23use crate::args::{parse_args, print_help, print_version, resolve_mode, Args, RunMode};
24use crate::provider::{resolve_with_extensions, ResolveError};
25use crate::session::{build_prepared, prepare_extensions, BuildError};
26use crate::startup_diagnostics::{Phase, StartupSpan};
27
28/// The exit code for a usage/parse error. (TS `main.ts` uses `process.exit(1)`
29/// for most error paths; v1 distinguishes usage errors with the conventional
30/// `2` so scripts can tell "bad invocation" from "run failed".)
31pub const EXIT_USAGE: i32 = 2;
32/// The exit code for a runtime failure (model-resolution, harness-build, or
33/// run failure). Mirrors TS `process.exitCode` set from `runPrintMode`.
34pub const EXIT_RUNTIME: i32 = 1;
35/// The exit code when an extension **vetoes** startup at a lifecycle event
36/// (e.g. a `BeforeTuiStart` handler returns [`rpi_plugin_sdk::EVENT_HANDLER_ABORT`]).
37/// Distinct from [`EXIT_RUNTIME`] so scripts can tell "an extension refused to
38/// start" from "the run itself failed".
39pub const EXIT_VETOED: i32 = 3;
40
41/// Read a long-flag value from argv, supporting both `--flag <value>` and
42/// `--flag=value`, without disturbing the normal parser. Used for the early
43/// `--connect` interception.
44fn take_flag_value(argv: &[String], flag: &str) -> Option<String> {
45    let prefix = format!("{flag}=");
46    let mut iter = argv.iter();
47    while let Some(arg) = iter.next() {
48        if let Some(value) = arg.strip_prefix(&prefix) {
49            return Some(value.to_string());
50        }
51        if arg == flag {
52            return iter.next().cloned();
53        }
54    }
55    None
56}
57
58/// Resolve the `--connect` auth token: the `--token` flag wins, then the
59/// `RPI_SERVER_TOKEN` environment variable (ignoring empty/whitespace values).
60fn resolve_connect_token(argv: &[String]) -> Option<String> {
61    take_flag_value(argv, "--token").or_else(|| {
62        std::env::var("RPI_SERVER_TOKEN")
63            .ok()
64            .map(|value| value.trim().to_string())
65            .filter(|value| !value.is_empty())
66    })
67}
68
69/// The v1 CLI entry point. Mirrors TS `export async function main(args)`.
70///
71/// Returns the process exit code (0 = success). The binary wrapper
72/// ([`crate::bin`] / `src/bin/rpi.rs`) calls this under a tokio runtime and
73/// `std::process::exit`s with the returned code.
74pub async fn run() -> i32 {
75    // Startup profiling wrapper: RPI_TIMING=1 records namespace timings and
76    // flushes them to stderr once the run completes, regardless of exit path.
77    crate::timings::reset(crate::timings::TimingNamespace::Main);
78    let code = run_inner().await;
79    crate::timings::print_timings();
80    code
81}
82
83async fn run_inner() -> i32 {
84    let startup = StartupSpan::start(Phase::StartupToHarness);
85    // argv[0] is the program name; skip it (TS `main(args)` receives the same,
86    // already sliced by the Node CLI entry).
87    let mut argv: Vec<String> = std::env::args().skip(1).collect();
88    if let Err(error) = crate::native_store::early_check(&argv) {
89        eprintln!("error: {error}");
90        return EXIT_USAGE;
91    }
92
93    // Safe old-host negotiation: callers discover this flag through --help
94    // first. Never fall through to prompts, remote clients, resource commands,
95    // trust, migration, leases, credentials, providers or DLL startup.
96    if argv
97        .iter()
98        .any(|a| a == "--resource-capabilities" || a.starts_with("--resource-capabilities="))
99    {
100        if argv.len() != 1 || argv[0] != "--resource-capabilities" {
101            println!(
102                "{}",
103                serde_json::json!({"version":1,"success":false,"error":"--resource-capabilities must be used alone"})
104            );
105            return EXIT_USAGE;
106        }
107        match serde_json::to_string(&crate::resource_selection::capabilities()) {
108            Ok(profile) if profile.len() < crate::resource_selection::MAX_CAPABILITIES_BYTES => {
109                println!("{profile}");
110                return 0;
111            }
112            _ => {
113                println!(
114                    "{}",
115                    serde_json::json!({"version":1,"success":false,"error":"capability profile exceeds bound"})
116                );
117                return EXIT_RUNTIME;
118            }
119        }
120    }
121
122    if argv
123        .iter()
124        .any(|arg| arg == "--resource-session-read" || arg.starts_with("--resource-session-read="))
125    {
126        return crate::saved_session_read::run(&argv).await;
127    }
128
129    if argv.first().map(String::as_str) == Some("__rpi_dev_cleanup") {
130        return crate::dev_extension::run_cleanup_helper(&argv[1..]);
131    }
132
133    // ---- `rpi --connect <addr>` — pure remote client ----
134    // Intercepted before any provider / harness / session / extension work so
135    // the client holds no local agent resources at all: it only connects to a
136    // running `rpi --server` and renders the remote transcript.
137    if let Some(addr) = take_flag_value(&argv, "--connect") {
138        let token = resolve_connect_token(&argv);
139        return crate::remote::tui::run(&addr, token.as_deref()).await;
140    }
141
142    // Normalize the CLI flag into RPI_OFFLINE so early-dispatch subcommands and
143    // the regular parsed path all observe the same process-wide gate.
144    crate::args::normalize_offline_mode(&argv);
145
146    // `rpi dev` wraps the normal CLI: consume only development-specific
147    // options, then pass every remaining argument through the regular parser.
148    let dev_command = argv.first().map(String::as_str);
149    let dev_options = if matches!(dev_command, Some("dev" | "dev-local")) {
150        match crate::dev_extension::parse_args(&argv[1..]) {
151            Ok(options) if options.help => {
152                crate::dev_extension::print_help();
153                return 0;
154            }
155            Ok(mut options) => {
156                if dev_command == Some("dev-local") {
157                    options.local_only = true;
158                }
159                argv = options.passthrough.clone();
160                Some(options)
161            }
162            Err(error) => {
163                eprintln!("error: {error}");
164                crate::dev_extension::print_help();
165                return EXIT_USAGE;
166            }
167        }
168    } else {
169        None
170    };
171
172    // ---- Top-level subcommand dispatch (before flag parsing) ----
173    // These are top-level subcommands (mirrors TS `runAuthCommand` / the
174    // `handlePackageCommand` / `handleConfigCommand` routing in `main.ts`);
175    // dispatching them here avoids them being misparsed as prompts. The set is
176    // fixed and each handler has a different shape (sync vs async, extra argv
177    // inspection), so a `match` on the first argument — not a trait registry —
178    // is the right level of abstraction (and matches the `match mode { .. }`
179    // dispatch at the end of this function).
180    match argv.first().map(String::as_str) {
181        Some("auth") => {
182            let cwd = std::env::current_dir().unwrap_or_else(|_| Path::new(".").to_path_buf());
183            let args = crate::args::parse_args(&argv[1..]);
184            if !args.errors.is_empty() {
185                for error in &args.errors {
186                    eprintln!("error: {error}");
187                }
188                return EXIT_USAGE;
189            }
190            let trusted = crate::session::resolve_project_trust(&args, &cwd);
191            let _resource_leases = match crate::resource_management::host_leases(&cwd) {
192                Ok(leases) => leases,
193                Err(error) => {
194                    eprintln!("error: {error}");
195                    return EXIT_RUNTIME;
196                }
197            };
198            let extension_session = crate::session::load_extensions(&args, &cwd, trusted, None);
199            return crate::auth::run_with_extensions(&argv[1..], extension_session.snapshot_arc())
200                .await;
201        }
202        Some("events") => return crate::events::run(&argv[1..]).await,
203        Some("session") => return crate::session_gc::run(&argv[1..]).await,
204        Some("update") => return crate::updates::run_self_update(&argv[1..]),
205        Some("install") => return crate::install::run_async(&argv[1..]).await,
206        Some("uninstall") => return crate::install::uninstall(&argv[1..]),
207        Some("extension") => return crate::packages::run_extension(&argv[1..]),
208        Some("resource") => return crate::resource_management::run(&argv[1..]),
209        Some("package") => return crate::packages::run(&argv[1..]),
210        // These historical aliases are intentionally rejected instead of
211        // falling through to the prompt path.
212        Some(removed @ ("pi-package" | "pi-update" | "install-pi" | "uninstall-pi")) => {
213            eprintln!(
214                "error: `rpi {removed}` is not available; use `rpi package`, `rpi install`, or `rpi update`."
215            );
216            return EXIT_USAGE;
217        }
218        // // Never a working invocation; the same fall-through applies.
219        // Some("self-update") => {
220        //     eprintln!("error: unknown command `self-update`; use `rpi update`");
221        //     return EXIT_USAGE;
222        // }
223        _ => {}
224    }
225
226    let mut parsed = parse_args(&argv);
227    crate::timings::time("args parsed", crate::timings::TimingNamespace::Main);
228
229    // ---- Parsed startup stages ----
230    if let Some(code) = handle_parse_short_circuits(&parsed) {
231        return code;
232    }
233
234    if dev_options.is_some()
235        && (parsed.resource_config.is_some() || parsed.resource_transition.is_some())
236    {
237        eprintln!(
238            "error: --resource-config is restart-only and cannot be combined with dev/dev-local"
239        );
240        return EXIT_USAGE;
241    }
242    let cwd = match resolve_cwd() {
243        Ok(cwd) => cwd,
244        Err(code) => return code,
245    };
246    match crate::native_store::root(&parsed, &cwd) {
247        Ok(root) => parsed.experimental_native_store = root,
248        Err(error) => {
249            eprintln!("error: {error}");
250            return EXIT_USAGE;
251        }
252    }
253
254    // ---- Legacy-layout migration (flat ~/.rpi → ~/.rpi/agent/) ----
255    // Best-effort; never blocks startup. Skipped when RPI_CODING_AGENT_DIR is
256    // set (an explicit override is its own layout).
257    let _ = crate::config::migrate_legacy_layout();
258    crate::timings::time("config migrated", crate::timings::TimingNamespace::Main);
259
260    if let Some(code) = export_if_requested(&parsed) {
261        return code;
262    }
263
264    // `--list-models` is intentionally handled before credentials, session
265    // restoration, and harness construction. It is a catalog inspection
266    // command, so it must work for a newly installed user who has not
267    // authenticated yet.
268    if let Some(search) = parsed.list_models.as_deref() {
269        return list_models(search, &parsed, &cwd).await;
270    }
271
272    // Dev compilation is deferred until after native session resource preflight.
273
274    // `-r/--resume` is an interactive picker, unlike `-c/--continue` which
275    // immediately opens the latest session. Resolve the picker result before
276    // building the harness so cancelling does not create or modify a session.
277    if let Some(code) = resolve_resume(&mut parsed, &cwd).await {
278        return code;
279    }
280
281    emit_startup_warnings(&parsed);
282
283    // ---- stdin ownership ----
284    // Do NOT drain stdin when the run is an RPC/server session: stdin is the
285    // JSONL command channel there (a spawned `rpi --mode rpc` child reads its
286    // commands from stdin), so consuming it up-front would leave the protocol
287    // loop nothing to read. `--mode rpc` and `--server` both select RunMode::Rpc.
288    //
289    // NOTE: the actual `read_piped_stdin()` call is deferred until *after*
290    // extension load (below), because a plugin may `declare
291    // {"ownsStdio":true}` — an ACP/MCP-style stdio server that owns this
292    // process's stdin/stdout. Draining stdin before that plugin's `register`
293    // runs would deadlock it (and the host would swallow the client handshake).
294    // `--mode rpc`/`--server` are a static pre-computation (no plugin needed);
295    // the plugin claim is only known once `build()` has loaded extensions.
296    let wants_rpc_channel =
297        parsed.mode == crate::args::Mode::Rpc || parsed.unknown_flags.contains_key("server");
298
299    // ---- @file attachments → text (TS processFileArguments, text branch only) ----
300    // Deliberately runs BEFORE the cwd adoption below: `@file` paths come from
301    // the shell that launched `rpi`, so they resolve against the launch cwd no
302    // matter which directory the restored session points at.
303    let (file_text, file_images) = match process_file_args(&parsed.file_args, &cwd) {
304        Ok(t) => t,
305        Err(msg) => {
306            eprintln!("error: {msg}");
307            return EXIT_USAGE;
308        }
309    };
310
311    // ---- restored-session working directory (adopted before any resource load) ----
312    // A session records the cwd it was created in; restoring one must return
313    // the agent to that directory, because every tool resolves relative paths
314    // against the run's cwd. Adopting it here — before trust resolution,
315    // extension preparation, and the harness build — makes the whole run (tool
316    // env, system prompt, context files, extensions, footer) agree on one
317    // working directory. `@file` args above intentionally stay launch-cwd.
318    //
319    // The session ROOT is frozen first, for the same reason: settings and
320    // `RPI_CODING_AGENT_SESSION_DIR` may change while extensions load, and the
321    // adopted cwd belongs to another project's tree. Pinning the resolved root
322    // into `args` makes `prepare_extensions` and the build below read one root.
323    let session_root = crate::session::configured_session_dir(&parsed, &cwd);
324    if parsed.experimental_native_store.is_none() {
325        parsed.session_dir = Some(session_root.clone());
326    }
327    let mut startup_notices: Vec<String> = Vec::new();
328    // The peek and the build both derive their selection from this frozen root,
329    // so they can never inspect one session and open another.
330    let selection = crate::session::select_session_in_dir(&parsed, session_root);
331    let cwd_lookup = StartupSpan::start(Phase::CwdLookup);
332    let restored_cwd = crate::session::peek_restored_session_cwd(&selection, &cwd).await;
333    cwd_lookup.finish();
334    // Pin the session the peek resolved: `-c` re-lists the directory when the
335    // build runs, and another `rpi` may have written a newer session in
336    // between. Adopting one session's directory while opening another would
337    // put the tools in a directory the opened conversation never used, which is
338    // the failure this adoption exists to prevent.
339    if let Some(restored) = &restored_cwd {
340        crate::session::pin_restored_selection(&mut parsed, restored);
341    }
342    let launch_cwd = cwd;
343    let cwd = match &restored_cwd {
344        Some(restored) => match &restored.adopted {
345            Some(adopted) => {
346                // Adopting a directory is a behaviour change the user must see:
347                // tools, context files, and extensions all switch projects.
348                startup_notices.push(crate::session_cwd::adopted_session_cwd_note(
349                    &launch_cwd,
350                    adopted,
351                ));
352                adopted.clone()
353            }
354            None => {
355                startup_notices.push(crate::session_cwd::missing_session_cwd_note(
356                    &restored.recorded,
357                    &launch_cwd,
358                ));
359                launch_cwd.clone()
360            }
361        },
362        None => launch_cwd.clone(),
363    };
364
365    // ---- provider + model resolution ----
366    // Trust is resolved against the (possibly adopted) cwd: a session recorded
367    // in another project must not inherit the launch directory's trust decision.
368    let project_trusted = crate::session::resolve_project_trust(&parsed, &cwd);
369    if !project_trusted && cwd != launch_cwd {
370        startup_notices.push(crate::session_cwd::untrusted_session_cwd_note(&cwd));
371    }
372    // Development preflight precedes prepare_extensions: protect its registry
373    // reads at orchestration too; the fact reader itself stays non-mutating.
374    let _dev_resource_leases = if dev_options.is_some() {
375        match crate::resource_management::host_leases(&cwd) {
376            Ok(leases) => Some(leases),
377            Err(error) => {
378                eprintln!("error: {error}");
379                return EXIT_RUNTIME;
380            }
381        }
382    } else {
383        None
384    };
385    // Reject a bound exact session before dev can build or stage any code.
386    if dev_options.is_some() {
387        if let Err(error) =
388            crate::session::preflight_extension_startup(&parsed, &cwd, project_trusted)
389        {
390            print_build_error(&error);
391            return EXIT_RUNTIME;
392        }
393    }
394    let dev_extension = match prepare_dev_extension(dev_options.as_ref(), &launch_cwd, &mut parsed)
395    {
396        Ok(extension) => extension,
397        Err(code) => return code,
398    };
399    let extension_prepare = StartupSpan::start(Phase::ExtensionPrepare);
400    let prepared = match prepare_extensions(&parsed, &cwd, project_trusted) {
401        Ok(prepared) => prepared,
402        Err(error) => {
403            print_build_error(&error);
404            return EXIT_RUNTIME;
405        }
406    };
407    extension_prepare.finish();
408    let model_resolve = StartupSpan::start(Phase::ModelResolve);
409    let resolved = match resolve_with_extensions(
410        &parsed,
411        &cwd,
412        project_trusted,
413        &prepared.extension_session,
414    ) {
415        Ok(r) => r,
416        Err(e) => {
417            print_resolve_error(&e);
418            return match e {
419                ResolveError::NoApiKey { .. } | ResolveError::Config(_) => EXIT_USAGE,
420                _ => EXIT_RUNTIME,
421            };
422        }
423    };
424
425    model_resolve.finish();
426    for warning in &resolved.compat_warnings {
427        eprintln!("warning: models.json: {warning}");
428    }
429
430    // The full authenticated catalog (read-only) for the TUI's `/model`
431    // selector, derived from the built provider runtimes so auth headers and
432    // base-url overrides survive.
433    let model_catalog = crate::provider::authenticated_catalog(&resolved);
434
435    // `--models <patterns>`: persist the Ctrl+P cycle scope to settings.json
436    // (the same set `/scoped-models` edits). Each pattern matches catalog ids
437    // case-insensitively; unmatched patterns are reported so a typo doesn't
438    // silently empty the cycle.
439    if let Some(patterns) = &parsed.models {
440        let mut matched: Vec<String> = Vec::new();
441        for p in patterns {
442            let hits: Vec<String> = model_catalog
443                .iter()
444                .filter(|m| m.id.eq_ignore_ascii_case(p))
445                .map(|m| m.id.clone())
446                .collect();
447            if hits.is_empty() {
448                eprintln!("warning: --models pattern \"{p}\" matched no model");
449            }
450            matched.extend(hits);
451        }
452        let mut settings = crate::settings::load_settings().unwrap_or_default();
453        settings.scoped_models = if matched.is_empty() {
454            None
455        } else {
456            Some(matched)
457        };
458        if let Err(e) = crate::settings::save_settings(&settings) {
459            eprintln!("warning: could not save --models scope: {e}");
460        }
461    }
462
463    // ---- harness build ----
464    let harness_build = StartupSpan::start(Phase::HarnessBuild);
465    let (harness, event_rx, mut reload_context) =
466        match build_prepared(&resolved, &parsed, &cwd, project_trusted, prepared).await {
467            Ok(triple) => triple,
468            Err(e) => {
469                print_build_error(&e);
470                return EXIT_RUNTIME;
471            }
472        };
473    harness_build.finish();
474    startup.finish();
475    reload_context.dev_extension = dev_extension;
476
477    // ---- post-load stdin claim + initial message ----
478    // Extensions are loaded by `build()` (above). A plugin may have declared
479    // `{"ownsStdio":true}`: this process's stdio belongs to it (an ACP/MCP stdio
480    // server), so the host must neither drain stdin nor run a prompt/TUI mode
481    // that writes to stdout. Only now — after load — do we know. `--mode
482    // rpc`/`--server` already skipped the drain via `wants_rpc_channel`.
483    let stdio_claimed = reload_context
484        .extension_session
485        .lock()
486        .map(|session| session.owns_stdio())
487        .unwrap_or(false);
488    let web_requested = match parsed.unknown_flags.get("web") {
489        Some(serde_json::Value::Bool(value)) => *value,
490        Some(serde_json::Value::String(value)) => {
491            !value.is_empty() && !value.eq_ignore_ascii_case("false")
492        }
493        _ => false,
494    };
495    let web_registered = reload_context
496        .extension_session
497        .lock()
498        .ok()
499        .and_then(|session| {
500            session
501                .snapshot()
502                .map(|snapshot| snapshot.flags().iter().any(|flag| flag.name == "web"))
503        })
504        .unwrap_or(false);
505    if web_requested && (!web_registered || !stdio_claimed) {
506        eprintln!("error: --web requires the rpi-web server extension; it is missing, disabled, or failed to load.\nInstall it with: rpi install rpi-web --github pi-rust/rpi-package\nThen restart with: rpi --web");
507        return EXIT_USAGE;
508    }
509    let stdio_lifecycle = reload_context
510        .extension_session
511        .lock()
512        .ok()
513        .and_then(|session| session.action_bridge())
514        .map(|bridge| bridge.stdio_lifecycle());
515    if let Some(lifecycle) = &stdio_lifecycle {
516        if let Err(error) = lifecycle.validate() {
517            eprintln!("error: {error}");
518            return EXIT_RUNTIME;
519        }
520    }
521    let stdin_text = if wants_rpc_channel || stdio_claimed {
522        None
523    } else {
524        read_piped_stdin()
525    };
526
527    // ---- initial message + extra messages (TS buildInitialMessage) ----
528    let file_text_opt = if file_text.is_empty() {
529        None
530    } else {
531        Some(file_text.as_str())
532    };
533    let (initial, extra) = build_initial_message(&parsed, stdin_text.as_deref(), file_text_opt);
534
535    // ---- mode dispatch (TS resolveAppMode → runPrintMode / InteractiveMode / runRpcMode) ----
536    let stdin_is_tty = std::io::stdin().is_terminal();
537    let stdout_is_tty = std::io::stdout().is_terminal();
538    let mode = resolve_mode(&parsed, stdin_is_tty, stdout_is_tty);
539
540    // TS downgrades interactive → print when piped stdin is present.
541    let mode = if matches!(mode, RunMode::Interactive) && stdin_text.is_some() {
542        RunMode::Print
543    } else {
544        mode
545    };
546
547    // Debug/testing escape hatch: RPI_FORCE_TUI=1 forces interactive mode
548    // (for testing the TUI in non-TTY environments).
549    let mode = if std::env::var("RPI_FORCE_TUI")
550        .map(|v| v == "1")
551        .unwrap_or(false)
552    {
553        RunMode::Interactive
554    } else {
555        mode
556    };
557
558    // A plugin that claimed stdio owns this process's stdin/stdout: force the
559    // headless Rpc lifecycle (dispatch startup events, then wait for completion)
560    // and let the plugin's own protocol server read/write stdio. This is
561    // authoritative — it must win over TTY detection and RPI_FORCE_TUI,
562    // otherwise the host would start a TUI/print run that writes to a stream the
563    // plugin owns.
564    let mode = if stdio_claimed { RunMode::Rpc } else { mode };
565    if let Err(error) =
566        crate::native_store::validate_mode(parsed.experimental_native_store.is_some(), mode)
567    {
568        eprintln!("error: {error}");
569        return EXIT_USAGE;
570    }
571
572    // ---- startup notices (restored-session cwd) ----
573    // The interactive TUI renders them as transcript notes (they must survive
574    // into the alternate screen); headless modes print them to stderr like the
575    // other startup warnings.
576    if matches!(mode, RunMode::Interactive) {
577        reload_context.startup_notices = startup_notices;
578    } else {
579        for notice in &startup_notices {
580            eprintln!("warning: {notice}");
581        }
582    }
583
584    let dev_cleanup = reload_context.dev_extension.clone();
585    let dev_watcher = if matches!(mode, RunMode::Interactive) {
586        reload_context
587            .dev_extension
588            .as_ref()
589            .and_then(|extension| extension.start_watcher(reload_context.mailbox.clone()))
590    } else {
591        None
592    };
593
594    let exit_code = match mode {
595        RunMode::Print => {
596            crate::modes::print(
597                &harness,
598                &parsed,
599                initial.clone(),
600                &extra,
601                file_images.clone(),
602            )
603            .await
604        }
605        RunMode::Json => {
606            crate::modes::json(
607                &harness,
608                &parsed,
609                initial.clone(),
610                &extra,
611                file_images.clone(),
612                Some(event_rx),
613            )
614            .await
615        }
616        RunMode::Interactive => {
617            crate::modes::interactive(
618                &harness,
619                Some(event_rx),
620                &parsed,
621                model_catalog,
622                initial.clone(),
623                &extra,
624                file_images.clone(),
625                if parsed.no_themes {
626                    None
627                } else {
628                    parsed.theme.as_deref().or(resolved.theme.as_deref())
629                },
630                parsed.no_themes,
631                &reload_context,
632            )
633            .await
634        }
635        RunMode::Rpc => {
636            // Headless lifecycle (P0): no TUI, but a session still starts/ends —
637            // extensions (e.g. rpi-server) auto-start on SessionStart and clean
638            // up on SessionShutdown, exactly as in interactive mode. This is why
639            // `rpi --server` works headless: the SessionStart hook fires and the
640            // extension brings up the TCP server.
641            let before_start = StartupSpan::start(Phase::BeforeStartHooks);
642            let veto = crate::session::dispatch_session_event_async(
643                &reload_context,
644                rpi_plugin_sdk::EventTag::BeforeTuiStart,
645            )
646            .await;
647            before_start.finish();
648            if let Some(reason) = veto {
649                eprintln!("[rpi] startup vetoed by extension: {reason}");
650                EXIT_VETOED
651            } else {
652                let session_start = StartupSpan::start(Phase::SessionStartHooks);
653                if let Some(reason) = crate::session::dispatch_session_event_async(
654                    &reload_context,
655                    rpi_plugin_sdk::EventTag::SessionStart,
656                )
657                .await
658                {
659                    tracing::warn!(
660                        "[rpi] extension vetoed SessionStart (headless, advisory): {reason}"
661                    );
662                }
663                session_start.finish();
664
665                let code = if parsed.unknown_flags.contains_key("server") || stdio_claimed {
666                    // Server mode OR a plugin-claimed stdio server: the extension
667                    // owns the process's I/O. Wait for its completion or Ctrl+C,
668                    // then dispatch SessionShutdown before unloading plugins.
669                    eprintln!(
670                        "[rpi] running in headless mode (no TUI); extension owns stdio; Ctrl+C to stop"
671                    );
672                    if stdio_claimed {
673                        let lifecycle = stdio_lifecycle
674                            .as_ref()
675                            .expect("stdio owner requires an action bridge");
676                        tokio::select! {
677                            code = lifecycle.wait() => code,
678                            _ = tokio::signal::ctrl_c() => 0,
679                        }
680                    } else {
681                        let _ = tokio::signal::ctrl_c().await;
682                        0
683                    }
684                } else {
685                    // `--mode rpc`: JSONL command loop over stdio — the
686                    // server-side agent that rpi-server spawns and that
687                    // `rpi --connect` talks to. The extension `UiDialog`
688                    // mailbox is bridged over the same channel so a permission
689                    // gate can ask the client mid-run.
690                    // Release the extension session lock before the RPC loop awaits.
691                    // ToolCall hooks need the same lock to dispatch approvals.
692                    let oauth_snapshot = {
693                        let session = reload_context.extension_session.lock().unwrap();
694                        session.snapshot_arc()
695                    };
696                    crate::modes::rpc(
697                        &harness,
698                        Some(event_rx),
699                        model_catalog,
700                        reload_context.ui_dialog.clone(),
701                        oauth_snapshot,
702                        parsed.rpc_message_updates,
703                    )
704                    .await
705                };
706
707                if let Some(reason) = crate::session::dispatch_session_event_async(
708                    &reload_context,
709                    rpi_plugin_sdk::EventTag::SessionShutdown,
710                )
711                .await
712                {
713                    tracing::warn!(
714                        "[rpi] extension vetoed SessionShutdown (ignored, closing): {reason}"
715                    );
716                }
717                code
718            }
719        }
720    };
721
722    if let Some(dev) = &dev_cleanup {
723        dev.stop_watcher();
724    }
725    if let Some(watcher) = dev_watcher {
726        let _ = watcher.join();
727    }
728    drop(reload_context);
729    drop(harness);
730    if let Some(dev) = dev_cleanup {
731        dev.cleanup();
732    }
733    exit_code
734}
735
736fn handle_parse_short_circuits(parsed: &Args) -> Option<i32> {
737    // ---- --help / --version short-circuit (before any heavy work) ----
738    if parsed.help {
739        print_help();
740        return Some(0);
741    }
742    if parsed.version {
743        print_version();
744        return Some(0);
745    }
746
747    // ---- Parse errors → help + usage exit ----
748    if !parsed.errors.is_empty() {
749        for err in &parsed.errors {
750            eprintln!("error: {err}");
751        }
752        eprintln!();
753        print_help();
754        return Some(EXIT_USAGE);
755    }
756
757    None
758}
759
760fn resolve_cwd() -> Result<std::path::PathBuf, i32> {
761    std::env::current_dir().map_err(|error| {
762        eprintln!("error: could not determine the current directory: {error}");
763        EXIT_USAGE
764    })
765}
766
767fn export_if_requested(parsed: &Args) -> Option<i32> {
768    let input = parsed.export.as_deref()?;
769    let output = parsed
770        .messages
771        .first()
772        .map(Path::new)
773        .map(Path::to_path_buf)
774        .unwrap_or_else(|| {
775            let stem = input
776                .file_stem()
777                .and_then(|value| value.to_str())
778                .unwrap_or("session");
779            Path::new(&format!("rpi-session-{stem}.html")).to_path_buf()
780        });
781
782    match crate::export::export_file(input, &output) {
783        Ok(()) => {
784            println!("Exported to: {}", output.display());
785            Some(0)
786        }
787        Err(error) => {
788            eprintln!("error: {error}");
789            Some(EXIT_RUNTIME)
790        }
791    }
792}
793
794fn prepare_dev_extension(
795    options: Option<&crate::dev_extension::DevOptions>,
796    cwd: &Path,
797    parsed: &mut Args,
798) -> Result<Option<std::sync::Arc<crate::dev_extension::DevExtension>>, i32> {
799    let Some(options) = options else {
800        return Ok(None);
801    };
802
803    match crate::dev_extension::DevExtension::detect(cwd, options) {
804        Ok(extension) => {
805            if let Err(error) = extension.rebuild() {
806                eprintln!("error: initial extension build failed: {error}");
807                return Err(EXIT_RUNTIME);
808            }
809            if let Err(error) = extension.apply_to_args(parsed) {
810                eprintln!("error: {error}");
811                return Err(EXIT_RUNTIME);
812            }
813            Ok(Some(extension))
814        }
815        Err(error) => {
816            // No Cargo cdylib found: degrade to skills-only mode.
817            eprintln!("dev: {error}");
818            eprintln!("dev: no Cargo cdylib found; running in skills-only mode");
819            parsed.no_extensions = true;
820            parsed.extensions_dir.clear();
821            parsed.extension.clear();
822            if options.local_only {
823                parsed.dev_local_only = true;
824            }
825            Ok(None)
826        }
827    }
828}
829
830async fn resolve_resume(parsed: &mut Args, cwd: &Path) -> Option<i32> {
831    if !parsed.resume {
832        return None;
833    }
834    if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
835        eprintln!("error: --resume requires an interactive terminal");
836        return Some(EXIT_USAGE);
837    }
838
839    let session_dir = crate::session::configured_session_dir(parsed, cwd);
840    match crate::resume_picker::select_in_dir(cwd, &session_dir).await {
841        Ok(Some(id)) => {
842            parsed.resume = false;
843            parsed.session = Some(id);
844            parsed.session_dir = Some(session_dir);
845            None
846        }
847        Ok(None) => Some(0),
848        Err(error) => {
849            eprintln!("error: {error}");
850            Some(EXIT_RUNTIME)
851        }
852    }
853}
854
855fn emit_startup_warnings(parsed: &Args) {
856    // ---- Startup warnings (ignored-but-recognized flags) ----
857    if parsed.verbose {
858        for warn in &parsed.ignored {
859            eprintln!("warning: {warn}");
860        }
861    }
862    if parsed.no_themes && parsed.theme.is_some() {
863        eprintln!("warning: --no-themes overrides --theme; using the built-in default theme");
864    }
865}
866
867/// Print the merged model catalog, optionally filtered by a case-insensitive
868/// fuzzy-ish substring over provider, id, and display name.
869async fn list_models(search: &str, args: &Args, cwd: &Path) -> i32 {
870    let trusted = crate::session::resolve_project_trust(args, cwd);
871    let prepared = match prepare_extensions(args, cwd, trusted) {
872        Ok(prepared) => prepared,
873        Err(error) => {
874            print_build_error(&error);
875            return EXIT_RUNTIME;
876        }
877    };
878    let manifests = crate::provider::manifests_from_session(&prepared.extension_session);
879    let catalog = match crate::provider::catalog_with_diagnostics(&manifests) {
880        Ok((models, warnings)) => {
881            for warning in warnings {
882                eprintln!("warning: models.json: {warning}");
883            }
884            models
885        }
886        Err(error) => {
887            eprintln!("warning: could not load models.json: {error}");
888            Vec::new()
889        }
890    };
891    let needle = search.trim().to_ascii_lowercase();
892    let mut models: Vec<_> = catalog
893        .into_iter()
894        .filter(|model| {
895            needle.is_empty()
896                || format!("{} {} {}", model.provider, model.id, model.name)
897                    .to_ascii_lowercase()
898                    .contains(&needle)
899        })
900        .collect();
901    if models.is_empty() {
902        if needle.is_empty() {
903            println!("{}", crate::auth_guidance::no_models_available_message());
904        } else {
905            println!("No models matching \"{search}\"");
906        }
907        return 0;
908    }
909
910    fn format_tokens(value: u64) -> String {
911        if value >= 1_000_000 {
912            let whole = value % 1_000_000 == 0;
913            if whole {
914                format!("{}M", value / 1_000_000)
915            } else {
916                format!("{:.1}M", value as f64 / 1_000_000.0)
917            }
918        } else if value >= 1_000 {
919            let whole = value % 1_000 == 0;
920            if whole {
921                format!("{}K", value / 1_000)
922            } else {
923                format!("{:.1}K", value as f64 / 1_000.0)
924            }
925        } else {
926            value.to_string()
927        }
928    }
929
930    let rows: Vec<_> = models
931        .drain(..)
932        .map(|model| {
933            let images = model
934                .input
935                .iter()
936                .any(|input| matches!(input, rpi_ai::InputModality::Image));
937            (
938                model.provider,
939                model.id,
940                format_tokens(model.context_window),
941                format_tokens(model.max_tokens),
942                if model.reasoning { "yes" } else { "no" }.to_string(),
943                if images { "yes" } else { "no" }.to_string(),
944            )
945        })
946        .collect();
947    let widths = (
948        rows.iter().map(|r| r.0.len()).max().unwrap_or(8).max(8),
949        rows.iter().map(|r| r.1.len()).max().unwrap_or(5).max(5),
950        rows.iter().map(|r| r.2.len()).max().unwrap_or(7).max(7),
951        rows.iter().map(|r| r.3.len()).max().unwrap_or(7).max(7),
952        rows.iter().map(|r| r.4.len()).max().unwrap_or(8).max(8),
953        rows.iter().map(|r| r.5.len()).max().unwrap_or(6).max(6),
954    );
955    println!(
956        "{:provider$}  {:model$}  {:context$}  {:max_out$}  {:thinking$}  {:images$}",
957        "provider",
958        "model",
959        "context",
960        "max-out",
961        "thinking",
962        "images",
963        provider = widths.0,
964        model = widths.1,
965        context = widths.2,
966        max_out = widths.3,
967        thinking = widths.4,
968        images = widths.5,
969    );
970    for row in rows {
971        println!(
972            "{:provider$}  {:model$}  {:context$}  {:max_out$}  {:thinking$}  {:images$}",
973            row.0,
974            row.1,
975            row.2,
976            row.3,
977            row.4,
978            row.5,
979            provider = widths.0,
980            model = widths.1,
981            context = widths.2,
982            max_out = widths.3,
983            thinking = widths.4,
984            images = widths.5,
985        );
986    }
987    0
988}
989
990/// Read piped stdin into a string. Mirrors TS `readPipedStdin`: returns `None`
991/// when stdin is a TTY (interactive), else the trimmed stdin text (empty ⇒
992/// `None`).
993///
994/// NOTE: if stdin is *not* a TTY but no bytes arrive (e.g. `pi < /dev/null`),
995/// this returns `None` (empty), which is what TS does too (`data.trim() || undefined`).
996fn read_piped_stdin() -> Option<String> {
997    // Debug/testing escape hatch: RPI_SKIP_STDIN=1 skips reading piped stdin
998    // (avoids blocking on non-TTY stdin in automated environments).
999    if std::env::var("RPI_SKIP_STDIN")
1000        .map(|v| v == "1")
1001        .unwrap_or(false)
1002    {
1003        return None;
1004    }
1005    if std::io::stdin().is_terminal() {
1006        return None;
1007    }
1008    let mut buf = String::new();
1009    match std::io::stdin().read_to_string(&mut buf) {
1010        Ok(_) => {
1011            let trimmed = buf.trim();
1012            if trimmed.is_empty() {
1013                None
1014            } else {
1015                Some(trimmed.to_string())
1016            }
1017        }
1018        Err(_) => None,
1019    }
1020}
1021
1022/// Expand `@file` attachments into prompt text. Mirrors the *text* branch of
1023/// TS `processFileArguments`: each readable text file is wrapped in
1024/// `<file name="...">\n<contents>\n</file>\n` and concatenated.
1025///
1026/// Paths are resolved relative to `cwd` (the TS uses `resolve(readPath, cwd)`).
1027fn process_file_args(
1028    file_args: &[std::path::PathBuf],
1029    cwd: &Path,
1030) -> Result<(String, Vec<ImageContent>), String> {
1031    let mut text = String::new();
1032    let mut images = Vec::new();
1033    for rel in file_args {
1034        let abs = if rel.is_absolute() {
1035            rel.clone()
1036        } else {
1037            cwd.join(rel)
1038        };
1039        if !abs.exists() {
1040            return Err(format!("file not found: {}", abs.display()));
1041        }
1042        let bytes = std::fs::read(&abs)
1043            .map_err(|e| format!("could not read file {}: {e}", abs.display()))?;
1044        if let Some(image) = image_content_from_bytes(&bytes) {
1045            images.push(image);
1046        } else {
1047            let content = String::from_utf8(bytes).map_err(|_| {
1048                format!(
1049                    "file is not valid UTF-8 text or a supported image: {}",
1050                    abs.display()
1051                )
1052            })?;
1053            text.push_str(&format!(
1054                "<file name=\"{}\">\n{}\n</file>\n",
1055                abs.display(),
1056                content
1057            ));
1058        }
1059    }
1060    Ok((text, images))
1061}
1062
1063pub(crate) fn image_content_from_path(path: &Path) -> Result<Option<ImageContent>, String> {
1064    let bytes =
1065        std::fs::read(path).map_err(|e| format!("could not read file {}: {e}", path.display()))?;
1066    Ok(image_content_from_bytes(&bytes))
1067}
1068
1069fn image_content_from_bytes(bytes: &[u8]) -> Option<ImageContent> {
1070    let mime_type = rpi_tools::detect_supported_image_mime_type(bytes)?;
1071    Some(ImageContent {
1072        kind: ImageContentType,
1073        data: rpi_tools::encode_base64(bytes).into(),
1074        mime_type: mime_type.to_string(),
1075    })
1076}
1077
1078/// Build the initial prompt + the remaining extra messages. Mirrors TS
1079/// `buildInitialMessage`: `[stdinContent, fileText, messages[0]].join("")` is
1080/// the initial message; `messages[1..]` are the follow-up prompts.
1081///
1082/// Returns `(initial: Option<String>, extra: Vec<String>)`.
1083fn build_initial_message(
1084    parsed: &Args,
1085    stdin: Option<&str>,
1086    file_text: Option<&str>,
1087) -> (Option<String>, Vec<String>) {
1088    let mut extra = parsed.messages.clone();
1089    let mut parts: Vec<String> = Vec::new();
1090    if let Some(s) = stdin {
1091        parts.push(s.to_string());
1092    }
1093    if let Some(t) = file_text {
1094        parts.push(t.to_string());
1095    }
1096    // Pull the first positional message into the initial prompt (TS `.shift()`).
1097    if !extra.is_empty() {
1098        parts.push(extra.remove(0));
1099    }
1100    let initial = if parts.is_empty() {
1101        None
1102    } else {
1103        Some(parts.join(""))
1104    };
1105    (initial, extra)
1106}
1107
1108/// Print a model-resolution error with env-specific guidance. Mirrors the TS
1109/// auth-guidance / model-resolver error formatting (condensed to stderr lines).
1110fn print_resolve_error(e: &ResolveError) {
1111    match e {
1112        ResolveError::NoApiKey { hint } => {
1113            eprintln!("error: {e}");
1114            eprintln!();
1115            eprintln!("Provide credentials via one of: {hint}.");
1116        }
1117        ResolveError::Config(_) => {
1118            eprintln!("error: {e}");
1119            eprintln!();
1120            eprintln!("Check ~/.rpi/auth.json / ~/.rpi/models.json (set RPI_CODING_AGENT_DIR to relocate).");
1121        }
1122        _ => eprintln!("error: {e}"),
1123    }
1124}
1125
1126/// Print a harness-build error with flag-specific guidance for restore requests.
1127fn print_build_error(e: &BuildError) {
1128    match e {
1129        BuildError::SessionNotFound { .. } => {
1130            eprintln!("error: {e}");
1131            eprintln!();
1132            eprintln!("List saved sessions with the /session command in interactive mode.");
1133        }
1134        _ => eprintln!("error: {e}"),
1135    }
1136}
1137
1138#[cfg(test)]
1139mod tests {
1140    use super::*;
1141    use crate::args::Args;
1142
1143    #[test]
1144    fn take_flag_value_supports_both_spellings() {
1145        let argv = vec![
1146            "--connect".to_string(),
1147            "127.0.0.1:9899".to_string(),
1148            "--token".to_string(),
1149            "abc".to_string(),
1150        ];
1151        assert_eq!(
1152            take_flag_value(&argv, "--connect").as_deref(),
1153            Some("127.0.0.1:9899")
1154        );
1155        assert_eq!(take_flag_value(&argv, "--token").as_deref(), Some("abc"));
1156        assert_eq!(take_flag_value(&argv, "--missing"), None);
1157
1158        let inline = vec!["--connect=1.2.3.4:1".to_string()];
1159        assert_eq!(
1160            take_flag_value(&inline, "--connect").as_deref(),
1161            Some("1.2.3.4:1")
1162        );
1163    }
1164
1165    #[test]
1166    fn connect_token_prefers_the_flag_over_the_env_var() {
1167        // The flag wins regardless of any RPI_SERVER_TOKEN in the environment.
1168        let argv = vec!["--token".to_string(), "flag-token".to_string()];
1169        assert_eq!(resolve_connect_token(&argv).as_deref(), Some("flag-token"));
1170    }
1171
1172    #[test]
1173    fn build_initial_combines_stdin_file_and_first_message() {
1174        let mut args = Args::default();
1175        args.messages = vec!["first".into(), "second".into(), "third".into()];
1176        let (initial, extra) =
1177            build_initial_message(&args, Some("stdin-text"), Some("<file>...</file>"));
1178        assert_eq!(initial.as_deref(), Some("stdin-text<file>...</file>first"));
1179        assert_eq!(extra, vec!["second".to_string(), "third".to_string()]);
1180    }
1181
1182    #[test]
1183    fn build_initial_with_no_messages_uses_stdin_and_file_only() {
1184        let args = Args::default();
1185        let (initial, extra) =
1186            build_initial_message(&args, Some("only-stdin"), Some("<file>x</file>"));
1187        assert_eq!(initial.as_deref(), Some("only-stdin<file>x</file>"));
1188        assert!(extra.is_empty());
1189    }
1190
1191    #[test]
1192    fn build_initial_none_when_all_empty() {
1193        let args = Args::default();
1194        let (initial, extra) = build_initial_message(&args, None, None);
1195        assert!(initial.is_none());
1196        assert!(extra.is_empty());
1197    }
1198
1199    #[test]
1200    fn build_initial_shifts_only_first_message() {
1201        let mut args = Args::default();
1202        args.messages = vec!["a".into(), "b".into()];
1203        let (initial, extra) = build_initial_message(&args, None, None);
1204        assert_eq!(initial.as_deref(), Some("a"));
1205        assert_eq!(extra, vec!["b".to_string()]);
1206    }
1207
1208    #[test]
1209    fn process_file_args_attaches_supported_images() {
1210        let dir = tempfile::tempdir().unwrap();
1211        let path = dir.path().join("image.bin");
1212        let mut png = vec![137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13];
1213        png.extend_from_slice(b"IHDR");
1214        png.extend_from_slice(&[0; 13]);
1215        std::fs::write(&path, png).unwrap();
1216        let (text, images) = process_file_args(&[path], dir.path()).unwrap();
1217        assert!(text.is_empty());
1218        assert_eq!(images.len(), 1);
1219        assert_eq!(images[0].mime_type, "image/png");
1220        assert!(!images[0].data.is_empty());
1221    }
1222
1223    #[test]
1224    fn image_content_from_path_reports_supported_mime() {
1225        let dir = tempfile::tempdir().unwrap();
1226        let path = dir.path().join("drop.png");
1227        let mut png = vec![137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13];
1228        png.extend_from_slice(b"IHDR");
1229        png.extend_from_slice(&[0; 13]);
1230        std::fs::write(&path, png).unwrap();
1231        let image = image_content_from_path(&path).unwrap().unwrap();
1232        assert_eq!(image.mime_type, "image/png");
1233    }
1234}