opencrabs 0.3.11

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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//! Shared slash-command handlers for channel platforms (Telegram, Discord, Slack).
//!
//! Each channel handler calls [`handle_command`] before forwarding to the agent.
//! If the message is a known command, the channel renders the response directly.

use uuid::Uuid;

use crate::brain::agent::AgentService;
use crate::config::Config;
use crate::db::repository::SessionListOptions;
use crate::services::SessionService;

/// Sync the channel agent's provider for a specific session.
///
/// If the session has its own provider/model stored, restore that — so each
/// channel keeps its own provider independently of the TUI or other channels.
/// Only falls back to the global config if the session has no provider set.
pub async fn sync_provider_for_session(
    agent: &AgentService,
    session_provider: Option<&str>,
    session_model: Option<&str>,
) {
    let config = match Config::load() {
        Ok(c) => c,
        Err(_) => return,
    };

    // If the session has an explicit provider, restore it (ignoring global config)
    if let Some(sess_prov) = session_provider {
        let agent_provider = agent.provider_name();
        let agent_model = agent.provider_model();
        let sess_prov_norm = normalize_provider_name(sess_prov);
        let agent_prov_norm = normalize_provider_name(&agent_provider);
        let same_provider = provider_names_match(&sess_prov_norm, &agent_prov_norm);
        let same_model = session_model.is_none_or(|m| m == agent_model);

        if !same_provider || !same_model {
            match crate::brain::provider::factory::create_provider_by_name(&config, sess_prov).await
            {
                Ok(new_provider) => {
                    tracing::info!(
                        "Channel: restored session provider {}/{} (was {}/{})",
                        sess_prov,
                        session_model.unwrap_or("default"),
                        agent_provider,
                        agent_model,
                    );
                    agent.swap_provider(new_provider);
                    return;
                }
                Err(e) => {
                    // Session's stored provider is gone (e.g. user removed a
                    // custom provider, or the config was reset). Don't leave
                    // the channel agent on a stale provider pointing at an
                    // unreachable URL — fall through to the global config.
                    tracing::warn!(
                        "Failed to restore session provider '{}': {} — falling back to active config provider",
                        sess_prov,
                        e
                    );
                }
            }
        } else {
            return;
        }
    }

    // No session provider — fall back to global config (first message in a new session)
    let (cfg_provider, cfg_model) = config.providers.active_provider_and_model();
    let agent_provider = agent.provider_name();
    let agent_model = agent.provider_model();

    let cfg_provider_norm = normalize_provider_name(&cfg_provider);
    let agent_provider_norm = normalize_provider_name(&agent_provider);
    let same_provider = provider_names_match(&cfg_provider_norm, &agent_provider_norm);

    if !same_provider || cfg_model != agent_model {
        match crate::brain::provider::create_provider(&config).await {
            Ok(new_provider) => {
                tracing::info!(
                    "Channel agent synced to config: {} → {}",
                    agent_provider,
                    cfg_provider,
                );
                agent.swap_provider(new_provider);
            }
            Err(e) => {
                tracing::warn!("Failed to sync channel agent provider: {}", e);
            }
        }
    }
}

/// Normalize provider names/aliases to stable IDs used by config.
fn normalize_provider_name(name: &str) -> String {
    crate::utils::providers::normalize_provider_name(name)
}

/// Compare normalized provider names, handling custom runtime names (`deepseek`).
fn provider_names_match(config_provider: &str, runtime_provider: &str) -> bool {
    config_provider == runtime_provider
        || config_provider
            .strip_prefix("custom:")
            .is_some_and(|name| name == runtime_provider)
}

/// Result of matching a channel message against known commands.
pub enum ChannelCommand {
    /// `/help` — formatted help text
    Help(String),
    /// `/usage` — formatted session/cost stats
    Usage(String),
    /// `/models` — provider picker (step 1: choose provider, step 2: choose model)
    Models(ProvidersResponse),
    /// `/new` — create a new session and switch to it
    NewSession,
    /// `/sessions` — list recent sessions to switch between
    Sessions(SessionsResponse),
    /// `/stop` — cancel the running agent task
    Stop,
    /// `/compact` — trigger context compaction via the agent
    Compact,
    /// `/doctor` — health check (no LLM needed)
    Doctor,
    /// `/evolve` — check for updates and install directly (no LLM needed)
    Evolve,
    /// User-defined command with action "prompt" — forward prompt text to the agent
    UserPrompt(String),
    /// User-defined command with action "system" — display text directly
    UserSystem(String),
    /// Not a recognised command — pass through to agent
    NotACommand,
}

