vtcode-core 0.98.7

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
//! Request validation for Anthropic Claude API
//!
//! Validates:
//! - Message requirements
//! - Structured output schema compliance
//! - Extended thinking parameter constraints

use crate::config::core::AnthropicConfig;
use crate::llm::error_display;
use crate::llm::provider::{LLMError, LLMRequest, MessageRole, ToolChoice};

use super::capabilities::{supports_effort, supports_reasoning_effort, supports_structured_output};

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

    // Note: Model name validation removed. The Anthropic API will validate model names
    // and return appropriate errors. This avoids maintenance burden of keeping hardcoded
    // model lists in sync and allows flexibility for proxies/aggregators.

    if request.output_format.is_some() && !supports_structured_output(&request.model, default_model)
    {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            &format!(
                "Structured output is not supported for model '{}'. Structured outputs are only available for Claude Sonnet 4.5/4.6, Claude Opus 4.5/4.6, and Claude Haiku 4.5 models.",
                request.model
            ),
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    if let Some(ref schema) = request.output_format
        && supports_structured_output(&request.model, default_model)
    {
        validate_anthropic_schema(schema)?;
    }

    if let Some(ref effort) = request.effort {
        validate_effort_setting(effort, &request.model, default_model)?;
    }

    if let Some(budget) = request.thinking_budget
        && budget < 1024
    {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            &format!("thinking_budget ({}) must be at least 1024 tokens.", budget),
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    let has_reasoning = request.reasoning_effort.is_some() || request.thinking_budget.is_some();
    if has_reasoning {
        validate_reasoning_constraints(request, default_model, anthropic_config)?;
    }

    if request.prefill.is_some() && has_reasoning {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            "Pre-filling assistant responses is not supported when extended thinking is enabled. Use 'prefill' only for non-reasoning requests.",
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    if request.prefill.is_some() && request.output_format.is_some() {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            "Pre-filling assistant responses is not supported when structured outputs are enabled.",
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    validate_tool_definitions(request)?;

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

    Ok(())
}

fn validate_tool_definitions(request: &LLMRequest) -> Result<(), LLMError> {
    let Some(tools) = request.tools.as_ref() else {
        return Ok(());
    };

    let mut has_programmatic_tool_calling = false;

    for tool in tools.iter() {
        let has_allowed_callers = tool
            .allowed_callers
            .as_ref()
            .is_some_and(|callers| !callers.is_empty());
        let has_input_examples = tool
            .input_examples
            .as_ref()
            .is_some_and(|examples| !examples.is_empty());

        if let Some(function) = tool.function.as_ref() {
            validate_anthropic_tool_name(&function.name)?;

            if has_allowed_callers && tool.strict == Some(true) {
                let formatted_error = error_display::format_llm_error(
                    "Anthropic",
                    &format!(
                        "tool '{}' cannot combine strict=true with allowed_callers; strict tool use is incompatible with programmatic tool calling",
                        function.name
                    ),
                );
                return Err(LLMError::InvalidRequest {
                    message: formatted_error,
                    metadata: None,
                });
            }
        } else if has_allowed_callers || has_input_examples {
            let formatted_error = error_display::format_llm_error(
                "Anthropic",
                &format!(
                    "tool type '{}' cannot use allowed_callers or input_examples without a function definition",
                    tool.tool_type
                ),
            );
            return Err(LLMError::InvalidRequest {
                message: formatted_error,
                metadata: None,
            });
        }

        has_programmatic_tool_calling |= has_allowed_callers;
    }

    if has_programmatic_tool_calling
        && request
            .parallel_tool_config
            .as_ref()
            .is_some_and(|config| config.disable_parallel_tool_use)
    {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            "programmatic tool calling is incompatible with disable_parallel_tool_use=true",
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    if has_programmatic_tool_calling
        && matches!(
            request.tool_choice,
            Some(ToolChoice::Any | ToolChoice::Specific(_))
        )
    {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            "programmatic tool calling is incompatible with forced tool_choice values; use 'auto' or omit tool_choice",
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    Ok(())
}

fn validate_anthropic_tool_name(name: &str) -> Result<(), LLMError> {
    let is_valid = !name.is_empty()
        && name.len() <= 64
        && name
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-'));

    if is_valid {
        return Ok(());
    }

    let formatted_error = error_display::format_llm_error(
        "Anthropic",
        &format!(
            "tool name '{}' must match ^[a-zA-Z0-9_-]{{1,64}}$ for Anthropic tool use",
            name
        ),
    );
    Err(LLMError::InvalidRequest {
        message: formatted_error,
        metadata: None,
    })
}

fn validate_effort_setting(effort: &str, model: &str, default_model: &str) -> Result<(), LLMError> {
    let normalized = effort.trim().to_ascii_lowercase();
    let is_supported = supports_effort(model, default_model);

    if !is_supported {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            &format!(
                "effort is not supported for model '{}'. Supported models are Claude Opus 4.5 and Claude Opus 4.6.",
                if model.trim().is_empty() {
                    default_model
                } else {
                    model
                }
            ),
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    let allowed = ["low", "medium", "high", "max"];
    if !allowed.contains(&normalized.as_str()) {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            &format!(
                "effort must be one of low, medium, high, or max (got '{}').",
                effort
            ),
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    let resolved_model = if model.trim().is_empty() {
        default_model
    } else {
        model
    };
    if normalized == "max"
        && resolved_model != crate::config::constants::models::anthropic::CLAUDE_OPUS_4_6
    {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            "effort='max' is only supported by Claude Opus 4.6.",
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    Ok(())
}

fn validate_reasoning_constraints(
    request: &LLMRequest,
    default_model: &str,
    anthropic_config: &AnthropicConfig,
) -> Result<(), LLMError> {
    use crate::config::types::ReasoningEffortLevel;

    let budget = if let Some(b) = request.thinking_budget {
        b
    } else if let Some(effort) = request.reasoning_effort {
        match effort {
            ReasoningEffortLevel::None => 0,
            ReasoningEffortLevel::Minimal => 1024,
            ReasoningEffortLevel::Low => 4096,
            ReasoningEffortLevel::Medium => 8192,
            ReasoningEffortLevel::High => 16384,
            ReasoningEffortLevel::XHigh => 32768,
        }
    } else {
        anthropic_config.interleaved_thinking_budget_tokens
    };

    let max_tokens = request.max_tokens.unwrap_or(4096);
    if budget >= max_tokens && !supports_reasoning_effort(&request.model, default_model) {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            &format!(
                "The value of max_tokens ({}) must be strictly greater than budget_tokens ({}) when extended thinking is enabled without interleaved-thinking support.",
                max_tokens, budget
            ),
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    if let Some(ToolChoice::Any | ToolChoice::Specific(_)) = request.tool_choice {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            "Forced tool use (any/specific) is incompatible with extended thinking. Use 'auto' or 'none'.",
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    if request.temperature.is_some() || request.top_k.is_some() {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            "temperature and top_k parameters must not be set when extended thinking is enabled.",
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    if let Some(top_p) = request.top_p
        && !(0.95..=1.0).contains(&top_p)
    {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            &format!(
                "top_p must be between 0.95 and 1.0 (got {}) when extended thinking is enabled.",
                top_p
            ),
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    if let Some(last_msg) = request.messages.last()
        && last_msg.role == MessageRole::Assistant
    {
        let formatted_error = error_display::format_llm_error(
            "Anthropic",
            "Pre-filling assistant responses is not supported when extended thinking is enabled.",
        );
        return Err(LLMError::InvalidRequest {
            message: formatted_error,
            metadata: None,
        });
    }

    Ok(())
}

pub fn validate_anthropic_schema(schema: &serde_json::Value) -> Result<(), LLMError> {
    use serde_json::Value;

    match schema {
        Value::Object(obj) => {
            validate_schema_object(obj, "root")?;
        }
        Value::String(_) | Value::Number(_) | Value::Bool(_) | Value::Array(_) | Value::Null => {
            let formatted_error = error_display::format_llm_error(
                "Anthropic",
                "Structured output schema must be a JSON object",
            );
            return Err(LLMError::InvalidRequest {
                message: formatted_error,
                metadata: None,
            });
        }
    }
    Ok(())
}

fn validate_schema_object(
    obj: &serde_json::Map<String, serde_json::Value>,
    path: &str,
) -> Result<(), LLMError> {
    use serde_json::Value;

    for (key, value) in obj {
        match key.as_str() {
            "type" => {
                if let Some(type_str) = value.as_str() {
                    match type_str {
                        "object" | "array" | "string" | "number" | "integer" | "boolean"
                        | "null" => {}
                        _ => {
                            let formatted_error = error_display::format_llm_error(
                                "Anthropic",
                                &format!("Unsupported schema type '{}', path: {}", type_str, path),
                            );
                            return Err(LLMError::InvalidRequest {
                                message: formatted_error,
                                metadata: None,
                            });
                        }
                    }
                }
            }
            "minimum" | "maximum" | "multipleOf" => {
                let formatted_error = error_display::format_llm_error(
                    "Anthropic",
                    &format!(
                        "Numeric constraints like '{}' are not supported by Anthropic structured output. Path: {}",
                        key, path
                    ),
                );
                return Err(LLMError::InvalidRequest {
                    message: formatted_error,
                    metadata: None,
                });
            }
            "minLength" | "maxLength" => {
                let formatted_error = error_display::format_llm_error(
                    "Anthropic",
                    &format!(
                        "String constraints like '{}' are not supported by Anthropic structured output. Path: {}",
                        key, path
                    ),
                );
                return Err(LLMError::InvalidRequest {
                    message: formatted_error,
                    metadata: None,
                });
            }
            "minItems" | "maxItems" | "uniqueItems" => {
                if key == "minItems" {
                    if let Some(min_items) = value.as_u64()
                        && min_items > 1
                    {
                        let formatted_error = error_display::format_llm_error(
                            "Anthropic",
                            &format!(
                                "Array minItems only supports values 0 or 1, got {}, path: {}",
                                min_items, path
                            ),
                        );
                        return Err(LLMError::InvalidRequest {
                            message: formatted_error,
                            metadata: None,
                        });
                    }
                } else {
                    let formatted_error = error_display::format_llm_error(
                        "Anthropic",
                        &format!(
                            "Array constraints like '{}' are not supported by Anthropic structured output. Path: {}",
                            key, path
                        ),
                    );
                    return Err(LLMError::InvalidRequest {
                        message: formatted_error,
                        metadata: None,
                    });
                }
            }
            "additionalProperties" => {
                if let Some(additional_props) = value.as_bool()
                    && additional_props
                {
                    let formatted_error = error_display::format_llm_error(
                        "Anthropic",
                        &format!(
                            "additionalProperties must be set to false, got {}, path: {}",
                            additional_props, path
                        ),
                    );
                    return Err(LLMError::InvalidRequest {
                        message: formatted_error,
                        metadata: None,
                    });
                }
            }
            "properties" => {
                if let Value::Object(props) = value {
                    for (prop_name, prop_value) in props {
                        let prop_path = format!("{}.properties.{}", path, prop_name);
                        if let Value::Object(prop_obj) = prop_value {
                            validate_schema_object(prop_obj, &prop_path)?;
                        }
                    }
                }
            }
            "items" => {
                if let Value::Object(items_obj) = value {
                    let items_path = format!("{}.items", path);
                    validate_schema_object(items_obj, &items_path)?;
                }
            }
            "anyOf" | "allOf" | "oneOf" => {
                if let Value::Array(options) = value {
                    for (i, option) in options.iter().enumerate() {
                        if let Value::Object(option_obj) = option {
                            let option_path = format!("{}.{}[{}]", path, key, i);
                            validate_schema_object(option_obj, &option_path)?;
                        }
                    }
                }
            }
            _ => {}
        }
    }
    Ok(())
}