Skip to main content

originlm_cli/
lib.rs

1//! The OriginLM native helper as a library: [`run`] is the `originlm`
2//! executable's entry point. The `originlm` binary of this crate only calls it.
3mod args;
4mod inventory;
5use inventory::source;
6use originlm_service::InventorySource;
7mod broker_cli;
8mod endpoints;
9mod host;
10mod image_cli;
11mod native_profiles;
12mod status;
13use args::{Action, Args};
14use originlm_contracts::{DomainError, ErrorCode, Result};
15use serde_json::json;
16use std::{
17    path::{Path, PathBuf},
18    sync::Arc,
19    time::Duration,
20};
21
22const HELP: &str = "OriginLM - native discovery and SDK helper
23Usage:
24  originlm serve --ipc LOCAL_ADDRESS [--allow-passive-discovery]
25  originlm serve --ipc LOCAL_ADDRESS --independent (--token-file ABSOLUTE_PATH | --grants-file ABSOLUTE_PATH)
26      [--admin-token-file ABSOLUTE_PATH] [--idle-timeout SECONDS] [--allow-passive-discovery]
27      [--os-notifications (requires an os-notifications build)]
28  originlm connect --ipc LOCAL_ADDRESS
29  originlm scan --json [--include-locations] [--home ABSOLUTE_DIRECTORY] [--executable-only-provider PROVIDER]
30      --include-locations adds this host's private executable and profile paths.
31  originlm usage --json [--home ABSOLUTE_DIRECTORY]
32      Reads bounded Claude Code and Codex session-history token totals. No prompt,
33      tool output or credential is read; malformed or oversized input is reported.
34  originlm models --json [--home ABSOLUTE_DIRECTORY]
35      Lists on-disk Ollama manifests and LM Studio GGUF files. Reports only ids,
36      names, sizes and a coarse format; no capability or quantization guesses.
37  originlm status [--json] [--ipc ADDRESS] [--token-file ABSOLUTE_FILE]
38      Prints the running helper, its providers and connected apps.
39      Exit: 0 running, 3 not running, 4 credential rejected.
40  originlm serve --stdio [--allow-passive-discovery] [--allow-identity] [--allow-codex-metadata] [--home ABSOLUTE_DIRECTORY]
41  originlm serve --http --port 4499 --assets ABSOLUTE_DIST_DIRECTORY
42      [--allow-passive-discovery] [--allow-codex-metadata]
43      [--allow-codex-execution --workspace ABSOLUTE_DIRECTORY]
44      [--allow-writes] [--allow-native-policy] [--review-native-requests] [--allow-paid-options]
45      [--warm-metadata] [--no-metadata-cache]
46  Reusable provider grants: --allow-metadata PROVIDER --allow-execution PROVIDER
47  --allow-usage cursor additionally reads Cursor's own dashboard allowances with the
48  session token stored by Cursor; the token is never logged, serialized or exported.
49  Kiro is metadata-only in this release: --allow-metadata kiro reads the CLI version,
50  whoami sign-in state and account model list.
51  --executable-only-provider PROVIDER may repeat for known discovery providers; retains private executable candidates without publishing their profiles or routes.
52  Execution providers: codex, claude_code, gemini_cli, antigravity, grok, ollama, lmstudio, openai_api, anthropic_api, gemini_api, xai_api, compatible_api, opencode, muse.
53  --endpoints ABSOLUTE_JSON registers local or API endpoints without contacting them.
54  --native-profiles ABSOLUTE_JSON explicitly registers Gemini CLI, Antigravity ACP, or Grok native profiles; the file contains paths/labels, never tokens.
55  --chatgpt-app-name NAME opts in a separate managed Codex profile and SIWC auth RPCs; grant --allow-metadata codex_managed to use them.
56  --billing-declarations ABSOLUTE_JSON declares billing for discovered connections whose provider leaves it unknown; recorded as user-supplied evidence, never verification.
57  originlm image --definition
58      Prints the generate_image tool definition. Contacts nothing.
59  originlm image --assets ABSOLUTE_DIRECTORY --prompt TEXT --allow-paid
60      [--size WIDTHxHEIGHT] [--aspect W:H] [--style TEXT] [--reference RELATIVE_PATH] [--count 1-4]
61      Generates images through ORIGINLM_IMAGE_ROUTE or the installed Codex login and
62      prints JSON holding images or a typed error. Exit: 0 generated, 1 tool error.
63  originlm --version
64
65Metadata observations are kept in the broker-owned state directory (state.db,
66no account identity, owner-only permissions) and the last ready snapshot is
67reloaded after a restart as stale-while-revalidate data; --no-metadata-cache
68turns that off. A parent-owned broker stops when its trusted control input
69closes. An --independent broker owns its lifetime, publishes a reusable
70owner-only token file for approved applications, and can stop after an idle
71timeout. --grants-file instead mints a distinct reusable credential and stable
72app identity for each manifest entry, so ordinary applications never share the
73owner credential or each other's account scope; an administrator can revoke one
74application and its grant live. It never silently replaces a live listener.
75Serving never scans on startup unless the host passes --warm-metadata (HTTP only,
76with --allow-passive-discovery and a metadata provider grant): the helper then runs
77one passive scan and the already-permitted metadata checks in the background, so
78results are ready when a browser pairs. Providers are checked concurrently; the
79profiles of one provider are checked in order. --allow-identity reveals the signed-in account label (email) that the provider reported; without it the projection withholds identity. --allow-passive-discovery explicitly
80authorizes metadata-only scans requested by the owning SDK. No credentials or inference.
81--allow-codex-metadata separately permits explicit connections.probe requests
82through the installed Codex client. This may read its login and contact its
83account/catalog/usage services, but never starts threads or model generation.
84--allow-codex-execution authorizes explicit session/turn requests, never generation
85at startup. A --workspace is required; its public name is default. Writes, native-policy
86tool access, native approval review, and paid options each require their own flag.
87Native policy delegates tool and filesystem/network limits to the installed client;
88it is not a Kit sandbox. HTTP is loopback-only
89and requires explicit single-use browser pairing. No tokens are printed.
90--home isolates all discovery roots and excludes the inherited PATH/overrides.";
91
92/// Host-initiated warm-up (opt-in). It uses only what the host already permitted for browsers:
93/// one passive scan, then metadata checks. Different providers run concurrently; the profiles of
94/// one provider run in order, because a status check can refresh that provider's own credentials
95/// and two checks must never race that refresh. Failures are ignored: the browser can still check.
96async fn warm_metadata(
97    service: Arc<originlm_service::NativeService>,
98    policy: originlm_core::ClientPolicy,
99) {
100    const HOST: &str = "host-warmup";
101    if service.register_client(HOST, policy).is_err() {
102        return;
103    }
104    let listed = match service
105        .handle(HOST, "discovery.refresh", json!({"level": "passive"}))
106        .await
107    {
108        Ok(_) => service.handle(HOST, "connections.list", json!({})).await,
109        Err(error) => Err(error),
110    };
111    let mut by_provider: std::collections::BTreeMap<String, Vec<String>> = Default::default();
112    if let Some(connections) = listed.ok().as_ref().and_then(|value| value.as_array()) {
113        for connection in connections {
114            if let (Some(provider), Some(id)) =
115                (connection["providerId"].as_str(), connection["id"].as_str())
116            {
117                by_provider
118                    .entry(provider.to_owned())
119                    .or_default()
120                    .push(id.to_owned());
121            }
122        }
123    }
124    let mut checks = tokio::task::JoinSet::new();
125    for ids in by_provider.into_values() {
126        let service = service.clone();
127        checks.spawn(async move {
128            for id in ids {
129                let _ = service
130                    .handle(HOST, "connections.probe", json!({"connectionId": id}))
131                    .await;
132            }
133        });
134    }
135    while checks.join_next().await.is_some() {}
136    service.close_client(HOST);
137}
138
139async fn execute(args: Args) -> Result<()> {
140    if let Action::Install(provider) = &args.action {
141        return install_provider(provider, args.home.as_deref()).await;
142    }
143    if let Action::Auth(provider) = &args.action {
144        return auth_provider(provider, args.home.as_deref()).await;
145    }
146    if matches!(args.action, Action::Connect) {
147        return broker_cli::connect(args.ipc.as_deref().unwrap()).await;
148    }
149    let registry = Arc::new(endpoints::load(args.endpoints.as_deref())?);
150    let state_dir = host::default_state_dir(args.home.as_deref());
151    let chatgpt = args
152        .chatgpt_app_name
153        .clone()
154        .map(|name| {
155            let root = state_dir.as_ref().ok_or_else(|| {
156                DomainError::new(
157                    ErrorCode::LocalAccessDenied,
158                    "Managed ChatGPT state directory is unavailable",
159                )
160            })?;
161            let manager =
162                originlm_chatgpt_auth::AuthManager::new(root.join("chatgpt-auth"), name.clone())
163                    .map_err(|_| {
164                        DomainError::new(
165                            ErrorCode::ProviderUnavailable,
166                            "Managed ChatGPT state is unavailable",
167                        )
168                    })?;
169            Ok::<_, DomainError>((Arc::new(manager), name))
170        })
171        .transpose()?;
172    let mut native = native_profiles::load(args.native_profiles.as_deref())?;
173    host::validate_executable_only_sources(&args, &registry, &native)?;
174    native.browser_blocker = native_profiles::packaged_browser_blocker();
175    let native = Arc::new(native);
176    let declarations = Arc::new(native_profiles::load_declarations(
177        args.billing_declarations.as_deref(),
178    )?);
179    let original = source(args.home.clone(), args.executable_only_providers.clone());
180    let scan_registry = registry.clone();
181    let scan_native = native.clone();
182    let managed_root = chatgpt.as_ref().and(state_dir.as_ref()).cloned();
183    let inventory: InventorySource = Arc::new(move |cancel| {
184        let mut result = original(cancel)?;
185        scan_registry.inject(&mut result);
186        scan_native.inject(&mut result);
187        if let Some(root) = &managed_root {
188            originlm_adapters::native_clients::config::inject_managed_codex(&mut result, root);
189        }
190        Ok(result)
191    });
192    let service = originlm_kit::build_service_with_cursor_usage(
193        inventory,
194        args.allow_execution,
195        registry,
196        native,
197        declarations,
198        state_dir,
199        chatgpt,
200        args.usage_providers.contains("cursor"),
201    );
202    if let Some(home) = args.home.clone().or_else(|| {
203        originlm_discovery::ScanEnvironment::from_process()
204            .ok()
205            .map(|environment| environment.home)
206    }) {
207        service.set_usage_home(home);
208    }
209    #[cfg(feature = "os-notifications")]
210    if args.os_notifications {
211        service.install_os_notifications();
212    }
213    service.enable_autonomous_refresh(args.metadata_providers.clone());
214    service.enable_inventory_refresh(args.allow_passive);
215    if matches!(args.action, Action::Serve)
216        && !args.no_metadata_cache
217        && let Some(directory) = host::default_state_dir(args.home.as_deref())
218        && let Err(error) = service.enable_state_store(directory.join("state.db"))
219    {
220        eprintln!("storage: {error}");
221    }
222    if matches!(args.action, Action::Serve) {
223        service.start_background_tasks();
224    }
225    let policy = host::policy(&args);
226    let grant = host::execution_grant(&args);
227    match args.action {
228        Action::Scan => {
229            service.register_client("stdio-owner", policy)?;
230            service
231                .handle(
232                    "stdio-owner",
233                    "discovery.refresh",
234                    json!({"level":"passive"}),
235                )
236                .await?;
237            let snapshot = service
238                .handle("stdio-owner", "snapshot.get", json!({}))
239                .await?;
240            if args.include_locations {
241                let result = inventory::scan(
242                    &args.home,
243                    args.executable_only_providers.clone(),
244                    &std::sync::atomic::AtomicBool::new(false),
245                )?;
246                let locations: Vec<_> = result
247                    .locations
248                    .iter()
249                    .map(|(connection, located)| {
250                        let resolved = located
251                            .executable_identity
252                            .as_ref()
253                            .map(|identity| identity.resolved.to_string_lossy().into_owned());
254                        json!({
255                            "connectionId": connection,
256                            "providerId": located.provider_id,
257                            "profileHome": located.profile_home.to_string_lossy(),
258                            "executable": located.executable.as_ref().map(|path| path.to_string_lossy().into_owned()),
259                            "resolvedExecutable": resolved,
260                        })
261                    })
262                    .collect();
263                let found: std::collections::BTreeSet<&str> = result
264                    .snapshot
265                    .connections
266                    .iter()
267                    .map(|connection| connection.provider_id.as_str())
268                    .collect();
269                let versions = if args.probe_versions {
270                    let mut versions = serde_json::Map::new();
271                    for (connection, located) in &result.locations {
272                        let Some(executable) = &located.executable else {
273                            continue;
274                        };
275                        let extension = executable
276                            .extension()
277                            .and_then(|extension| extension.to_str())
278                            .unwrap_or("")
279                            .to_ascii_lowercase();
280                        let mut command =
281                            if cfg!(windows) && matches!(extension.as_str(), "cmd" | "bat") {
282                                // npm installs .cmd shims; the bounded process layer
283                                // refuses them, but this flag is an explicit local
284                                // version probe, never a session launch.
285                                let mut command = tokio::process::Command::new("cmd");
286                                command.args(["/D", "/C"]).arg(executable);
287                                command
288                            } else {
289                                tokio::process::Command::new(executable)
290                            };
291                        command.arg("--version").kill_on_drop(true);
292                        let output = tokio::time::timeout(
293                            std::time::Duration::from_secs(15),
294                            command.output(),
295                        )
296                        .await;
297                        let value = match output {
298                            Ok(Ok(output)) => {
299                                let text = String::from_utf8_lossy(&output.stdout);
300                                json!({
301                                    "ok": output.status.success(),
302                                    "output": text.lines().next().unwrap_or("").chars().take(200).collect::<String>(),
303                                })
304                            }
305                            _ => json!({"ok": false, "output": ""}),
306                        };
307                        versions.insert(connection.clone(), value);
308                    }
309                    Some(versions)
310                } else {
311                    None
312                };
313                let checked: Vec<_> = originlm_discovery::definitions()
314                    .iter()
315                    .map(|definition| {
316                        json!({
317                            "providerId": definition.id,
318                            "name": definition.name,
319                            "status": if found.contains(definition.id) { "found" } else { "not_found" },
320                        })
321                    })
322                    .collect();
323                println!(
324                    "{}",
325                    json!({
326                        "snapshot": snapshot,
327                        "locations": locations,
328                        "metadataProbes": result.metadata_probes,
329                        "checkedProviders": checked,
330                        "versions": versions,
331                    })
332                );
333            } else {
334                println!("{snapshot}");
335            }
336            Ok(())
337        }
338        Action::Usage => {
339            let history = match args.home.clone() {
340                Some(home) => originlm_discovery::history::read_usage(
341                    &home,
342                    originlm_discovery::history::Limits::default(),
343                ),
344                None => {
345                    let environment = originlm_discovery::ScanEnvironment::from_process()?;
346                    originlm_discovery::history::read_usage_for_environment(
347                        &environment,
348                        originlm_discovery::history::Limits::default(),
349                    )
350                }
351            };
352            println!("{}", json!(history));
353            Ok(())
354        }
355        Action::Models => {
356            let environment = match args.home.clone() {
357                Some(home) => {
358                    let platform = if cfg!(windows) {
359                        originlm_discovery::HostPlatform::Windows
360                    } else if cfg!(target_os = "macos") {
361                        originlm_discovery::HostPlatform::Macos
362                    } else {
363                        originlm_discovery::HostPlatform::Linux
364                    };
365                    originlm_discovery::ScanEnvironment::for_home(home, platform)
366                }
367                None => originlm_discovery::ScanEnvironment::from_process()?,
368            };
369            let ollama_override = environment.overrides.get("OLLAMA_MODELS").cloned();
370            println!(
371                "{}",
372                json!({"providers": [
373                    originlm_discovery::local_models::read_ollama_models(
374                        &environment.home,
375                        ollama_override.as_deref(),
376                        8192,
377                    ),
378                    originlm_discovery::local_models::read_lmstudio_models(
379                        &environment.home,
380                        &originlm_discovery::local_models::lmstudio_config_home(&environment),
381                        8192,
382                    ),
383                ]})
384            );
385            Ok(())
386        }
387        Action::Serve if args.ipc.is_some() => {
388            let lifetime = if args.independent {
389                broker_cli::Lifetime::Independent {
390                    token_file: args.token_file.clone(),
391                    admin_token_file: args.admin_token_file.clone(),
392                    grants_file: args.grants_file.clone(),
393                    idle_timeout: args.idle_timeout_seconds.map(Duration::from_secs),
394                }
395            } else {
396                broker_cli::Lifetime::Parent
397            };
398            broker_cli::serve(
399                service,
400                args.ipc.as_deref().unwrap(),
401                policy,
402                grant,
403                lifetime,
404            )
405            .await
406        }
407        Action::Serve if args.http => {
408            if args.warm_metadata {
409                tokio::spawn(warm_metadata(service.clone(), policy.clone()));
410            }
411            let server = originlm_transports::http::start(
412                service,
413                originlm_transports::http::HttpOptions {
414                    port: args.port,
415                    policy,
416                    execution: grant,
417                    assets: args.assets,
418                },
419            )
420            .await?;
421            println!("OriginLM: {}", server.url);
422            println!(
423                "Pairing code (single use, expires in five minutes): {}",
424                server.pairing_code
425            );
426            tokio::signal::ctrl_c().await.map_err(|_| {
427                DomainError::new(
428                    ErrorCode::ProviderUnavailable,
429                    "Shutdown signal unavailable",
430                )
431            })?;
432            server.close().await;
433            Ok(())
434        }
435        Action::Serve => {
436            service.register_client("stdio-owner", policy)?;
437            if let Some(grant) = grant {
438                service.register_execution("stdio-owner", grant)?;
439            }
440            originlm_transports::serve_io(
441                tokio::io::stdin(),
442                tokio::io::stdout(),
443                service,
444                "stdio-owner".into(),
445                Default::default(),
446            )
447            .await
448        }
449        _ => Ok(()),
450    }
451}
452async fn install_provider(provider: &str, home: Option<&Path>) -> Result<()> {
453    if provider != "antigravity" {
454        return Err(DomainError::new(
455            ErrorCode::InvalidRequest,
456            "Only the Antigravity ACP server has a managed installer",
457        ));
458    }
459    let base = home
460        .map(|home| home.join(".gemini/antigravity-acp"))
461        .or_else(|| {
462            std::env::var_os("HOME")
463                .or_else(|| std::env::var_os("USERPROFILE"))
464                .map(PathBuf::from)
465                .map(|home| home.join(".gemini/antigravity-acp"))
466        })
467        .ok_or_else(|| {
468            DomainError::new(
469                ErrorCode::LocalAccessDenied,
470                "Home directory is unavailable",
471            )
472        })?;
473    let platform = match std::env::consts::OS {
474        "macos" => "darwin",
475        "windows" => "win32",
476        other => other,
477    };
478    let arch = match std::env::consts::ARCH {
479        "x86_64" => "x64",
480        "aarch64" => "arm64",
481        other => other,
482    };
483    let release =
484        originlm_adapters::native_clients::antigravity_install::release_for(platform, arch)
485            .ok_or_else(|| {
486                DomainError::new(
487                    ErrorCode::CapabilityUnsupported,
488                    "Antigravity is unavailable for this platform",
489                )
490            })?;
491    let path =
492        originlm_adapters::native_clients::antigravity_install::install(&base, release).await?;
493    println!(
494        "Antigravity ACP server {} installed at {}",
495        release.version,
496        path.display()
497    );
498    Ok(())
499}
500
501fn home_directory(home: Option<&Path>) -> Result<PathBuf> {
502    home.map(Path::to_path_buf)
503        .or_else(|| {
504            std::env::var_os("HOME")
505                .or_else(|| std::env::var_os("USERPROFILE"))
506                .map(PathBuf::from)
507        })
508        .ok_or_else(|| {
509            DomainError::new(
510                ErrorCode::LocalAccessDenied,
511                "Home directory is unavailable",
512            )
513        })
514}
515
516fn gemini_executable(home: &Path) -> Option<PathBuf> {
517    let tools = home.join(".t3/tools/gemini");
518    if let Ok(entries) = std::fs::read_dir(&tools) {
519        let mut candidates: Vec<_> = entries
520            .flatten()
521            .map(|entry| entry.path().join("npm/bin/gemini"))
522            .filter(|path| path.is_file())
523            .collect();
524        candidates.sort();
525        if let Some(path) = candidates.pop() {
526            return Some(path);
527        }
528    }
529    std::env::var_os("PATH").and_then(|path| {
530        std::env::split_paths(&path)
531            .map(|root| root.join("gemini"))
532            .find(|path| path.is_file())
533    })
534}
535
536async fn auth_provider(provider: &str, home: Option<&Path>) -> Result<()> {
537    let home = home_directory(home)?;
538    let (native, executable, profile_home) = match provider {
539        "antigravity" => {
540            let profile_home = home.join(".gemini/antigravity-acp");
541            let executable = profile_home.join(if cfg!(windows) {
542                "agy_acp_server.exe"
543            } else {
544                "agy_acp_server.par"
545            });
546            (
547                originlm_adapters::native_clients::config::NativeProvider::Antigravity,
548                executable,
549                profile_home,
550            )
551        }
552        "gemini_cli" => {
553            let executable = gemini_executable(&home).ok_or_else(|| {
554                DomainError::new(ErrorCode::RuntimeMissing, "Gemini CLI is not installed")
555            })?;
556            (
557                originlm_adapters::native_clients::config::NativeProvider::GeminiCli,
558                executable,
559                home.join(".gemini"),
560            )
561        }
562        _ => {
563            return Err(DomainError::new(
564                ErrorCode::InvalidRequest,
565                "Unsupported provider for interactive auth",
566            ));
567        }
568    };
569    if !executable.is_file() {
570        return Err(DomainError::new(
571            ErrorCode::RuntimeMissing,
572            "The provider runtime is not installed; run `originlm install antigravity` first",
573        ));
574    }
575    let scratch = tempfile::Builder::new()
576        .prefix("originlm-auth-")
577        .tempdir()
578        .map_err(|_| {
579            DomainError::new(
580                ErrorCode::ProviderUnavailable,
581                "Auth workspace is unavailable",
582            )
583        })?;
584    let url_file = scratch.path().join("authorization-url");
585    let browser = scratch.path().join(if cfg!(windows) {
586        "browser.cmd"
587    } else {
588        "browser.sh"
589    });
590    let script = if cfg!(windows) {
591        format!(
592            "@echo off\r\necho %~1>\"{}\"\r\n",
593            url_file.to_string_lossy()
594        )
595    } else {
596        format!(
597            "#!/bin/sh\nprintf '%s' \"$1\" > \"{}\"\n",
598            url_file.to_string_lossy()
599        )
600    };
601    std::fs::write(&browser, script).map_err(|_| {
602        DomainError::new(ErrorCode::LocalAccessDenied, "Auth helper is unavailable")
603    })?;
604    #[cfg(unix)]
605    {
606        use std::os::unix::fs::PermissionsExt;
607        std::fs::set_permissions(&browser, std::fs::Permissions::from_mode(0o700)).map_err(
608            |_| DomainError::new(ErrorCode::LocalAccessDenied, "Auth helper is unavailable"),
609        )?;
610    }
611    let profile = originlm_adapters::native_clients::config::NativeProfile {
612        id: provider.to_owned(),
613        label: provider.to_owned(),
614        provider: native,
615        executable,
616        profile_home,
617        auth_method: Some("oauth-personal".into()),
618        billing: None,
619    };
620    let prepared = originlm_adapters::native_clients::launch::prepare_auth(
621        &profile,
622        scratch.path(),
623        &browser,
624    )?;
625    let method = prepared
626        .auth_method
627        .clone()
628        .unwrap_or_else(|| "oauth-personal".into());
629    let spec = prepared.spec;
630    let _scratch = prepared.scratch;
631    let auth =
632        originlm_adapters::acp::authenticate(spec, provider.to_owned(), "auth".into(), &method);
633    tokio::pin!(auth);
634    let mut printed = false;
635    loop {
636        tokio::select! {
637            result = &mut auth => {
638                result?;
639                println!("AUTHENTICATED");
640                break;
641            }
642            _ = tokio::time::sleep(Duration::from_millis(100)) => {
643                if !printed
644                    && let Ok(url) = std::fs::read_to_string(&url_file)
645                    && !url.trim().is_empty()
646                {
647                    println!("AUTHORIZATION_URL={}", url.trim());
648                    printed = true;
649                }
650            }
651        }
652    }
653    Ok(())
654}
655
656/// Runs the `originlm` helper with this process's arguments, standard streams
657/// and environment, and returns its exit code.
658///
659/// This is the whole `originlm` executable. It is a library function so a Rust
660/// host can ship the helper as a binary of its own Cargo workspace, built with
661/// its own lockfile and toolchain, instead of downloading or separately
662/// compiling a prebuilt one:
663///
664/// ```no_run
665/// fn main() -> std::process::ExitCode {
666///     originlm_cli::run()
667/// }
668/// ```
669///
670/// Nothing happens until it is called: it parses the command line and only
671/// then performs the selected command.
672pub fn run() -> std::process::ExitCode {
673    run_from(std::env::args_os().skip(1))
674}
675
676/// [`run`] with explicit arguments (everything after the program name).
677///
678/// A host that has no separate helper executable can re-launch its own binary
679/// with a private first argument and hand the remaining arguments to the
680/// helper, so the helper still runs in a process of its own:
681///
682/// ```no_run
683/// fn main() -> std::process::ExitCode {
684///     let mut args = std::env::args_os().skip(1);
685///     if args.next().is_some_and(|first| first == "--originlm-helper") {
686///         return originlm_cli::run_from(args);
687///     }
688///     // ... the host application ...
689///     std::process::ExitCode::SUCCESS
690/// }
691/// ```
692pub fn run_from(arguments: impl IntoIterator<Item = std::ffi::OsString>) -> std::process::ExitCode {
693    let arguments: Vec<std::ffi::OsString> = arguments.into_iter().collect();
694    let result = (|| -> originlm_contracts::Result<u8> {
695        if arguments.first().is_some_and(|command| command == "image") {
696            return image_cli::run(arguments.into_iter().skip(1));
697        }
698        let args = Args::parse(arguments)?;
699        match args.action {
700            Action::Help => {
701                println!("{HELP}");
702                return Ok(0);
703            }
704            Action::Version => {
705                println!("originlm {}", env!("CARGO_PKG_VERSION"));
706                return Ok(0);
707            }
708            Action::Status => {
709                return status::run(args.ipc.clone(), args.token_file.clone(), args.json);
710            }
711            _ => {}
712        }
713        let runtime = tokio::runtime::Builder::new_multi_thread()
714            .worker_threads(2)
715            .max_blocking_threads(4)
716            .enable_all()
717            .build()
718            .map_err(|_| DomainError::new(ErrorCode::ProviderUnavailable, "Runtime unavailable"))?;
719        let result = runtime.block_on(execute(args));
720        // Tokio stdin uses a blocking thread; an idle pipe must not hold shutdown forever.
721        runtime.shutdown_timeout(Duration::from_millis(100));
722        result.map(|_| 0u8)
723    })();
724    match result {
725        Ok(code) => std::process::ExitCode::from(code),
726        Err(error) => {
727            eprintln!("{error}");
728            std::process::ExitCode::from(2)
729        }
730    }
731}