vtcode-core 0.116.4

Core library for VT Code - a Rust-based terminal coding agent
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
#![allow(clippy::result_large_err)]

use super::common::resolve_model;
use super::ollama::base_url_to_host_root;
use super::openai::OpenAIProvider;
use crate::config::TimeoutsConfig;
use crate::config::constants::{env_vars, models, urls};
use crate::config::core::{AnthropicConfig, ModelConfig, PromptCachingConfig};
use crate::llm::client::LLMClient;
use crate::llm::error_display;
use crate::llm::provider::{LLMError, LLMProvider, LLMRequest, LLMResponse, LLMStream, Message};
use crate::llm::providers::common::override_base_url;
use crate::utils::http_client;
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::process::Stdio;
use std::sync::{Arc, LazyLock, Mutex};
use std::time::{Duration, Instant};
use tokio::process::{Child, Command};
use tokio::sync::{Mutex as AsyncMutex, watch};
use tokio::time::sleep;
use url::Url;

const DEFAULT_STARTUP_TIMEOUT_SECONDS: u64 = 60;
const SERVER_POLL_INTERVAL: Duration = Duration::from_millis(500);

#[derive(Debug, Deserialize, Serialize)]
struct LlamaCppModelsResponse {
    data: Vec<LlamaCppModel>,
}

#[derive(Debug, Deserialize, Serialize)]
struct LlamaCppModel {
    id: String,
}

const LLAMACPP_CONNECTION_ERROR: &str = "llama.cpp is not responding. Install from https://llama.app and either start `llama-server -m /path/to/model.gguf --port 8080` yourself or set LLAMACPP_MODEL_PATH so VT Code can manage startup.";

#[derive(Debug, Clone, PartialEq, Eq)]
enum ServerPhase {
    NotStarted,
    Starting,
    Ready,
    Failed,
}

#[derive(Debug, Clone)]
struct ServerStatus {
    phase: ServerPhase,
    model_id: Option<String>,
    model_path: Option<String>,
    error: Option<String>,
}

impl Default for ServerStatus {
    fn default() -> Self {
        Self {
            phase: ServerPhase::NotStarted,
            model_id: None,
            model_path: None,
            error: None,
        }
    }
}

impl ServerStatus {
    fn starting(model_path: Option<String>) -> Self {
        Self {
            phase: ServerPhase::Starting,
            model_id: None,
            model_path,
            error: None,
        }
    }

    fn ready(model_id: String, model_path: Option<String>) -> Self {
        Self {
            phase: ServerPhase::Ready,
            model_id: Some(model_id),
            model_path,
            error: None,
        }
    }

    fn failed(error: impl Into<String>, model_path: Option<String>) -> Self {
        Self {
            phase: ServerPhase::Failed,
            model_id: None,
            model_path,
            error: Some(error.into()),
        }
    }
}

#[derive(Debug)]
struct ManagedLlamaCppServer {
    state: AsyncMutex<ManagedLlamaCppState>,
    status_tx: watch::Sender<ServerStatus>,
}

#[derive(Debug, Default)]
struct ManagedLlamaCppState {
    child: Option<Child>,
    status: ServerStatus,
}

impl ManagedLlamaCppServer {
    fn new() -> Self {
        let status = ServerStatus::default();
        let (status_tx, _) = watch::channel(status.clone());
        Self {
            state: AsyncMutex::new(ManagedLlamaCppState {
                child: None,
                status,
            }),
            status_tx,
        }
    }
}

#[derive(Debug)]
enum ServerProbe {
    Ready(String),
    Loading,
    Unavailable(String),
}

static MANAGED_LLAMACPP_SERVERS: LazyLock<Mutex<HashMap<String, Arc<ManagedLlamaCppServer>>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