/// Data for rendering a provider-picker on the channel platform.
pub struct ProvidersResponse {
    pub current_provider: String,
    pub current_model: String,
    /// Available providers (name, display label) that have API keys configured.
    pub providers: Vec<(String, String)>,
    /// Fallback text when platform buttons are unavailable.
    pub text: String,
}

/// Data for rendering a session-picker on the channel platform.
pub struct SessionsResponse {
    pub current_session_id: Uuid,
    /// (session_id, display_label)
    pub sessions: Vec<(Uuid, String)>,
    /// Fallback text when platform buttons are unavailable.
    pub text: String,
}

/// Data for rendering a model-picker after a provider is selected.
pub struct ModelsResponse {
    pub provider_name: String,
    pub current_model: String,
    pub models: Vec<String>,
    /// Fallback text when platform buttons are unavailable.
    pub text: String,
    /// When true, the provider has too many models for inline buttons (OpenRouter, custom).
    /// Channels should switch to default immediately and let the agent handle follow-up.
    pub agent_handled: bool,
}

/// Check if a message is a known channel command and return the response.
/// Commands that produce output are persisted to session history so they
/// appear in TUI and give the agent context about what happened.
pub async fn handle_command(
    text: &str,
    session_id: Uuid,
    agent: &AgentService,
    session_svc: &SessionService,
) -> ChannelCommand {
    let trimmed = text.trim();
    let result = match trimmed {
        "/compact" => ChannelCommand::Compact,
        "/doctor" => ChannelCommand::Doctor,
        "/evolve" => ChannelCommand::Evolve,
        "/help" => ChannelCommand::Help(format_help()),
        "/models" => ChannelCommand::Models(format_providers(agent)),
        "/new" => ChannelCommand::NewSession,
        "/sessions" => ChannelCommand::Sessions(format_sessions(session_id, session_svc).await),
        "/stop" => ChannelCommand::Stop,
        "/usage" => ChannelCommand::Usage(format_usage(session_id, agent, session_svc).await),
        _ if trimmed.starts_with('/') => match_user_command(trimmed),
        _ => ChannelCommand::NotACommand,
    };

    // Persist command + response to session history
    let response_text = match &result {
        ChannelCommand::Help(body) | ChannelCommand::Usage(body) => Some(body.clone()),
        ChannelCommand::Models(resp) => Some(resp.text.clone()),
        ChannelCommand::Sessions(resp) => Some(resp.text.clone()),
        ChannelCommand::NewSession => Some("New session started.".to_string()),
        ChannelCommand::Stop => Some("Operation stopped.".to_string()),
        ChannelCommand::UserSystem(body) => Some(body.clone()),
        ChannelCommand::Doctor => Some("Running health check...".to_string()),
        ChannelCommand::Evolve => Some("Checking for updates...".to_string()),
        ChannelCommand::Compact | ChannelCommand::UserPrompt(_) | ChannelCommand::NotACommand => {
            None
        }
    };

    if let Some(response) = response_text {
        persist_command_to_history(agent, session_id, trimmed, &response).await;
    }

    result
}

/// Save the user command and bot response to session message history,
/// then notify TUI so it refreshes live.
async fn persist_command_to_history(
    agent: &AgentService,
    session_id: Uuid,
    command: &str,
    response: &str,
) {
    let msg_svc = crate::services::MessageService::new(agent.context().clone());
    if let Err(e) = msg_svc
        .create_message(session_id, "user".to_string(), command.to_string())
        .await
    {
        tracing::warn!("Failed to persist channel command to history: {}", e);
    }
    if let Err(e) = msg_svc
        .create_message(session_id, "assistant".to_string(), response.to_string())
        .await
    {
        tracing::warn!(
            "Failed to persist channel command response to history: {}",
            e
        );
    }
    // Notify TUI to reload session messages (same mechanism as agent responses)
    if let Some(tx) = agent.session_updated_tx() {
        let _ = tx.send(crate::brain::agent::ChannelSessionEvent::Updated(
            session_id,
        ));
    }
}

