opencrabs 0.3.25

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
use crossterm::event::{KeyCode, KeyEvent};

use super::types::*;
use super::wizard::OnboardingWizard;

impl OnboardingWizard {
    pub(super) fn handle_voice_setup_key(&mut self, event: KeyEvent) -> WizardAction {
        super::voice::handle_key(self, event)
    }

    pub(super) fn handle_image_setup_key(&mut self, event: KeyEvent) -> WizardAction {
        let either_enabled = self.image_vision_enabled || self.image_generation_enabled;

        match self.image_field {
            ImageField::VisionToggle => match event.code {
                KeyCode::Char(' ') | KeyCode::Up | KeyCode::Down => {
                    self.image_vision_enabled = !self.image_vision_enabled;
                }
                KeyCode::Tab | KeyCode::Enter => {
                    self.image_field = ImageField::GenerationToggle;
                }
                _ => {}
            },
            ImageField::GenerationToggle => match event.code {
                KeyCode::Char(' ') | KeyCode::Up | KeyCode::Down => {
                    self.image_generation_enabled = !self.image_generation_enabled;
                }
                KeyCode::BackTab => {
                    self.image_field = ImageField::VisionToggle;
                }
                KeyCode::Tab | KeyCode::Enter => {
                    if self.image_generation_enabled {
                        self.image_field = ImageField::GenerationModel;
                    } else if either_enabled {
                        self.image_field = ImageField::ApiKey;
                    } else {
                        self.next_step();
                    }
                }
                _ => {}
            },
            ImageField::GenerationModel => match event.code {
                KeyCode::Char(c) => {
                    self.image_generation_model_input.push(c);
                }
                KeyCode::Backspace => {
                    self.image_generation_model_input.pop();
                }
                KeyCode::BackTab => {
                    self.image_field = ImageField::GenerationToggle;
                }
                KeyCode::Tab | KeyCode::Enter => {
                    self.image_field = ImageField::ApiKey;
                }
                _ => {}
            },
            ImageField::ApiKey => match event.code {
                KeyCode::Char(c) => {
                    if self.has_existing_image_key() {
                        self.image_api_key_input.clear();
                    }
                    self.image_api_key_input.push(c);
                }
                KeyCode::Backspace => {
                    if self.has_existing_image_key() {
                        self.image_api_key_input.clear();
                    } else {
                        self.image_api_key_input.pop();
                    }
                }
                KeyCode::BackTab => {
                    // Skip back over GenerationModel only when generation
                    // is enabled — otherwise it never got navigated to.
                    self.image_field = if self.image_generation_enabled {
                        ImageField::GenerationModel
                    } else {
                        ImageField::GenerationToggle
                    };
                }
                KeyCode::Enter => {
                    self.next_step();
                }
                _ => {}
            },
        }
        WizardAction::None
    }

    pub(super) fn handle_daemon_key(&mut self, event: KeyEvent) -> WizardAction {
        match event.code {
            KeyCode::Up | KeyCode::Down | KeyCode::Char(' ') => {
                self.install_daemon = !self.install_daemon;
            }
            KeyCode::Enter => {
                self.next_step();
            }
            _ => {}
        }
        WizardAction::None
    }

    pub(super) fn handle_health_check_key(&mut self, event: KeyEvent) -> WizardAction {
        match event.code {
            KeyCode::Enter if self.quick_jump && self.health_complete => {
                // Re-run checks on Enter after complete
                self.start_health_check();
            }
            KeyCode::Enter if self.health_complete => {
                self.next_step();
                return WizardAction::None;
            }
            KeyCode::Char('r') | KeyCode::Char('R') => {
                self.start_health_check();
            }
            _ => {}
        }
        WizardAction::None
    }
}

