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