// ── User-defined commands ───────────────────────────────────────────────────

fn match_user_command(text: &str) -> ChannelCommand {
    let brain_path = crate::brain::BrainLoader::resolve_path();
    let loader = crate::brain::CommandLoader::from_brain_path(&brain_path);
    let commands = loader.load();
    match_user_command_inner(text, &commands)
}

fn match_user_command_inner(
    text: &str,
    commands: &[crate::brain::commands::UserCommand],
) -> ChannelCommand {
    // Split "/command args" into command name and optional args
    let (cmd_name, args) = text
        .split_once(' ')
        .map(|(c, a)| (c, a.trim()))
        .unwrap_or((text, ""));

    if let Some(cmd) = commands.iter().find(|c| c.name == cmd_name) {
        let prompt = if args.is_empty() {
            cmd.prompt.clone()
        } else {
            format!("{} {}", cmd.prompt, args)
        };
        match cmd.action.as_str() {
            "system" => ChannelCommand::UserSystem(prompt),
            _ => ChannelCommand::UserPrompt(prompt),
        }
    } else {
        ChannelCommand::NotACommand
    }
}

// ── /help ───────────────────────────────────────────────────────────────────

fn format_help() -> String {
    let mut lines = vec![
        "📖 *Available Commands*".to_string(),
        String::new(),
        "`/compact`  — Compact context (summarize & trim)".to_string(),
        "`/evolve`   — Download latest release & restart".to_string(),
        "`/help`     — Show this message".to_string(),
        "`/models`   — Switch AI model".to_string(),
        "`/new`      — Start a new session".to_string(),
        "`/sessions` — Switch between sessions".to_string(),
        "`/stop`     — Abort current operation".to_string(),
        "`/usage`    — Session token & cost stats".to_string(),
    ];

    // Append user-defined commands from commands.toml
    let brain_path = crate::brain::BrainLoader::resolve_path();
    let loader = crate::brain::CommandLoader::from_brain_path(&brain_path);
    let mut user_cmds = loader.load();
    if !user_cmds.is_empty() {
        user_cmds.sort_by(|a, b| a.name.cmp(&b.name));
        lines.push(String::new());
        lines.push("📌 *Custom Commands*".to_string());
        for cmd in &user_cmds {
            lines.push(format!("`{}`  — {}", cmd.name, cmd.description));
        }
    }

    lines.push(String::new());
    lines.push("🦀 Any other message is sent to OpenCrabs. 🦀".to_string());
    lines.join("\n")
}

// ── /usage ──────────────────────────────────────────────────────────────────

async fn format_usage(
    session_id: Uuid,
    agent: &AgentService,
    session_svc: &SessionService,
) -> String {
    let mut lines = vec!["📊 *Usage Stats*".to_string(), String::new()];

    // Current session
    let current_model = agent.provider_model();
    match session_svc.get_session(session_id).await {
        Ok(Some(session)) => {
            let name = session.title.as_deref().unwrap_or("Current Session");
            let model = session
                .model
                .as_deref()
                .filter(|m| !m.is_empty())
                .unwrap_or(&current_model);
            let tokens = session.token_count;
            let cost = if session.total_cost > 0.0 {
                session.total_cost
            } else if tokens > 0 {
                estimate_cost(model, tokens as i64).unwrap_or(0.0)
            } else {
                0.0
            };
            lines.push(format!("*Current Session:* {}", name));
            lines.push(format!("  Model: `{}`", model));
            lines.push(format!("  Tokens: {}", format_number(tokens as i64)));
            lines.push(format!("  Cost: ${:.4}", cost));
        }
        _ => {
            lines.push("*Current Session:* (not found)".to_string());
        }
    }

    // All-time stats from usage ledger (survives session deletes)
    lines.push(String::new());
    {
        use crate::db::repository::UsageLedgerRepository;
        let ledger = UsageLedgerRepository::new(session_svc.pool());
        let ledger_stats = ledger.stats_by_model().await.unwrap_or_default();

        let all_tokens: i64 = ledger_stats.iter().map(|s| s.total_tokens).sum();
        let all_cost: f64 = ledger_stats.iter().map(|s| s.total_cost).sum();

        let total_sessions = session_svc
            .list_sessions(SessionListOptions::default())
            .await
            .map(|s| s.len())
            .unwrap_or(0);

        lines.push(format!(
            "*All-Time:* {} sessions, {} tokens, ${:.4}",
            total_sessions,
            format_number(all_tokens),
            all_cost
        ));

        // Top models by cost (already sorted desc from ledger)
        for stats in ledger_stats.iter().take(5) {
            lines.push(format!(
                "  `{}` — {} tokens, ${:.4}",
                stats.model,
                format_number(stats.total_tokens),
                stats.total_cost
            ));
        }
    }

    lines.join("\n")
}