pub async fn fetch_llamacpp_models(base_url: Option<String>) -> Result<Vec<String>, anyhow::Error> {
    let resolved_base_url = override_base_url(
        urls::LLAMACPP_API_BASE,
        base_url,
        Some(env_vars::LLAMACPP_BASE_URL),
    );
    let models_url = format!("{}/models", resolved_base_url.trim_end_matches('/'));
    let client = http_client::create_client_with_timeout(std::time::Duration::from_secs(5));
    let response = client
        .get(&models_url)
        .header("Content-Type", "application/json")
        .send()
        .await
        .map_err(|e| {
            tracing::warn!("Failed to connect to llama.cpp server: {e:?}");
            anyhow::anyhow!(LLAMACPP_CONNECTION_ERROR)
        })?;

    if !response.status().is_success() {
        return Err(anyhow::anyhow!(
            "Failed to fetch llama.cpp models: HTTP {}. {}",
            response.status(),
            if response.status() == reqwest::StatusCode::NOT_FOUND {
                "Ensure llama-server is running and exposing the OpenAI-compatible /v1 API."
            } else {
                ""
            }
        ));
    }

    let models_response: LlamaCppModelsResponse = response
        .json()
        .await
        .map_err(|e| anyhow::anyhow!("Failed to parse llama.cpp models response: {}", e))?;

    Ok(models_response
        .data
        .into_iter()
        .map(|model| model.id)
        .collect())
}

pub struct LlamaCppProvider {
    inner: OpenAIProvider,
    api_key: Option<String>,
    configured_model: Option<String>,
    base_url: String,
    prompt_cache: Option<PromptCachingConfig>,
    timeouts: Option<TimeoutsConfig>,
    anthropic: Option<AnthropicConfig>,
    model_behavior: Option<ModelConfig>,
}

impl LlamaCppProvider {
    fn resolve_base_url(base_url: Option<String>) -> String {
        override_base_url(
            urls::LLAMACPP_API_BASE,
            base_url,
            Some(env_vars::LLAMACPP_BASE_URL),
        )
    }

    fn build_inner(
        api_key: Option<String>,
        model: Option<String>,
        base_url: Option<String>,
        prompt_cache: Option<PromptCachingConfig>,
        timeouts: Option<TimeoutsConfig>,
        anthropic: Option<AnthropicConfig>,
        model_behavior: Option<ModelConfig>,
    ) -> OpenAIProvider {
        let resolved_model = resolve_model(model, models::llamacpp::DEFAULT_MODEL);
        let resolved_base = Self::resolve_base_url(base_url);
        OpenAIProvider::from_config(
            api_key,
            None,
            Some(resolved_model),
            Some(resolved_base),
            prompt_cache,
            timeouts,
            anthropic,
            None,
            model_behavior,
        )
    }

    fn managed_server_for(base_url: &str) -> Arc<ManagedLlamaCppServer> {
        let host_root = base_url_to_host_root(base_url);
        let mut guard = MANAGED_LLAMACPP_SERVERS
            .lock()
            .expect("llama.cpp managed server map poisoned");
        guard
            .entry(host_root)
            .or_insert_with(|| Arc::new(ManagedLlamaCppServer::new()))
            .clone()
    }

    fn provider_error(message: impl Into<String>) -> LLMError {
        LLMError::Provider {
            message: error_display::format_llm_error("llama.cpp", &message.into()),
            metadata: None,
        }
    }

    fn configured_startup_model_path(configured_model: Option<&str>) -> Option<String> {
        std::env::var(env_vars::LLAMACPP_MODEL_PATH)
            .ok()
            .filter(|value| !value.trim().is_empty())
            .or_else(|| {
                configured_model.and_then(|value| {
                    let trimmed = value.trim();
                    if trimmed.is_empty() || !Self::looks_like_local_model_path(trimmed) {
                        return None;
                    }
                    Some(trimmed.to_string())
                })
            })
    }

    fn startup_timeout() -> Duration {
        std::env::var(env_vars::LLAMACPP_STARTUP_TIMEOUT_SECONDS)
            .ok()
            .and_then(|value| value.parse::<u64>().ok())
            .filter(|seconds| *seconds > 0)
            .map(Duration::from_secs)
            .unwrap_or_else(|| Duration::from_secs(DEFAULT_STARTUP_TIMEOUT_SECONDS))
    }

