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