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