    fn looks_like_local_model_path(value: &str) -> bool {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            return false;
        }

        trimmed.ends_with(".gguf")
            || trimmed.contains(std::path::MAIN_SEPARATOR)
            || trimmed.contains('/')
            || trimmed.starts_with('.')
            || Path::new(trimmed).exists()
    }

    fn is_local_base_url(base_url: &str) -> bool {
        let host_root = base_url_to_host_root(base_url);
        Url::parse(&host_root)
            .ok()
            .and_then(|url| url.host_str().map(str::to_ascii_lowercase))
            .is_some_and(|host| host == "localhost" || host == "127.0.0.1" || host == "::1")
    }

    fn host_port(base_url: &str) -> Result<u16> {
        let host_root = base_url_to_host_root(base_url);
        let parsed = Url::parse(&host_root)
            .with_context(|| format!("Failed to parse llama.cpp base URL: {host_root}"))?;
        Ok(parsed.port().unwrap_or(8080))
    }

    fn resolve_binary_path() -> Result<String> {
        if let Ok(path) = std::env::var(env_vars::LLAMACPP_BINARY_PATH)
            && !path.trim().is_empty()
        {
            return Ok(path);
        }

        which::which("llama-server")
            .map(|path| path.to_string_lossy().into_owned())
            .context("Could not find `llama-server` on PATH. Install llama.cpp from https://llama.app or set LLAMACPP_BINARY_PATH.")
    }

    fn build_command_args(base_url: &str, model_path: &str) -> Result<Vec<String>> {
        let path = Path::new(model_path);
        if !path.exists() {
            anyhow::bail!("Configured model path does not exist: {model_path}");
        }

        let mut args = vec![
            "-m".to_string(),
            model_path.to_string(),
            "--port".to_string(),
            Self::host_port(base_url)?.to_string(),
        ];

        if let Ok(extra_args) = std::env::var(env_vars::LLAMACPP_EXTRA_ARGS)
            && !extra_args.trim().is_empty()
        {
            args.extend(shell_words::split(&extra_args).with_context(|| {
                format!(
                    "Failed to parse {}: {extra_args}",
                    env_vars::LLAMACPP_EXTRA_ARGS
                )
            })?);
        }

        Ok(args)
    }

    async fn spawn_managed_server(base_url: &str, model_path: &str) -> Result<Child> {
        let binary = Self::resolve_binary_path()?;
        let args = Self::build_command_args(base_url, model_path)?;
        let mut command = Command::new(&binary);
        command
            .args(&args)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .kill_on_drop(true);

        command.spawn().with_context(|| {
            format!(
                "Failed to start llama.cpp server with `{binary} {}`",
                args.join(" ")
            )
        })
    }

    async fn probe_server(base_url: &str) -> ServerProbe {
        let host_root = base_url_to_host_root(base_url);
        let health_url = format!("{}/health", host_root.trim_end_matches('/'));
        let client = http_client::create_client_with_timeout(Duration::from_secs(5));

        let response = match client.get(&health_url).send().await {
            Ok(response) => response,
            Err(error) => {
                tracing::debug!("llama.cpp health probe failed for {health_url}: {error}");
                return ServerProbe::Unavailable(LLAMACPP_CONNECTION_ERROR.to_string());
            }
        };

        if response.status().is_success() {
            return match fetch_llamacpp_models(Some(base_url.to_string())).await {
                Ok(models) if !models.is_empty() => ServerProbe::Ready(models[0].clone()),
                Ok(_) => ServerProbe::Unavailable(
                    "llama.cpp is running but did not report any loaded models from /v1/models."
                        .to_string(),
                ),
                Err(error) => ServerProbe::Unavailable(error.to_string()),
            };
        }

        let status = response.status();
        let body = response.text().await.unwrap_or_default();
        if status == reqwest::StatusCode::SERVICE_UNAVAILABLE
            && body.to_ascii_lowercase().contains("loading")
        {
            return ServerProbe::Loading;
        }

        if status == reqwest::StatusCode::NOT_FOUND {
            return match fetch_llamacpp_models(Some(base_url.to_string())).await {
                Ok(models) if !models.is_empty() => ServerProbe::Ready(models[0].clone()),
                Ok(_) => ServerProbe::Unavailable(
                    "llama.cpp is running but did not report any loaded models from /v1/models."
                        .to_string(),
                ),
                Err(error) => ServerProbe::Unavailable(error.to_string()),
            };
        }

        ServerProbe::Unavailable(format!(
            "llama.cpp health check failed with HTTP {}{}",
            status,
            if body.trim().is_empty() {
                String::new()
            } else {
                format!(": {}", body.trim())
            }
        ))
    }

    async fn wait_until_ready(base_url: &str, timeout: Duration) -> Result<String> {
        let deadline = Instant::now() + timeout;
        let mut last_error = LLAMACPP_CONNECTION_ERROR.to_string();

        while Instant::now() < deadline {
            match Self::probe_server(base_url).await {
                ServerProbe::Ready(model_id) => return Ok(model_id),
                ServerProbe::Loading => {
                    last_error = "llama.cpp is still loading the configured model".to_string();
                }
                ServerProbe::Unavailable(message) => {
                    last_error = message;
                }
            }

            sleep(SERVER_POLL_INTERVAL).await;
        }

        Err(anyhow::anyhow!(
            "Timed out waiting for llama.cpp to become ready after {}s. Last status: {}",
            timeout.as_secs(),
            last_error
        ))
    }

    async fn ensure_server_ready(&self) -> Result<String, LLMError> {
        let timeout = Self::startup_timeout();
        let initial_probe = Self::probe_server(&self.base_url).await;
        match &initial_probe {
            ServerProbe::Ready(model_id) => {
                let server = Self::managed_server_for(&self.base_url);
                let mut state = server.state.lock().await;
                state.status =
                    ServerStatus::ready(model_id.clone(), state.status.model_path.clone());
                let _ = server.status_tx.send(state.status.clone());
                return Ok(model_id.clone());
            }
            ServerProbe::Loading => {}
            ServerProbe::Unavailable(_) => {}
        }

        let startup_model_path =
            Self::configured_startup_model_path(self.configured_model.as_deref());
        let server = Self::managed_server_for(&self.base_url);
        let mut rx = server.status_tx.subscribe();

        loop {
            let mut should_spawn = false;
            {
                let mut state = server.state.lock().await;

                if let Some(child) = state.child.as_mut() {
                    match child.try_wait() {
                        Ok(Some(exit_status)) => {
                            let model_path = state.status.model_path.clone();
                            state.child = None;
                            state.status = ServerStatus::failed(
                                format!(
                                    "Managed llama.cpp server exited with status {exit_status}"
                                ),
                                model_path,
                            );
                            let _ = server.status_tx.send(state.status.clone());
                        }
                        Ok(None) => {}
                        Err(error) => {
                            let model_path = state.status.model_path.clone();
                            state.child = None;
                            state.status = ServerStatus::failed(
                                format!("Failed to inspect managed llama.cpp server: {error}"),
                                model_path,
                            );
                            let _ = server.status_tx.send(state.status.clone());
                        }
                    }
                }

                match state.status.phase {
                    ServerPhase::Ready => {
                        if let Some(model_id) = state.status.model_id.clone() {
                            return Ok(model_id);
                        }
                        state.status = ServerStatus::default();
                        let _ = server.status_tx.send(state.status.clone());
                    }
                    ServerPhase::Starting => {}
                    ServerPhase::NotStarted | ServerPhase::Failed => {
                        match startup_model_path.clone() {
                            Some(model_path) => {
                                if !Self::is_local_base_url(&self.base_url) {
                                    return Err(Self::provider_error(format!(
                                        "{} Auto-start is only available for localhost llama.cpp endpoints.",
                                        LLAMACPP_CONNECTION_ERROR
                                    )));
                                }
                                state.status = ServerStatus::starting(Some(model_path));
                                let _ = server.status_tx.send(state.status.clone());
                                should_spawn = true;
                            }
                            None => {
                                let reason = match &initial_probe {
                                    ServerProbe::Unavailable(message) => message.clone(),
                                    ServerProbe::Loading => {
                                        "llama.cpp is still loading but no managed model path is configured"
                                            .to_string()
                                    }
                                    ServerProbe::Ready(model_id) => return Ok(model_id.clone()),
                                };
                                return Err(Self::provider_error(format!(
                                    "{reason} Set {} or configure the provider model to a local .gguf path so VT Code can launch llama-server automatically.",
                                    env_vars::LLAMACPP_MODEL_PATH
                                )));
                            }
                        }
                    }
                }
            }

            if should_spawn {
                let model_path = startup_model_path.clone().ok_or_else(|| {
                    Self::provider_error(format!(
                        "Managed llama.cpp startup requires {} or a provider model path",
                        env_vars::LLAMACPP_MODEL_PATH
                    ))
                })?;

                let spawn_result = async {
                    let child = Self::spawn_managed_server(&self.base_url, &model_path).await?;
                    let model_id = Self::wait_until_ready(&self.base_url, timeout).await?;
                    Ok::<_, anyhow::Error>((child, model_id))
                }
                .await;

                let mut state = server.state.lock().await;
                match spawn_result {
                    Ok((child, model_id)) => {
                        state.child = Some(child);
                        state.status = ServerStatus::ready(model_id.clone(), Some(model_path));
                        let _ = server.status_tx.send(state.status.clone());
                        return Ok(model_id);
                    }
                    Err(error) => {
                        state.child = None;
                        state.status = ServerStatus::failed(error.to_string(), Some(model_path));
                        let _ = server.status_tx.send(state.status.clone());
                        return Err(Self::provider_error(error.to_string()));
                    }
                }
            }

            rx.changed().await.map_err(|_| {
                Self::provider_error("llama.cpp managed server watcher unexpectedly closed")
            })?;

            let status = rx.borrow().clone();
            match status.phase {
                ServerPhase::Ready => {
                    if let Some(model_id) = status.model_id {
                        return Ok(model_id);
                    }
                }
                ServerPhase::Failed => {
                    return Err(Self::provider_error(
                        status
                            .error
                            .unwrap_or_else(|| LLAMACPP_CONNECTION_ERROR.to_string()),
                    ));
                }
                ServerPhase::Starting | ServerPhase::NotStarted => {}
            }
        }
    }

    fn should_replace_request_model(
        &self,
        request_model: &str,
        discovered_models: &[String],
    ) -> bool {
        let trimmed = request_model.trim();
        if trimmed.is_empty() || Self::looks_like_local_model_path(trimmed) {
            return true;
        }

        if discovered_models.len() == 1 {
            let configured = self
                .configured_model
                .as_deref()
                .map(str::trim)
                .unwrap_or_default();
            if trimmed == models::llamacpp::DEFAULT_MODEL || trimmed == configured {
                return true;
            }
        }

        !discovered_models.iter().any(|model| model == trimmed) && discovered_models.len() == 1
    }

    fn request_model_or_default(&self, request_model: &str) -> String {
        let trimmed = request_model.trim();
        if trimmed.is_empty() {
            resolve_model(
                self.configured_model.clone(),
                models::llamacpp::DEFAULT_MODEL,
            )
        } else {
            trimmed.to_string()
        }
    }

    fn build_request_provider(&self, model: String) -> OpenAIProvider {
        Self::build_inner(
            self.api_key.clone(),
            Some(model),
            Some(self.base_url.clone()),
            self.prompt_cache.clone(),
            self.timeouts.clone(),
            self.anthropic.clone(),
            self.model_behavior.clone(),
        )
    }

    async fn prepare_request(
        &self,
        mut request: LLMRequest,
    ) -> Result<(OpenAIProvider, LLMRequest), LLMError> {
        let discovered_model = self.ensure_server_ready().await?;
        let discovered_models = vec![discovered_model.clone()];

        if self.should_replace_request_model(&request.model, &discovered_models)
            || request.model.trim().is_empty()
        {
            request.model = discovered_model.clone();
        } else {
            request.model = self.request_model_or_default(&request.model);
        }

        Ok((self.build_request_provider(request.model.clone()), request))
    }

    pub fn from_config(
        api_key: Option<String>,
        model: Option<String>,
        base_url: Option<String>,
        prompt_cache: Option<PromptCachingConfig>,
        timeouts: Option<TimeoutsConfig>,
        anthropic: Option<AnthropicConfig>,
        model_behavior: Option<ModelConfig>,
    ) -> Self {
        let resolved_base_url = Self::resolve_base_url(base_url.clone());
        Self {
            inner: Self::build_inner(
                api_key.clone(),
                model.clone(),
                base_url,
                prompt_cache.clone(),
                timeouts.clone(),
                anthropic.clone(),
                model_behavior.clone(),
            ),
            api_key,
            configured_model: model,
            base_url: resolved_base_url,
            prompt_cache,
            timeouts,
            anthropic,
            model_behavior,
        }
    }
}