fn estimate_cost(model: &str, token_count: i64) -> Option<f64> {
    crate::pricing::PricingConfig::load().estimate_cost(model, token_count)
}

fn format_number(n: i64) -> String {
    if n >= 1_000_000 {
        format!("{:.1}M", n as f64 / 1_000_000.0)
    } else if n >= 1_000 {
        format!("{:.1}K", n as f64 / 1_000.0)
    } else {
        n.to_string()
    }
}

// ── /sessions ──────────────────────────────────────────────────────────────

async fn format_sessions(
    current_session_id: Uuid,
    session_svc: &SessionService,
) -> SessionsResponse {
    let sessions = session_svc
        .list_sessions(SessionListOptions {
            include_archived: false,
            limit: Some(10),
            offset: 0,
        })
        .await
        .unwrap_or_default();

    let mut text_lines = vec!["📂 *Sessions*".to_string(), String::new()];
    let mut items = Vec::new();

    for s in &sessions {
        let title = s.title.as_deref().unwrap_or("Untitled");
        let marker = if s.id == current_session_id {
            ""
        } else {
            ""
        };
        let date = s.updated_at.format("%b %d %H:%M");
        let label = format!("{} ({})", title, date);
        text_lines.push(format!("• `{}`{}", label, marker));
        items.push((s.id, label));
    }

    if sessions.is_empty() {
        text_lines.push("No sessions found.".to_string());
    }

    SessionsResponse {
        current_session_id,
        sessions: items,
        text: text_lines.join("\n"),
    }
}

// ── /models ─────────────────────────────────────────────────────────────────

fn format_providers(agent: &AgentService) -> ProvidersResponse {
    // Read current provider/model from config (not the channel agent, which may be stale)
    let (current_provider, current_model) = match crate::config::Config::load() {
        Ok(cfg) => {
            let (prov, model) = cfg.providers.active_provider_and_model();
            (prov, model)
        }
        Err(_) => (agent.provider_name(), agent.provider_model()),
    };

    let providers = configured_providers();

    let mut text_lines = vec![
        "🤖 *Switch Provider*".to_string(),
        format!("Current: `{}` / `{}`", current_provider, current_model),
        String::new(),
    ];
    for (name, label) in &providers {
        let marker = if *name == current_provider {
            ""
        } else {
            ""
        };
        text_lines.push(format!("• `{}`{}", label, marker));
    }

    ProvidersResponse {
        current_provider,
        current_model,
        providers,
        text: text_lines.join("\n"),
    }
}

/// List configured providers (those with API keys set or enabled CLI providers).
fn configured_providers() -> Vec<(String, String)> {
    let config = match crate::config::Config::load() {
        Ok(c) => c,
        Err(_) => return vec![],
    };
    crate::utils::providers::configured_providers(&config.providers)
}

