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