/// First-time detection: no config file AND no API keys in environment.
/// Once config.toml is written (by onboarding or manually), this returns false forever.
/// If any API key env var is set, the user has already configured auth — skip onboarding.
/// To re-run the wizard, use `opencrabs onboard`, `--onboard` flag, or `/onboard`.
pub fn is_first_time() -> bool {
    tracing::debug!("[is_first_time] checking if first time setup needed...");

    // Check if config exists
    let config_path = crate::config::opencrabs_home().join("config.toml");
    if !config_path.exists() {
        tracing::debug!("[is_first_time] no config found, need onboarding");
        return true;
    }

    // Config exists - check if any provider is actually enabled
    let config = match crate::config::Config::load() {
        Ok(c) => c,
        Err(e) => {
            tracing::debug!(
                "[is_first_time] failed to load config: {}, need onboarding",
                e
            );
            return true;
        }
    };

    let has_enabled_provider = config
        .providers
        .anthropic
        .as_ref()
        .is_some_and(|p| p.enabled)
        || config.providers.openai.as_ref().is_some_and(|p| p.enabled)
        || config.providers.github.as_ref().is_some_and(|p| p.enabled)
        || config.providers.gemini.as_ref().is_some_and(|p| p.enabled)
        || config
            .providers
            .openrouter
            .as_ref()
            .is_some_and(|p| p.enabled)
        || config.providers.minimax.as_ref().is_some_and(|p| p.enabled)
        || config.providers.zhipu.as_ref().is_some_and(|p| p.enabled)
        || config
            .providers
            .claude_cli
            .as_ref()
            .is_some_and(|p| p.enabled)
        || config
            .providers
            .opencode_cli
            .as_ref()
            .is_some_and(|p| p.enabled)
        || config
            .providers
            .codex_cli
            .as_ref()
            .is_some_and(|p| p.enabled)
        || config.providers.codex.as_ref().is_some_and(|p| p.enabled)
        || config.providers.qwen.as_ref().is_some_and(|p| p.enabled)
        || config.providers.ollama.as_ref().is_some_and(|p| p.enabled)
        || config
            .providers
            .opencode
            .as_ref()
            .is_some_and(|p| p.enabled)
        || config.providers.active_custom().is_some();

    tracing::debug!(
        "[is_first_time] has_enabled_provider={}, result={}",
        has_enabled_provider,
        !has_enabled_provider
    );
    !has_enabled_provider
}