/// Fetch models for a specific provider (called from callback handler).
pub async fn models_for_provider(provider_name: &str) -> ModelsResponse {
    let config = match crate::config::Config::load() {
        Ok(c) => c,
        Err(_) => {
            return ModelsResponse {
                provider_name: provider_name.to_string(),
                current_model: String::new(),
                models: vec![],
                text: "Failed to load config.".to_string(),
                agent_handled: false,
            };
        }
    };

    // Create a temporary provider to fetch its models
    let provider = match crate::brain::provider::factory::create_provider_by_name(
        &config,
        provider_name,
    )
    .await
    {
        Ok(p) => p,
        Err(e) => {
            return ModelsResponse {
                provider_name: provider_name.to_string(),
                current_model: String::new(),
                models: vec![],
                text: format!("Failed to create provider: {}", e),
                agent_handled: false,
            };
        }
    };

    let current_model = provider.default_model().to_string();

    // OpenRouter (300+ models) and custom providers skip live fetch on channels.
    // Switch to default immediately; the agent handles follow-up via config_manager tool.
    if provider_name == "openrouter" || provider_name.starts_with("custom:") {
        return ModelsResponse {
            provider_name: provider_name.to_string(),
            current_model,
            models: vec![],
            text: String::new(),
            agent_handled: true,
        };
    }

    // Standard providers: config models first (instant), then live fetch with timeout.
    let config_models = provider_config_models(&config, provider_name);
    let mut models = if !config_models.is_empty() {
        config_models
    } else {
        match tokio::time::timeout(std::time::Duration::from_secs(10), provider.fetch_models())
            .await
        {
            Ok(fetched) if !fetched.is_empty() => fetched,
            Ok(_) => vec![current_model.clone()],
            Err(_) => {
                tracing::warn!("fetch_models timed out for '{}'", provider_name);
                vec![current_model.clone()]
            }
        }
    };

    // Ensure current model is in the list
    if !models.contains(&current_model) {
        models.insert(0, current_model.clone());
    }

    let display_name = provider_display_name(provider_name);
    let mut text_lines = vec![
        format!("🤖 *{} Models*", display_name),
        format!("Current: `{}`", current_model),
        String::new(),
    ];
    for (i, m) in models.iter().enumerate() {
        let marker = if *m == current_model { "" } else { "" };
        text_lines.push(format!("{}. `{}`{}", i + 1, m, marker));
    }

    ModelsResponse {
        provider_name: provider_name.to_string(),
        current_model,
        models,
        text: text_lines.join("\n"),
        agent_handled: false,
    }
}

/// Get models from the provider's config section (for providers without /models endpoint).
fn provider_config_models(config: &crate::config::Config, name: &str) -> Vec<String> {
    crate::utils::providers::config_for(&config.providers, name)
        .map(|c| c.models.clone())
        .unwrap_or_default()
}

pub fn provider_display_name(name: &str) -> &str {
    crate::utils::providers::display_name(name)
}

// ── Model switching ─────────────────────────────────────────────────────────

/// Switch the active model for this session's provider.
///
/// Persists provider + model to the session DB record so the session keeps
/// its own provider independently. Does NOT toggle global config enabled flags
/// — that would leak into other sessions/channels.
/// Saves a `[Model changed to ...]` message to the session history so the agent
/// is aware of the switch.
/// Returns an error message on failure so channels can report it to the user.
pub async fn switch_model(
    agent: &AgentService,
    model_name: &str,
    session_id: Option<uuid::Uuid>,
) -> Result<String, String> {
    let provider_name = agent.provider_name();

    let config =
        crate::config::Config::load().map_err(|e| format!("Failed to load config: {}", e))?;

    tracing::info!(
        "Channel: switched model to {} (provider: {})",
        model_name,
        provider_name
    );

    // Create provider by name (doesn't modify global config enabled flags)
    let new_provider =
        crate::brain::provider::factory::create_provider_by_name(&config, &provider_name)
            .await
            .map_err(|e| {
                tracing::warn!("Failed to create provider after model switch: {}", e);
                format!("Model saved but failed to reload provider: {}", e)
            })?;
    let display_name = provider_display_name(&provider_name);
    agent.swap_provider(new_provider);

    let change_msg = format!(
        "[Model changed to {} (provider: {})]",
        model_name, display_name
    );

    // Persist provider + model to session DB record so it survives restarts
    if let Some(sid) = session_id {
        let session_svc = crate::services::SessionService::new(agent.context().clone());
        if let Ok(Some(mut session)) = session_svc.get_session(sid).await {
            session.provider_name = Some(provider_name.clone());
            session.model = Some(model_name.to_string());
            if let Err(e) = session_svc.update_session(&session).await {
                tracing::warn!("Failed to persist provider to session: {}", e);
            }
        }

        // Persist change message to session history so the agent knows
        let msg_svc = crate::services::MessageService::new(agent.context().clone());
        if let Err(e) = msg_svc
            .create_message(sid, "user".to_string(), change_msg.clone())
            .await
        {
            tracing::warn!("Failed to persist model-change message: {}", e);
        }
    }

    Ok(change_msg)
}

