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            if !args.json {
375                eprintln!("Checking provider usage. This can take up to a minute.");
376            }
377            let report = mcp::collect_usage(
378                &service,
379                CLIENT,
380                &args.metadata_providers,
381                None,
382                args.refresh,
383                true,
384                args.allow_identity,
385            )
386            .await;
387            service.close_client(CLIENT);
388            let report = report?;
389            if args.json {
390                println!("{report}");
391            } else {
392                print!(
393                    "{}",
394                    mcp::usage_terminal(&report, *chrono::Local::now().offset())
395                );
396            }
397            Ok(())
398        }
399        Action::Usage => {
400            let history = match args.home.clone() {
401                Some(home) => originlm_discovery::history::read_usage(
402                    &home,
403                    originlm_discovery::history::Limits::default(),
404                ),
405                None => {
406                    let environment = originlm_discovery::ScanEnvironment::from_process()?;
407                    originlm_discovery::history::read_usage_for_environment(
408                        &environment,
409                        originlm_discovery::history::Limits::default(),
410                    )
411                }
412            };
413            if args.json {
414                println!("{}", json!(history));
415            } else {
416                print!("{}", mcp::history_text(&json!(history)));
417            }
418            Ok(())
419        }
420        Action::Models => {
421            let environment = match args.home.clone() {
422                Some(home) => {
423                    let platform = if cfg!(windows) {
424                        originlm_discovery::HostPlatform::Windows
425                    } else if cfg!(target_os = "macos") {
426                        originlm_discovery::HostPlatform::Macos
427                    } else {
428                        originlm_discovery::HostPlatform::Linux
429                    };
430                    originlm_discovery::ScanEnvironment::for_home(home, platform)
431                }
432                None => originlm_discovery::ScanEnvironment::from_process()?,
433            };
434            let ollama_override = environment.overrides.get("OLLAMA_MODELS").cloned();
435            println!(
436                "{}",
437                json!({"providers": [
438                    originlm_discovery::local_models::read_ollama_models(
439                        &environment.home,
440                        ollama_override.as_deref(),
441                        8192,
442                    ),
443                    originlm_discovery::local_models::read_lmstudio_models(
444                        &environment.home,
445                        &originlm_discovery::local_models::lmstudio_config_home(&environment),
446                        8192,
447                    ),
448                ]})
449            );
450            Ok(())
451        }
452        Action::Serve if args.ipc.is_some() => {
453            let lifetime = if args.independent {
454                broker_cli::Lifetime::Independent {
455                    token_file: args.token_file.clone(),
456                    admin_token_file: args.admin_token_file.clone(),
457                    grants_file: args.grants_file.clone(),
458                    idle_timeout: args.idle_timeout_seconds.map(Duration::from_secs),
459                }
460            } else {
461                broker_cli::Lifetime::Parent
462            };
463            broker_cli::serve(
464                service,
465                args.ipc.as_deref().unwrap(),
466                policy,
467                grant,
468                lifetime,
469            )
470            .await
471        }
472        Action::Serve if args.http => {
473            if args.warm_metadata {
474                tokio::spawn(warm_metadata(service.clone(), policy.clone()));
475            }
476            let server = originlm_transports::http::start(
477                service,
478                originlm_transports::http::HttpOptions {
479                    port: args.port,
480                    policy,
481                    execution: grant,
482                    assets: args.assets,
483                },
484            )
485            .await?;
486            println!("OriginLM: {}", server.url);
487            println!(
488                "Pairing code (single use, expires in five minutes): {}",
489                server.pairing_code
490            );
491            tokio::signal::ctrl_c().await.map_err(|_| {
492                DomainError::new(
493                    ErrorCode::ProviderUnavailable,
494                    "Shutdown signal unavailable",
495                )
496            })?;
497            server.close().await;
498            Ok(())
499        }
500        Action::Mcp => {
501            service.register_client(mcp::CLIENT, policy)?;
502            let server = mcp::McpServer::new(
503                service.clone(),
504                args.metadata_providers.clone(),
505                args.home.clone(),
506                args.allow_identity,
507            );
508            let outcome = mcp::serve(tokio::io::stdin(), tokio::io::stdout(), server).await;
509            service.close_client(mcp::CLIENT);
510            outcome
511        }
512        Action::Serve => {
513            service.register_client("stdio-owner", policy)?;
514            if let Some(grant) = grant {
515                service.register_execution("stdio-owner", grant)?;
516            }
517            originlm_transports::serve_io(
518                tokio::io::stdin(),
519                tokio::io::stdout(),
520                service,
521                "stdio-owner".into(),
522                Default::default(),
523            )
524            .await
525        }
526        _ => Ok(()),
527    }
528}
529async fn install_provider(provider: &str, home: Option<&Path>) -> Result<()> {
530    if provider != "antigravity" {
531        return Err(DomainError::new(
532            ErrorCode::InvalidRequest,
533            "Only the Antigravity ACP server has a managed installer",
534        ));
535    }
536    let base = home
537        .map(|home| home.join(".gemini/antigravity-acp"))
538        .or_else(|| {
539            std::env::var_os("HOME")
540                .or_else(|| std::env::var_os("USERPROFILE"))
541                .map(PathBuf::from)
542                .map(|home| home.join(".gemini/antigravity-acp"))
543        })
544        .ok_or_else(|| {
545            DomainError::new(
546                ErrorCode::LocalAccessDenied,
547                "Home directory is unavailable",
548            )
549        })?;
550    let platform = match std::env::consts::OS {
551        "macos" => "darwin",
552        "windows" => "win32",
553        other => other,
554    };
555    let arch = match std::env::consts::ARCH {
556        "x86_64" => "x64",
557        "aarch64" => "arm64",
558        other => other,
559    };
560    let release =
561        originlm_adapters::native_clients::antigravity_install::release_for(platform, arch)
562            .ok_or_else(|| {
563                DomainError::new(
564                    ErrorCode::CapabilityUnsupported,
565                    "Antigravity is unavailable for this platform",
566                )
567            })?;
568    let path =
569        originlm_adapters::native_clients::antigravity_install::install(&base, release).await?;
570    println!(
571        "Antigravity ACP server {} installed at {}",
572        release.version,
573        path.display()
574    );
575    Ok(())
576}
577
578fn home_directory(home: Option<&Path>) -> Result<PathBuf> {
579    home.map(Path::to_path_buf)
580        .or_else(|| {
581            std::env::var_os("HOME")
582                .or_else(|| std::env::var_os("USERPROFILE"))
583                .map(PathBuf::from)
584        })
585        .ok_or_else(|| {
586            DomainError::new(
587                ErrorCode::LocalAccessDenied,
588                "Home directory is unavailable",
589            )
590        })
591}
592
593fn gemini_executable(home: &Path) -> Option<PathBuf> {
594    let tools = home.join(".t3/tools/gemini");
595    if let Ok(entries) = std::fs::read_dir(&tools) {
596        let mut candidates: Vec<_> = entries
597            .flatten()
598            .map(|entry| entry.path().join("npm/bin/gemini"))
599            .filter(|path| path.is_file())
600            .collect();
601        candidates.sort();
602        if let Some(path) = candidates.pop() {
603            return Some(path);
604        }
605    }
606    std::env::var_os("PATH").and_then(|path| {
607        std::env::split_paths(&path)
608            .map(|root| root.join("gemini"))
609            .find(|path| path.is_file())
610    })
611}
612
613async fn auth_provider(provider: &str, home: Option<&Path>) -> Result<()> {
614    let home = home_directory(home)?;
615    let (native, executable, profile_home) = match provider {
616        "antigravity" => {
617            let profile_home = home.join(".gemini/antigravity-acp");
618            let executable = profile_home.join(if cfg!(windows) {
619                "agy_acp_server.exe"
620            } else {
621                "agy_acp_server.par"
622            });
623            (
624                originlm_adapters::native_clients::config::NativeProvider::Antigravity,
625                executable,
626                profile_home,
627            )
628        }
629        "gemini_cli" => {
630            let executable = gemini_executable(&home).ok_or_else(|| {
631                DomainError::new(ErrorCode::RuntimeMissing, "Gemini CLI is not installed")
632            })?;
633            (
634                originlm_adapters::native_clients::config::NativeProvider::GeminiCli,
635                executable,
636                home.join(".gemini"),
637            )
638        }
639        _ => {
640            return Err(DomainError::new(
641                ErrorCode::InvalidRequest,
642                "Unsupported provider for interactive auth",
643            ));
644        }
645    };
646    if !executable.is_file() {
647        return Err(DomainError::new(
648            ErrorCode::RuntimeMissing,
649            "The provider runtime is not installed; run `originlm install antigravity` first",
650        ));
651    }
652    let scratch = tempfile::Builder::new()
653        .prefix("originlm-auth-")
654        .tempdir()
655        .map_err(|_| {
656            DomainError::new(
657                ErrorCode::ProviderUnavailable,
658                "Auth workspace is unavailable",
659            )
660        })?;
661    let url_file = scratch.path().join("authorization-url");
662    let browser = scratch.path().join(if cfg!(windows) {
663        "browser.cmd"
664    } else {
665        "browser.sh"
666    });
667    let script = if cfg!(windows) {
668        format!(
669            "@echo off\r\necho %~1>\"{}\"\r\n",
670            url_file.to_string_lossy()
671        )
672    } else {
673        format!(
674            "#!/bin/sh\nprintf '%s' \"$1\" > \"{}\"\n",
675            url_file.to_string_lossy()
676        )
677    };
678    std::fs::write(&browser, script).map_err(|_| {
679        DomainError::new(ErrorCode::LocalAccessDenied, "Auth helper is unavailable")
680    })?;
681    #[cfg(unix)]
682    {
683        use std::os::unix::fs::PermissionsExt;
684        std::fs::set_permissions(&browser, std::fs::Permissions::from_mode(0o700)).map_err(
685            |_| DomainError::new(ErrorCode::LocalAccessDenied, "Auth helper is unavailable"),
686        )?;
687    }
688    let profile = originlm_adapters::native_clients::config::NativeProfile {
689        id: provider.to_owned(),
690        label: provider.to_owned(),
691        provider: native,
692        executable,
693        profile_home,
694        auth_method: Some("oauth-personal".into()),
695        billing: None,
696    };
697    let prepared = originlm_adapters::native_clients::launch::prepare_auth(
698        &profile,
699        scratch.path(),
700        &browser,
701    )?;
702    let method = prepared
703        .auth_method
704        .clone()
705        .unwrap_or_else(|| "oauth-personal".into());
706    let spec = prepared.spec;
707    let _scratch = prepared.scratch;
708    let auth =
709        originlm_adapters::acp::authenticate(spec, provider.to_owned(), "auth".into(), &method);
710    tokio::pin!(auth);
711    let mut printed = false;
712    loop {
713        tokio::select! {
714            result = &mut auth => {
715                result?;
716                println!("AUTHENTICATED");
717                break;
718            }
719            _ = tokio::time::sleep(Duration::from_millis(100)) => {
720                if !printed
721                    && let Ok(url) = std::fs::read_to_string(&url_file)
722                    && !url.trim().is_empty()
723                {
724                    println!("AUTHORIZATION_URL={}", url.trim());
725                    printed = true;
726                }
727            }
728        }
729    }
730    Ok(())
731}
732
733/// Runs the `originlm` helper with this process's arguments, standard streams
734/// and environment, and returns its exit code.
735///
736/// This is the whole `originlm` executable. It is a library function so a Rust
737/// host can ship the helper as a binary of its own Cargo workspace, built with
738/// its own lockfile and toolchain, instead of downloading or separately
739/// compiling a prebuilt one:
740///
741/// ```no_run
742/// fn main() -> std::process::ExitCode {
743///     originlm_cli::run()
744/// }
745/// ```
746///
747/// Nothing happens until it is called: it parses the command line and only
748/// then performs the selected command.
749pub fn run() -> std::process::ExitCode {
750    run_from(std::env::args_os().skip(1))
751}
752
753/// [`run`] with explicit arguments (everything after the program name).
754///
755/// A host that has no separate helper executable can re-launch its own binary
756/// with a private first argument and hand the remaining arguments to the
757/// helper, so the helper still runs in a process of its own:
758///
759/// ```no_run
760/// fn main() -> std::process::ExitCode {
761///     let mut args = std::env::args_os().skip(1);
762///     if args.next().is_some_and(|first| first == "--originlm-helper") {
763///         return originlm_cli::run_from(args);
764///     }
765///     // ... the host application ...
766///     std::process::ExitCode::SUCCESS
767/// }
768/// ```
769pub fn run_from(arguments: impl IntoIterator<Item = std::ffi::OsString>) -> std::process::ExitCode {
770    let arguments: Vec<std::ffi::OsString> = arguments.into_iter().collect();
771    let result = (|| -> originlm_contracts::Result<u8> {
772        if arguments.first().is_some_and(|command| command == "image") {
773            return image_cli::run(arguments.into_iter().skip(1));
774        }
775        if arguments
776            .first()
777            .is_some_and(|command| command == "providers")
778        {
779            return providers_cli::run(arguments.into_iter().skip(1));
780        }
781        let args = Args::parse(arguments)?;
782        match args.action {
783            Action::Help => {
784                println!("{HELP}{}", providers_cli::HELP);
785                return Ok(0);
786            }
787            Action::Version => {
788                println!("originlm {}", env!("CARGO_PKG_VERSION"));
789                return Ok(0);
790            }
791            Action::Status => {
792                return status::run(args.ipc.clone(), args.token_file.clone(), args.json);
793            }
794            _ => {}
795        }
796        let runtime = tokio::runtime::Builder::new_multi_thread()
797            .worker_threads(2)
798            .max_blocking_threads(4)
799            .enable_all()
800            .build()
801            .map_err(|_| DomainError::new(ErrorCode::ProviderUnavailable, "Runtime unavailable"))?;
802        let result = runtime.block_on(execute(args));
803        // Tokio stdin uses a blocking thread; an idle pipe must not hold shutdown forever.
804        runtime.shutdown_timeout(Duration::from_millis(100));
805        result.map(|_| 0u8)
806    })();
807    match result {
808        Ok(code) => std::process::ExitCode::from(code),
809        Err(error) => {
810            eprintln!("{error}");
811            std::process::ExitCode::from(2)
812        }
813    }
814}