/// Fetch models from provider API. No API key needed for most providers.
/// If api_key is provided, includes it (some endpoints filter by access level).
/// For custom providers, pass base_url to fetch from the endpoint.
/// Returns empty vec on failure (callers fall back to static list).
pub async fn fetch_provider_models(
    provider_index: usize,
    api_key: Option<&str>,
    zhipu_endpoint_type: Option<&str>,
    base_url: Option<&str>,
) -> Vec<String> {
    use crate::tui::onboarding::PROVIDERS;
    let provider_id = PROVIDERS.get(provider_index).map(|p| p.id).unwrap_or("");
    tracing::info!(
        "[fetch_provider_models] provider_index={}, provider_id={}, has_api_key={}",
        provider_index,
        provider_id,
        api_key.is_some(),
    );
    #[derive(serde::Deserialize)]
    struct ModelEntry {
        id: String,
        #[serde(default)]
        created: i64,
    }
    #[derive(serde::Deserialize)]
    struct ModelsResponse {
        data: Vec<ModelEntry>,
    }

    // Claude CLI — models are fixed (sonnet/opus/haiku), no API needed
    if provider_id == "claude-cli" {
        return vec![
            "sonnet".to_string(),
            "opus".to_string(),
            "haiku".to_string(),
        ];
    }

    // OpenCode CLI — fetch models via `opencode models` command
    if provider_id == "opencode-cli" {
        return fetch_opencode_models().await;
    }

    // Codex CLI & Codex OAuth — model list is curated; no /v1/models endpoint.
    if provider_id == "codex-cli" || provider_id == "codex" {
        let config_key = if provider_id == "codex" {
            "codex"
        } else {
            "codex-cli"
        };
        let models = crate::tui::provider_selector::load_default_models(config_key);
        if !models.is_empty() {
            return models;
        }
        return vec![
            "gpt-5.5".to_string(),
            "gpt-5.4".to_string(),
            "gpt-5.4-mini".to_string(),
            "gpt-5.3-codex".to_string(),
            "gpt-5.3-codex-spark".to_string(),
            "gpt-5.2".to_string(),
        ];
    }

    // Qwen (DashScope): no /v1/models endpoint on the OpenAI-compat path,
    // so we read the curated list from config.toml.example. Users can
    // override via `models = [...]` in their own config.toml.
    if provider_id == "qwen" {
        let models = crate::tui::provider_selector::load_default_models("qwen");
        if !models.is_empty() {
            return models;
        }
        return vec![
            "qwen3.6-plus".to_string(),
            "qwen3-max".to_string(),
            "qwen3-coder-plus".to_string(),
            "qwen3.5-plus".to_string(),
            "qwen-max".to_string(),
            "qwen-plus".to_string(),
            "qwen-flash".to_string(),
        ];
    }

    // Handle Minimax specially - no /models API, must use config
    if provider_id == "minimax" {
        // Minimax — NO /models API endpoint, must use config.models
        if let Ok(config) = crate::config::Config::load()
            && let Some(p) = &config.providers.minimax
        {
            if !p.models.is_empty() {
                return p.models.clone();
            }
            // Fall back to default_model if no models list
            if let Some(model) = &p.default_model {
                return vec![model.clone()];
            }
        }
        // Return hardcoded defaults if no config
        return vec![
            "MiniMax-M2.7".to_string(),
            "MiniMax-M2.5".to_string(),
            "MiniMax-M2.1".to_string(),
        ];
    }

    let client = reqwest::Client::new();

    let result = match provider_id {
        "anthropic" => {
            // Anthropic — /v1/models is public
            let mut req = client
                .get("https://api.anthropic.com/v1/models")
                .header("anthropic-version", "2023-06-01");

            // Include key if available (may show more models)
            if let Some(key) = api_key {
                if key.starts_with("sk-ant-oat") {
                    req = req
                        .header("Authorization", format!("Bearer {}", key))
                        .header("anthropic-beta", "oauth-2025-04-20");
                } else if !key.is_empty() {
                    req = req.header("x-api-key", key);
                }
            }

            req.send().await
        }
        "openai" => {
            // OpenAI — /v1/models
            let mut req = client.get("https://api.openai.com/v1/models");
            if let Some(key) = api_key
                && !key.is_empty()
            {
                req = req.header("Authorization", format!("Bearer {}", key));
            }
            req.send().await
        }
        "github" => {
            // GitHub Copilot — fetch from Copilot API using OAuth token
            if let Some(key) = api_key
                && !key.is_empty()
            {
                match crate::brain::provider::copilot::fetch_copilot_models(key).await {
                    Ok(models) if !models.is_empty() => return models,
                    Ok(_) => tracing::debug!("Copilot models endpoint returned empty list"),
                    Err(e) => tracing::debug!("Copilot models fetch failed: {}", e),
                }
            }
            // Fall back to config or defaults
            if let Ok(config) = crate::config::Config::load()
                && let Some(p) = &config.providers.github
            {
                if !p.models.is_empty() {
                    return p.models.clone();
                }
                if let Some(model) = &p.default_model {
                    return vec![model.clone()];
                }
            }
            return crate::tui::provider_selector::load_default_models("github");
        }
        "gemini" => {
            // Google Gemini — list models via generativelanguage API
            let key = match api_key {
                Some(k) if !k.is_empty() => k,
                _ => {
                    tracing::warn!(
                        "[fetch_provider_models] Gemini: no API key provided, returning empty"
                    );
                    return Vec::new();
                }
            };
            tracing::info!("[fetch_provider_models] Gemini: fetching models (key present)");
            let url = "https://generativelanguage.googleapis.com/v1beta/models";
            // Gemini uses a different response shape: { models: [{ name: "models/gemini-..." }] }
            #[derive(serde::Deserialize)]
            #[serde(rename_all = "camelCase")]
            struct GeminiModel {
                name: String,
                #[serde(default)]
                supported_generation_methods: Vec<String>,
            }
            #[derive(serde::Deserialize)]
            struct GeminiModelsResponse {
                models: Vec<GeminiModel>,
            }
            match client.get(url).header("x-goog-api-key", key).send().await {
                Ok(resp) if resp.status().is_success() => {
                    match resp.json::<GeminiModelsResponse>().await {
                        Ok(body) => {
                            let mut models: Vec<String> = body
                                .models
                                .into_iter()
                                .filter(|m| {
                                    m.supported_generation_methods
                                        .iter()
                                        .any(|g| g == "generateContent")
                                })
                                .map(|m| {
                                    m.name
                                        .strip_prefix("models/")
                                        .unwrap_or(&m.name)
                                        .to_string()
                                })
                                .collect();
                            models.sort();
                            models.reverse(); // Newest model versions first
                            tracing::info!(
                                "[fetch_provider_models] Gemini: fetched {} models",
                                models.len()
                            );
                            return models;
                        }
                        Err(e) => {
                            tracing::warn!("Gemini models parse error: {}", e);
                            return Vec::new();
                        }
                    }
                }
                Ok(resp) => {
                    tracing::warn!("Gemini models API returned {}", resp.status());
                    return Vec::new();
                }
                Err(e) => {
                    tracing::warn!("Gemini models fetch failed: {}", e);
                    return Vec::new();
                }
            }
        }
        "openrouter" => {
            // OpenRouter — /api/v1/models
            let mut req = client.get("https://openrouter.ai/api/v1/models");
            if let Some(key) = api_key
                && !key.is_empty()
            {
                req = req.header("Authorization", format!("Bearer {}", key));
            }
            req.send().await
        }
        "opencode" => {
            // OpenCode API — /zen/go/v1/models (Go and Zen plans)
            let mut req = client.get("https://opencode.ai/zen/go/v1/models");
            if let Some(key) = api_key
                && !key.is_empty()
            {
                req = req.header("Authorization", format!("Bearer {}", key));
            }
            req.send().await
        }
        "zhipu" => {
            // z.ai GLM — /api/paas/v4/models or /api/coding/paas/v4/models
            // Use passed endpoint_type (from wizard state), fall back to config, then default "api"
            let endpoint_type = zhipu_endpoint_type
                .map(|s| s.to_string())
                .or_else(|| {
                    crate::config::Config::load()
                        .ok()
                        .and_then(|c| c.providers.zhipu.clone())
                        .and_then(|p| p.endpoint_type)
                })
                .unwrap_or_else(|| "api".to_string());

            let base = match endpoint_type.as_str() {
                "coding" => "https://api.z.ai/api/coding/paas/v4/models",
                _ => "https://api.z.ai/api/paas/v4/models",
            };

            let mut req = client.get(base);
            if let Some(key) = api_key
                && !key.is_empty()
            {
                req = req.header("Authorization", format!("Bearer {}", key));
            }
            req.send().await
        }
        "ollama" => {
            // Ollama — fetch from /api/tags (local or cloud)
            let base = if let Some(url) = base_url
                && !url.is_empty()
            {
                url.to_string()
            } else {
                "http://localhost:11434".to_string()
            };
            let base = base.trim_end_matches('/');
            #[derive(serde::Deserialize)]
            struct OllamaModel {
                name: String,
            }
            #[derive(serde::Deserialize)]
            struct OllamaModelsResponse {
                models: Vec<OllamaModel>,
            }
            let mut req = client.get(format!("{}/api/tags", base));
            if let Some(key) = api_key
                && !key.is_empty()
            {
                req = req.header("Authorization", format!("Bearer {}", key));
            }
            match req.send().await {
                Ok(resp) if resp.status().is_success() => {
                    match resp.json::<OllamaModelsResponse>().await {
                        Ok(body) => {
                            let mut models: Vec<String> =
                                body.models.into_iter().map(|m| m.name).collect();
                            models.sort();
                            models.reverse();
                            tracing::info!(
                                "[fetch_provider_models] Ollama: fetched {} models",
                                models.len()
                            );
                            return models;
                        }
                        Err(e) => {
                            tracing::warn!("Ollama models parse error: {}", e);
                            return Vec::new();
                        }
                    }
                }
                Ok(resp) => {
                    tracing::warn!("Ollama models API returned {}", resp.status());
                    return Vec::new();
                }
                Err(e) => {
                    tracing::warn!("Ollama models fetch failed: {}", e);
                    return Vec::new();
                }
            }
        }
        _ => {
            // Custom provider: try fetching from base_url if provided
            if let Some(url) = base_url
                && !url.is_empty()
            {
                return crate::brain::provider::model_fetch::fetch_models_from_endpoint(
                    url, api_key,
                )
                .await;
            }
            return Vec::new();
        }
    };

    match result {
        Ok(resp) if resp.status().is_success() => match resp.json::<ModelsResponse>().await {
            Ok(body) => {
                let mut entries = body.data;
                // Sort newest first (by created timestamp descending)
                entries.sort_by_key(|e| std::cmp::Reverse(e.created));
                entries.into_iter().map(|m| m.id).collect()
            }
            Err(_) => Vec::new(),
        },
        _ => Vec::new(),
    }
}