/// Run evolve directly (no LLM needed). Returns a user-facing status message.
pub async fn run_evolve() -> String {
    use crate::brain::tools::{Tool, ToolExecutionContext, evolve::EvolveTool};

    let ctx = ToolExecutionContext::new(uuid::Uuid::nil());
    let tool = EvolveTool::new(None);
    match tool
        .execute(serde_json::json!({"check_only": false}), &ctx)
        .await
    {
        Ok(result) => result.output,
        Err(e) => format!("Evolve failed: {}", e),
    }
}

/// Run doctor health check directly (no LLM needed). Returns a user-facing status message.
pub fn run_doctor() -> String {
    use crate::brain::tools::slash_command::SlashCommandTool;

    // Reuse the slash command tool's doctor logic
    SlashCommandTool::doctor_text()
}

/// Try to execute a command that returns a simple text response (no platform-specific UI).
/// Returns `Some(text)` for commands handled here, `None` for commands that need
/// platform-specific rendering (Models, Sessions, NewSession) or agent passthrough.
/// Channels call this first — if it returns Some, send the text and return.
pub async fn try_execute_text_command(cmd: &ChannelCommand) -> Option<String> {
    match cmd {
        ChannelCommand::Help(body)
        | ChannelCommand::Usage(body)
        | ChannelCommand::UserSystem(body) => Some(body.clone()),
        ChannelCommand::Doctor => Some(run_doctor()),
        ChannelCommand::Evolve => Some(run_evolve().await),
        _ => None,
    }
}