#[async_trait]
impl LLMProvider for LlamaCppProvider {
    fn name(&self) -> &str {
        "llamacpp"
    }

    fn supports_streaming(&self) -> bool {
        self.inner.supports_streaming()
    }

    fn supports_reasoning(&self, model: &str) -> bool {
        self.inner.supports_reasoning(model)
    }

    fn supports_reasoning_effort(&self, model: &str) -> bool {
        self.inner.supports_reasoning_effort(model)
    }

    fn supports_tools(&self, model: &str) -> bool {
        self.inner.supports_tools(model)
    }

    fn supports_parallel_tool_config(&self, model: &str) -> bool {
        self.inner.supports_parallel_tool_config(model)
    }

    async fn generate(&self, request: LLMRequest) -> Result<LLMResponse, LLMError> {
        let (provider, request) = self.prepare_request(request).await?;
        provider.generate(request).await
    }

    async fn stream(&self, request: LLMRequest) -> Result<LLMStream, LLMError> {
        let (provider, request) = self.prepare_request(request).await?;
        provider.stream(request).await
    }

    fn supported_models(&self) -> Vec<String> {
        models::llamacpp::SUPPORTED_MODELS
            .iter()
            .map(|model| model.to_string())
            .collect()
    }

    fn validate_request(&self, request: &LLMRequest) -> Result<(), LLMError> {
        if request.messages.is_empty() {
            let formatted_error =
                error_display::format_llm_error("llama.cpp", "Messages cannot be empty");
            return Err(LLMError::InvalidRequest {
                message: formatted_error,
                metadata: None,
            });
        }

        for message in &request.messages {
            if let Err(err) = message.validate_for_provider("openai") {
                let formatted = error_display::format_llm_error("llama.cpp", &err);
                return Err(LLMError::InvalidRequest {
                    message: formatted,
                    metadata: None,
                });
            }
        }

        Ok(())
    }
}

#[async_trait]
impl LLMClient for LlamaCppProvider {
    async fn generate(&mut self, prompt: &str) -> Result<LLMResponse, LLMError> {
        LLMProvider::generate(
            self,
            LLMRequest {
                messages: vec![Message::user(prompt.to_string())],
                model: self
                    .configured_model
                    .clone()
                    .unwrap_or_else(|| models::llamacpp::DEFAULT_MODEL.to_string()),
                ..Default::default()
            },
        )
        .await
    }

    fn model_id(&self) -> &str {
        self.inner.model_id()
    }
}