/// Fetch available models from the opencode CLI binary.
async fn fetch_opencode_models() -> Vec<String> {
    // Resolve binary path
    let home = dirs::home_dir().unwrap_or_default();
    let candidates = [
        std::env::var("OPENCODE_PATH").unwrap_or_default(),
        home.join(".opencode/bin/opencode")
            .to_string_lossy()
            .to_string(),
        "/opt/homebrew/bin/opencode".to_string(),
        "/usr/local/bin/opencode".to_string(),
    ];

    let binary = candidates
        .iter()
        .find(|p| !p.is_empty() && std::path::Path::new(p).exists());

    let Some(binary) = binary else {
        // Try `which` as fallback
        if let Ok(output) = tokio::process::Command::new("which")
            .arg("opencode")
            .output()
            .await
            && output.status.success()
        {
            let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if !path.is_empty() {
                return run_opencode_models(&path).await;
            }
        }
        return Vec::new();
    };

    run_opencode_models(binary).await
}

async fn run_opencode_models(binary: &str) -> Vec<String> {
    let output = match tokio::process::Command::new(binary)
        .arg("models")
        .output()
        .await
    {
        Ok(o) if o.status.success() => o,
        _ => return Vec::new(),
    };

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut models: Vec<String> = stdout
        .lines()
        .map(|l| l.trim())
        .filter(|l| !l.is_empty() && !l.starts_with('{'))
        .map(|l| l.to_string())
        .collect();
    models.sort();
    models
}