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