Skip to main content

oxi/cli/commands/
misc.rs

1//! Miscellaneous subcommand handlers: completions, install, update, commit,
2//! models, refresh, and the catalog builder used by `models` / `refresh`.
3
4use crate::store::settings::Settings;
5use anyhow::{Context, Result};
6use std::sync::Arc;
7
8/// Handle `oxi completions <bash|zsh|fish>` — print shell completion script.
9pub fn handle_completions(shell: &str) -> Result<()> {
10    use clap::CommandFactory;
11
12    let shell = match shell {
13        "bash" => clap_complete::Shell::Bash,
14        "zsh" => clap_complete::Shell::Zsh,
15        "fish" => clap_complete::Shell::Fish,
16        "elvish" => clap_complete::Shell::Elvish,
17        "powershell" => clap_complete::Shell::PowerShell,
18        _ => {
19            anyhow::bail!("Unknown shell: {shell}. Supported: bash, zsh, fish, elvish, powershell")
20        }
21    };
22
23    let mut cmd = crate::cli::CliArgs::command();
24    let name = cmd.get_name().to_string();
25    clap_complete::generate(shell, &mut cmd, name, &mut std::io::stdout());
26    Ok(())
27}
28
29/// Handle `oxi install <source>` — dispatch to `ext install` or `pkg install`.
30pub async fn handle_install(source: &str) -> Result<()> {
31    use crate::cli::{ExtCommands, PkgCommands};
32
33    // Local paths or npm: prefix → pkg install
34    if source.starts_with('.')
35        || source.starts_with('/')
36        || source.starts_with('~')
37        || source.starts_with("npm:")
38    {
39        super::pkg::handle_pkg(&PkgCommands::Install {
40            source: source.to_string(),
41        })?;
42    } else {
43        // GitHub repo spec (owner/repo) → ext install
44        super::ext::handle_ext(&ExtCommands::Install {
45            source: source.to_string(),
46            prerelease: false,
47        })
48        .await?;
49    }
50    Ok(())
51}
52
53/// Handle `oxi update [--check]` — check for and install updates.
54pub async fn handle_update(check: bool) -> Result<()> {
55    #[cfg(feature = "self-update")]
56    {
57        use self_update::cargo_crate_version;
58
59        let current = cargo_crate_version!();
60        println!("Current version: v{current}");
61
62        if check {
63            return Ok(());
64        }
65
66        // Use cargo install via `cargo install oxi-cli --force`
67        println!("Updating oxi...");
68        let status = tokio::process::Command::new("cargo")
69            .args(["install", "oxi-cli", "--force"])
70            .stdout(std::process::Stdio::inherit())
71            .stderr(std::process::Stdio::inherit())
72            .status()
73            .await?;
74
75        if !status.success() {
76            anyhow::bail!("Update failed: cargo install exited with {status}");
77        }
78
79        println!("✅ oxi updated successfully. Restart to use the new version.");
80        Ok(())
81    }
82
83    #[cfg(not(feature = "self-update"))]
84    {
85        let _ = check;
86        anyhow::bail!("Self-update is not available (compiled without `self-update` feature)");
87    }
88}
89
90/// Handle `oxi commit [--push] [--dry-run] [-c <context>]`.
91pub async fn handle_commit(push: bool, dry_run: bool, context: Option<&str>) -> Result<()> {
92    use oxi_agent::AgentTool;
93    use oxi_agent::tools::ToolContext;
94    use oxi_agent::tools::commit::CommitTool;
95    use serde_json::json;
96
97    // Check for staged changes
98    let diff_output = tokio::process::Command::new("git")
99        .args(["diff", "--cached"])
100        .output()
101        .await
102        .with_context(|| "Failed to run git diff --cached")?;
103
104    if diff_output.stdout.is_empty() && diff_output.stderr.is_empty() {
105        let has_changes = tokio::process::Command::new("git")
106            .args(["status", "--porcelain"])
107            .output()
108            .await
109            .with_context(|| "Failed to run git status")?;
110        if has_changes.stdout.is_empty() {
111            anyhow::bail!("Nothing to commit. Working tree is clean.");
112        }
113        anyhow::bail!(
114            "No staged changes. Use `git add` to stage files, or include unstaged changes with `git commit -a`."
115        );
116    }
117
118    // Run CommitTool (deterministic-only in CLI mode — no agent context)
119    let cwd = std::env::current_dir().context("Failed to get current directory")?;
120    let ctx = ToolContext::new(cwd.clone());
121    let tool = CommitTool::unconfigured();
122    let params = json!({
123        "dry_run": dry_run,
124        "push": push,
125        "context": context.unwrap_or(""),
126    });
127    let result = tool
128        .execute("cli", params, None, &ctx)
129        .await
130        .map_err(|e| anyhow::anyhow!("Commit tool failed: {e}"))?;
131
132    if dry_run {
133        println!("{}", result.output);
134        return Ok(());
135    }
136
137    // Actual commit: run `git commit -m "<message>"`
138    let message = result
139        .output
140        .lines()
141        .find(|l| {
142            l.starts_with("feat")
143                || l.starts_with("fix")
144                || l.starts_with("chore")
145                || l.starts_with("docs")
146                || l.starts_with("refactor")
147                || l.starts_with("test")
148                || l.starts_with("perf")
149                || l.starts_with("build")
150                || l.starts_with("ci")
151                || l.starts_with("style")
152                || l.starts_with("revert")
153        })
154        .unwrap_or("feat: commit")
155        .to_string();
156
157    let status = tokio::process::Command::new("git")
158        .args(["commit", "-m", &message])
159        .stdout(std::process::Stdio::inherit())
160        .stderr(std::process::Stdio::inherit())
161        .status()
162        .await
163        .with_context(|| "Failed to run git commit")?;
164
165    if !status.success() {
166        anyhow::bail!("Commit failed.\nProposed message was:\n{message}");
167    }
168
169    println!("Committed: {message}");
170
171    if push {
172        let push_status = tokio::process::Command::new("git")
173            .args(["push"])
174            .stdout(std::process::Stdio::inherit())
175            .stderr(std::process::Stdio::inherit())
176            .status()
177            .await
178            .with_context(|| "Failed to run git push")?;
179        if !push_status.success() {
180            anyhow::bail!("Commit succeeded but push failed.");
181        }
182        println!("Pushed.");
183    }
184
185    Ok(())
186}
187
188/// Handle `oxi refresh` — force-refresh the model catalog from models.dev.
189///
190/// Performs a conditional GET (ETag). The refreshed cache takes effect
191/// on the next process start (the in-memory catalog is immutable).
192///
193/// Uses the catalog port (`FileModelCatalog`) directly. The `App`'s
194/// catalog would be equivalent but this command runs standalone (no App).
195pub async fn handle_refresh() -> Result<()> {
196    use oxi_sdk::ModelCatalog;
197    use oxi_sdk::ports::catalog::RefreshOutcome;
198    use oxi_sdk::ports::fs::{CatalogConfig, FileModelCatalog};
199
200    let paths = crate::services::OxiPaths::default_paths()?;
201    let config = CatalogConfig {
202        cache_path: paths.home.join("cache").join("models-dev.json"),
203        etag_path: paths.home.join("cache").join("models-dev.json.etag"),
204        override_path: paths.home.join("catalog").join("overrides.toml"),
205        // Bypass the mtime window so we always issue a conditional GET.
206        mtime_window: std::time::Duration::ZERO,
207        ..Default::default()
208    };
209    // We don't run `init`'s optional pre-refresh — load SNAP+cache, then
210    // explicitly call refresh to issue a conditional GET.
211    let cat = FileModelCatalog::init(config).await?;
212
213    println!("Refreshing model catalog from models.dev...");
214    match cat.refresh().await? {
215        RefreshOutcome::Updated {
216            provider_count,
217            model_count,
218        } => {
219            println!(
220                "✓ Catalog updated: {} providers, {} models.",
221                provider_count, model_count
222            );
223        }
224        RefreshOutcome::Unchanged => {
225            println!("✓ Catalog already up to date.");
226        }
227        RefreshOutcome::Offline { reason } => {
228            println!("⚠ Catalog refresh skipped (offline: {reason}).");
229        }
230        RefreshOutcome::Failed { reason } => {
231            println!("✗ Catalog refresh failed: {reason}.");
232        }
233    }
234    Ok(())
235}
236
237/// Handle `oxi models [--provider <name>]`
238pub async fn handle_models(provider: &Option<String>) -> Result<()> {
239    use oxi_sdk::ModelCatalog;
240
241    // If a custom provider is specified, also try to fetch models dynamically
242    if let Some(ref provider_name) = *provider {
243        let settings = Settings::load().unwrap_or_default();
244        if let Some(cp) = settings
245            .custom_providers
246            .iter()
247            .find(|cp| cp.name == *provider_name)
248        {
249            let auth = crate::store::auth_storage::shared_auth_storage();
250            let api_key = auth.get_api_key(&cp.name);
251            if let Some(ref key) = api_key {
252                match oxi_sdk::fetch_models_blocking(&cp.base_url, key) {
253                    Ok(model_ids) => {
254                        let api_type = match cp.api.to_lowercase().as_str() {
255                            "openai-responses" | "responses" => oxi_sdk::Api::OpenAiResponses,
256                            _ => oxi_sdk::Api::OpenAiCompletions,
257                        };
258                        for model_id in &model_ids {
259                            let model = oxi_sdk::Model {
260                                id: model_id.clone(),
261                                name: model_id.clone(),
262                                api: api_type,
263                                provider: cp.name.clone(),
264                                base_url: cp.base_url.clone(),
265                                reasoning: false,
266                                input: vec![oxi_sdk::InputModality::Text],
267                                cost: oxi_sdk::Cost::default(),
268                                context_window: 128_000,
269                                max_tokens: 8_192,
270                                headers: Default::default(),
271                                compat: None,
272                            };
273                            oxi_sdk::register_model(model);
274                        }
275                        if model_ids.is_empty() {
276                            println!("No models found for provider '{}'.", provider_name);
277                        } else {
278                            println!(
279                                "Models from '{}' ({} fetched):",
280                                provider_name,
281                                model_ids.len()
282                            );
283                            for id in &model_ids {
284                                println!("  {}", id);
285                            }
286                        }
287                        return Ok(());
288                    }
289                    Err(e) => {
290                        eprintln!(
291                            "[oxi] warning: failed to resolve models for {}: {}",
292                            provider_name, e
293                        );
294                    }
295                }
296            } else {
297                eprintln!(
298                    "[oxi] API key not set for provider '{}' (expected: {})",
299                    provider_name, cp.api_key_env
300                );
301            }
302        }
303
304        // Fallback: show catalog models for this provider via the port.
305        let cat = build_catalog_for_cli().await?;
306        let models = cat.list_models(provider_name).await?;
307        if models.is_empty() {
308            println!(
309                "No models found for provider '{}' (static or dynamic).",
310                provider_name
311            );
312        } else {
313            println!(
314                "Models for provider '{}' ({}):",
315                provider_name,
316                models.len()
317            );
318            for m in models {
319                println!("  {} ({})", m.model_id, m.name);
320            }
321        }
322        return Ok(());
323    }
324
325    // No provider filter: show everything via the catalog port.
326    let cat = build_catalog_for_cli().await?;
327    let all = cat.search("").await?;
328    let count = cat.model_count().await?;
329    println!("Available models ({} total):", count);
330    for entry in &all {
331        println!("  {}/{} — {}", entry.provider, entry.model_id, entry.name);
332    }
333    Ok(())
334}
335
336/// Build a catalog port for `oxi models` / `oxi refresh` standalone commands.
337///
338/// These commands run without an `App`; we construct a fresh `FileModelCatalog`
339/// rooted at the conventional oxi home directory. The result is a short-lived
340/// catalog used only for this one command.
341pub(crate) async fn build_catalog_for_cli() -> Result<Arc<oxi_sdk::FileModelCatalog>> {
342    use oxi_sdk::ports::fs::CatalogConfig;
343    let paths = crate::services::OxiPaths::default_paths()?;
344    let config = CatalogConfig {
345        cache_path: paths.home.join("cache").join("models-dev.json"),
346        etag_path: paths.home.join("cache").join("models-dev.json.etag"),
347        override_path: paths.home.join("catalog").join("overrides.toml"),
348        // Don't trigger a refresh during `oxi models`; users who want fresh
349        // data should run `oxi refresh` first.
350        fetch_enabled: false,
351        ..Default::default()
352    };
353    Ok(oxi_sdk::FileModelCatalog::init(config).await?)
354}