/// Map a provider name to its config section key.
#[cfg(test)]
pub(crate) fn provider_section(provider_name: &str) -> Option<String> {
    crate::utils::providers::config_section(provider_name)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::brain::commands::UserCommand;

    // ── format_number ──────────────────────────────────────────────────────

    #[test]
    fn format_number_small() {
        assert_eq!(format_number(0), "0");
        assert_eq!(format_number(1), "1");
        assert_eq!(format_number(999), "999");
    }

    #[test]
    fn format_number_thousands() {
        assert_eq!(format_number(1_000), "1.0K");
        assert_eq!(format_number(1_500), "1.5K");
        assert_eq!(format_number(999_999), "1000.0K");
    }

    #[test]
    fn format_number_millions() {
        assert_eq!(format_number(1_000_000), "1.0M");
        assert_eq!(format_number(2_500_000), "2.5M");
        assert_eq!(format_number(123_456_789), "123.5M");
    }

    // ── format_help ────────────────────────────────────────────────────────

    #[test]
    fn format_help_contains_all_commands() {
        let help = format_help();
        for cmd in [
            "/evolve",
            "/help",
            "/models",
            "/new",
            "/sessions",
            "/stop",
            "/usage",
        ] {
            assert!(help.contains(cmd), "help text missing {}", cmd);
        }
    }

    #[test]
    fn format_help_is_alphabetical() {
        let help = format_help();
        // Only check built-in commands (before "Custom Commands" section)
        let builtin_section = help.split("Custom Commands").next().unwrap_or(&help);
        let commands: Vec<&str> = builtin_section
            .lines()
            .filter_map(|line| {
                let trimmed = line.trim().strip_prefix('`')?;
                let cmd = trimmed.split('`').next()?;
                if cmd.starts_with('/') {
                    Some(cmd.split_whitespace().next().unwrap_or(cmd))
                } else {
                    None
                }
            })
            .collect();
        let mut sorted = commands.clone();
        sorted.sort();
        assert_eq!(
            commands, sorted,
            "built-in help commands are not alphabetical"
        );
    }

    // ── provider_display_name ──────────────────────────────────────────────

    #[test]
    fn provider_display_name_known() {
        assert_eq!(provider_display_name("anthropic"), "Anthropic");
        assert_eq!(provider_display_name("openai"), "OpenAI");
        assert_eq!(provider_display_name("github"), "GitHub Copilot");
        assert_eq!(provider_display_name("openrouter"), "OpenRouter");
        assert_eq!(provider_display_name("minimax"), "MiniMax");
        assert_eq!(provider_display_name("gemini"), "Gemini");
    }

    #[test]
    fn provider_aliases_normalize_and_match() {
        assert_eq!(normalize_provider_name("GitHub Copilot"), "github");
        assert_eq!(normalize_provider_name("Google Gemini"), "gemini");
        assert_eq!(
            normalize_provider_name("custom(DeepSeek)"),
            "custom:deepseek"
        );
        assert!(provider_names_match("custom:deepseek", "deepseek"));
    }

    #[test]
    fn provider_display_name_custom() {
        assert_eq!(provider_display_name("custom:deepseek"), "deepseek");
        assert_eq!(provider_display_name("custom:local-llm"), "local-llm");
    }

    #[test]
    fn provider_display_name_unknown() {
        assert_eq!(provider_display_name("mystery"), "mystery");
    }

    // ── match_user_command_inner ────────────────────────────────────────────

    fn make_cmd(name: &str, action: &str, prompt: &str) -> UserCommand {
        UserCommand {
            name: name.to_string(),
            description: String::new(),
            action: action.to_string(),
            prompt: prompt.to_string(),
        }
    }

    #[test]
    fn user_command_prompt_no_args() {
        let cmds = vec![make_cmd(
            "/credits",
            "prompt",
            "Check my OpenRouter credits",
        )];
        match match_user_command_inner("/credits", &cmds) {
            ChannelCommand::UserPrompt(p) => {
                assert_eq!(p, "Check my OpenRouter credits");
            }
            other => panic!("expected UserPrompt, got {:?}", variant_name(&other)),
        }
    }

    #[test]
    fn user_command_prompt_with_args() {
        let cmds = vec![make_cmd("/deploy", "prompt", "Deploy the service")];
        match match_user_command_inner("/deploy staging --dry-run", &cmds) {
            ChannelCommand::UserPrompt(p) => {
                assert_eq!(p, "Deploy the service staging --dry-run");
            }
            other => panic!("expected UserPrompt, got {:?}", variant_name(&other)),
        }
    }

    #[test]
    fn user_command_system_action() {
        let cmds = vec![make_cmd("/info", "system", "OpenCrabs v0.2")];
        match match_user_command_inner("/info", &cmds) {
            ChannelCommand::UserSystem(t) => assert_eq!(t, "OpenCrabs v0.2"),
            other => panic!("expected UserSystem, got {:?}", variant_name(&other)),
        }
    }

    #[test]
    fn user_command_unknown_falls_through() {
        let cmds = vec![make_cmd("/credits", "prompt", "Check credits")];
        assert!(matches!(
            match_user_command_inner("/unknown", &cmds),
            ChannelCommand::NotACommand
        ));
    }

    #[test]
    fn user_command_empty_list() {
        assert!(matches!(
            match_user_command_inner("/anything", &[]),
            ChannelCommand::NotACommand
        ));
    }

    #[test]
    fn user_command_default_action_is_prompt() {
        let cmds = vec![make_cmd("/test", "whatever", "test prompt")];
        assert!(matches!(
            match_user_command_inner("/test", &cmds),
            ChannelCommand::UserPrompt(_)
        ));
    }

    /// Helper to name variants for panic messages (ChannelCommand has no Debug).
    fn variant_name(cmd: &ChannelCommand) -> &'static str {
        match cmd {
            ChannelCommand::Compact => "Compact",
            ChannelCommand::Help(_) => "Help",
            ChannelCommand::Usage(_) => "Usage",
            ChannelCommand::Models(_) => "Models",
            ChannelCommand::NewSession => "NewSession",
            ChannelCommand::Sessions(_) => "Sessions",
            ChannelCommand::Stop => "Stop",
            ChannelCommand::UserPrompt(_) => "UserPrompt",
            ChannelCommand::UserSystem(_) => "UserSystem",
            ChannelCommand::Doctor => "Doctor",
            ChannelCommand::Evolve => "Evolve",
            ChannelCommand::NotACommand => "NotACommand",
        }
    }
}