vtcode-core 0.136.0

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
#![allow(missing_docs)]

pub use crate::AgentRunner;
pub use crate::config::VTCodeConfig;
pub use crate::config::constants::tools;
pub use crate::config::models::ModelId;
pub use crate::config::types::CapabilityLevel;
pub use crate::core::agent::events::ExecEventRecorder;
pub use crate::core::agent::harness_kernel::SessionToolCatalogSnapshot;
pub use crate::core::agent::runner::RunnerSettings;
pub use crate::core::agent::runtime::AgentRuntime;
pub use crate::core::agent::session::AgentSessionState;
pub use crate::core::agent::steering::SteeringMessage;
pub use crate::core::agent::task::{Task, TaskOutcome, TaskResults};
pub use crate::core::agent::types::AgentType;
pub use crate::core::threads::ThreadBootstrap;
pub use crate::exec::events::{HarnessEventKind, ItemCompletedEvent, ThreadEvent, ThreadItemDetails, ToolCallStatus};
pub use crate::llm::provider::{FinishReason, LLMError, LLMProvider, LLMRequest, LLMResponse, ToolCall, ToolChoice};
pub use crate::primary_agent::ActivePrimaryAgent;
pub use crate::tool_policy::ToolPolicy;
pub use crate::tools::Tool;
pub use crate::tools::circuit_breaker::{CircuitBreaker, CircuitBreakerConfig};
pub use crate::tools::handlers::{PlanningWorkflowState, TaskTrackerTool};
pub use crate::tools::handlers::{SessionSurface, SessionToolsConfig, ToolModelCapabilities};
pub use async_trait::async_trait;
pub use parking_lot::Mutex;
pub use serde_json::json;
pub use std::collections::VecDeque;
pub use std::fs;
pub use std::path::{Path, PathBuf};
pub use std::sync::Arc;
pub use std::time::{Duration, Instant};
pub use tempfile::TempDir;
use vtcode_commons::canonicalize;
pub use vtcode_config::ToolProfile;
pub use vtcode_config::core::permissions::{AgentPermissionsConfig, PermissionDefault};

pub fn provider_tool_names(snapshot: &SessionToolCatalogSnapshot) -> Vec<&str> {
    snapshot
        .snapshot
        .as_ref()
        .map(|tools| tools.iter().map(|tool| tool.function_name()).collect())
        .unwrap_or_default()
}

pub fn assert_provider_exposes_tool(snapshot: &SessionToolCatalogSnapshot, tool_name: &str) {
    let names = provider_tool_names(snapshot);
    assert!(names.contains(&tool_name), "provider-facing snapshot should include {tool_name}; got {names:?}");
    assert!(
        snapshot.active_tool_names.iter().any(|active_name| active_name == tool_name),
        "active tool names should include {tool_name}"
    );
}

pub fn assert_provider_hides_tool(snapshot: &SessionToolCatalogSnapshot, tool_name: &str) {
    let names = provider_tool_names(snapshot);
    assert!(!names.contains(&tool_name), "provider-facing snapshot should hide {tool_name}; got {names:?}");
    assert!(
        !snapshot.active_tool_names.iter().any(|active_name| active_name == tool_name),
        "active tool names should hide {tool_name}"
    );
}

pub fn assert_provider_catalogues_inactive_tool(snapshot: &SessionToolCatalogSnapshot, tool_name: &str) {
    let names = provider_tool_names(snapshot);
    assert!(names.contains(&tool_name), "stable provider catalogue should include {tool_name}; got {names:?}");
    assert!(
        !snapshot.active_tool_names.iter().any(|active_name| active_name == tool_name),
        "active tool names should hide {tool_name}"
    );
}

#[derive(Clone)]
pub struct QueuedProvider {
    pub responses: Arc<Mutex<VecDeque<LLMResponse>>>,
}

impl QueuedProvider {
    pub fn new(responses: Vec<LLMResponse>) -> Self {
        Self { responses: Arc::new(Mutex::new(responses.into())) }
    }
}

#[async_trait]
impl LLMProvider for QueuedProvider {
    fn name(&self) -> &str {
        "queued-test-provider"
    }

    async fn generate(&self, _request: LLMRequest) -> Result<LLMResponse, LLMError> {
        self.responses.lock().pop_front().ok_or(LLMError::InvalidRequest {
            message: "QueuedProvider has no queued responses".to_string(),
            metadata: None,
        })
    }

    fn supported_models(&self) -> Vec<String> {
        vec!["gpt-5.3-codex".to_string()]
    }

    fn validate_request(&self, _request: &LLMRequest) -> Result<(), LLMError> {
        Ok(())
    }
}

#[derive(Clone)]
pub struct RecordingQueuedProvider {
    name: &'static str,
    supports_native_allowed_tools: bool,
    responses: Arc<Mutex<VecDeque<LLMResponse>>>,
    requests: Arc<Mutex<Vec<LLMRequest>>>,
}

impl RecordingQueuedProvider {
    pub fn new(responses: Vec<LLMResponse>) -> Self {
        Self::with_native_allowed_tools("openai", true, responses)
    }

    pub fn with_name(name: &'static str, responses: Vec<LLMResponse>) -> Self {
        Self::with_native_allowed_tools(name, false, responses)
    }

    fn with_native_allowed_tools(
        name: &'static str,
        supports_native_allowed_tools: bool,
        responses: Vec<LLMResponse>,
    ) -> Self {
        Self {
            name,
            supports_native_allowed_tools,
            responses: Arc::new(Mutex::new(responses.into())),
            requests: Arc::new(Mutex::new(Vec::new())),
        }
    }

    pub fn recorded_requests(&self) -> Vec<LLMRequest> {
        self.requests.lock().clone()
    }
}

#[async_trait]
impl LLMProvider for RecordingQueuedProvider {
    fn name(&self) -> &str {
        self.name
    }

    async fn generate(&self, request: LLMRequest) -> Result<LLMResponse, LLMError> {
        self.requests.lock().push(request);
        self.responses.lock().pop_front().ok_or(LLMError::InvalidRequest {
            message: "RecordingQueuedProvider has no queued responses".to_string(),
            metadata: None,
        })
    }

    fn supported_models(&self) -> Vec<String> {
        vec!["gpt-5.3-codex".to_string()]
    }

    fn supports_native_allowed_tools(&self, _model: &str) -> bool {
        self.supports_native_allowed_tools
    }

    fn validate_request(&self, _request: &LLMRequest) -> Result<(), LLMError> {
        Ok(())
    }
}

/// Roles in the orchestrated harness LLM-call lifecycle.
///
/// The harness drives several distinct sub-agents (planner, build, evaluator,
/// replanner) through the same `LLMProvider`. `RoleQueuedProvider` maps each
/// `generate` call to its role via the system prompt so responses are matched
/// by role instead of by flat position. This keeps tests resilient to harness
/// flow changes (e.g. an added build turn between a replan and re-evaluation):
/// when a role's queue is empty, a role-appropriate default is returned instead
/// of erroring on a missing queued response.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HarnessRole {
    Planner,
    Build,
    Evaluator,
    Replanner,
}

pub fn harness_role_of(request: &LLMRequest) -> HarnessRole {
    let sys = request.system_prompt.as_ref().map(|s| s.as_str()).unwrap_or("");
    if sys.contains("harness replanner") {
        HarnessRole::Replanner
    } else if sys.contains("harness evaluator") {
        HarnessRole::Evaluator
    } else if sys.contains("harness planner") {
        HarnessRole::Planner
    } else {
        HarnessRole::Build
    }
}

#[derive(Clone)]
pub struct RoleQueuedProvider {
    pub planner: Arc<Mutex<VecDeque<LLMResponse>>>,
    pub build: Arc<Mutex<VecDeque<LLMResponse>>>,
    pub evaluator: Arc<Mutex<VecDeque<LLMResponse>>>,
    pub replanner: Arc<Mutex<VecDeque<LLMResponse>>>,
    pub requests: Arc<Mutex<Vec<LLMRequest>>>,
}

impl RoleQueuedProvider {
    pub fn new() -> Self {
        Self {
            planner: Arc::new(Mutex::new(VecDeque::new())),
            build: Arc::new(Mutex::new(VecDeque::new())),
            evaluator: Arc::new(Mutex::new(VecDeque::new())),
            replanner: Arc::new(Mutex::new(VecDeque::new())),
            requests: Arc::new(Mutex::new(Vec::new())),
        }
    }

    pub fn planner(&mut self, response: LLMResponse) -> &mut Self {
        self.planner.lock().push_back(response);
        self
    }

    pub fn build(&mut self, response: LLMResponse) -> &mut Self {
        self.build.lock().push_back(response);
        self
    }

    pub fn evaluator(&mut self, response: LLMResponse) -> &mut Self {
        self.evaluator.lock().push_back(response);
        self
    }

    pub fn replanner(&mut self, response: LLMResponse) -> &mut Self {
        self.replanner.lock().push_back(response);
        self
    }

    pub fn recorded_requests(&self) -> Vec<LLMRequest> {
        self.requests.lock().clone()
    }
}

fn default_response_for(role: HarnessRole) -> LLMResponse {
    match role {
        HarnessRole::Planner => json_response(planner_response_json("pwd")),
        HarnessRole::Build => text_response("All requested changes have been applied."),
        HarnessRole::Evaluator => json_response(evaluator_response_json("pass", "default evaluator response", 0)),
        HarnessRole::Replanner => text_response("Revision 1: task is complete."),
    }
}

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

    async fn generate(&self, request: LLMRequest) -> Result<LLMResponse, LLMError> {
        self.requests.lock().push(request.clone());
        let role = harness_role_of(&request);
        let queue = match role {
            HarnessRole::Planner => &self.planner,
            HarnessRole::Build => &self.build,
            HarnessRole::Evaluator => &self.evaluator,
            HarnessRole::Replanner => &self.replanner,
        };
        let mut q = queue.lock();
        if let Some(response) = q.pop_front() {
            Ok(response)
        } else {
            Ok(default_response_for(role))
        }
    }

    fn supported_models(&self) -> Vec<String> {
        vec!["gpt-5.3-codex".to_string()]
    }

    fn validate_request(&self, _request: &LLMRequest) -> Result<(), LLMError> {
        Ok(())
    }
}

pub fn task(title: &str, id: &str) -> Task {
    Task {
        id: id.to_string(),
        title: title.to_string(),
        description: title.to_string(),
        instructions: None,
    }
}

pub fn text_response(text: &str) -> LLMResponse {
    LLMResponse {
        content: Some(text.to_string()),
        model: "gpt-5.3-codex".to_string(),
        finish_reason: FinishReason::Stop,
        ..Default::default()
    }
}

pub fn json_response(value: serde_json::Value) -> LLMResponse {
    text_response(&value.to_string())
}

pub fn tool_call_response(tool_name: &str, args: serde_json::Value) -> LLMResponse {
    LLMResponse {
        content: Some(format!("Calling {tool_name}")),
        tool_calls: Some(vec![ToolCall::function(
            "call-1".to_string(),
            tool_name.to_string(),
            args.to_string(),
        )]),
        model: "gpt-5.3-codex".to_string(),
        finish_reason: FinishReason::ToolCalls,
        ..Default::default()
    }
}

pub fn planner_response_json(verify_command: &str) -> serde_json::Value {
    json!({
        "spec_markdown": "# Execution Spec\n\nImplement the requested change with a resumable tracker.",
        "contract_markdown": format!(
            "# Execution Contract\n\n## Done Criteria\n- Implement the requested change.\n- Verify with `{}`.\n",
            verify_command
        ),
        "task_title": "Planner seeded task",
        "items": [{
            "description": "Implement the requested change",
            "outcome": "The requested change is implemented and tracked.",
            "verify": [verify_command],
        }]
    })
}

pub fn evaluator_response_json(verdict: &str, summary: &str, high_severity_findings: usize) -> serde_json::Value {
    let scores = if verdict.eq_ignore_ascii_case("pass") && high_severity_findings == 0 {
        (5, 5, 5, 5)
    } else {
        (3, 2, 4, 3)
    };
    evaluator_response_json_with_scorecard(verdict, summary, high_severity_findings, scores)
}

pub fn evaluator_response_json_with_scorecard(
    verdict: &str,
    summary: &str,
    high_severity_findings: usize,
    scores: (u8, u8, u8, u8),
) -> serde_json::Value {
    json!({
        "verdict": verdict,
        "summary": summary,
        "high_severity_findings": high_severity_findings,
        "scorecard": {
            "contract_fidelity": scores.0,
            "functionality": scores.1,
            "code_quality": scores.2,
            "verification_integrity": scores.3,
        },
        "findings": [{
            "severity": if high_severity_findings > 0 { "high" } else { "low" },
            "title": summary,
            "detail": summary,
        }],
        "unmet_contract_items": [],
        "residual_risks": [],
        "required_tracker_updates": [],
    })
}

pub fn tool_call_response_with_request_id(tool_name: &str, args: serde_json::Value, request_id: &str) -> LLMResponse {
    let mut response = tool_call_response(tool_name, args);
    response.request_id = Some(request_id.to_string());
    response
}

pub fn workspace_root(temp: &TempDir) -> PathBuf {
    canonicalize(temp.path()).unwrap_or_else(|_| temp.path().to_path_buf())
}

pub async fn make_runner(temp: &TempDir, vt_cfg: VTCodeConfig, session_id: &str) -> AgentRunner {
    make_runner_for_model(temp, vt_cfg, session_id, ModelId::default()).await
}

pub async fn make_runner_for_model(
    temp: &TempDir,
    vt_cfg: VTCodeConfig,
    session_id: &str,
    model: ModelId,
) -> AgentRunner {
    let mut runner = Box::pin(AgentRunner::new_with_bootstrap(
        AgentType::Single,
        model,
        "test-key".to_string(),
        workspace_root(temp),
        session_id.to_string(),
        RunnerSettings { reasoning_effort: None, verbosity: None },
        None,
        ThreadBootstrap::new(None),
        Some(vt_cfg),
        None,
    ))
    .await
    .expect("runner");
    runner.set_quiet(true);
    runner
}

pub async fn seed_tracker(workspace_root: &Path, items: serde_json::Value) {
    let tool =
        TaskTrackerTool::new(workspace_root.to_path_buf(), PlanningWorkflowState::new(workspace_root.to_path_buf()));
    tool.execute(json!({
        "action": "create",
        "title": "Harness hardening",
        "items": items,
    }))
    .await
    .expect("seed tracker");
}

pub fn turn_started_count(results: &TaskResults) -> usize {
    results
        .thread_events
        .iter()
        .filter(|event| matches!(event, ThreadEvent::TurnStarted(_)))
        .count()
}

pub fn harness_events(results: &TaskResults) -> Vec<HarnessEventKind> {
    results
        .thread_events
        .iter()
        .filter_map(|event| match event {
            ThreadEvent::ItemCompleted(ItemCompletedEvent { item }) => match &item.details {
                ThreadItemDetails::Harness(harness) => Some(harness.event.clone()),
                _ => None,
            },
            _ => None,
        })
        .collect()
}

pub fn harness_paths(results: &TaskResults, kind: HarnessEventKind) -> Vec<String> {
    results
        .thread_events
        .iter()
        .filter_map(|event| match event {
            ThreadEvent::ItemCompleted(ItemCompletedEvent { item }) => match &item.details {
                ThreadItemDetails::Harness(harness) if harness.event == kind => harness.path.clone(),
                _ => None,
            },
            _ => None,
        })
        .collect()
}

pub fn completed_tool_invocation_item_id(events: &[ThreadEvent], tool_call_id: &str) -> Option<String> {
    events.iter().find_map(|event| match event {
        ThreadEvent::ItemCompleted(ItemCompletedEvent { item }) => match &item.details {
            ThreadItemDetails::ToolInvocation(details) if details.tool_call_id.as_deref() == Some(tool_call_id) => {
                Some(item.id.clone())
            }
            _ => None,
        },
        _ => None,
    })
}

pub fn completed_tool_output_count(
    events: &[ThreadEvent],
    tool_call_id: &str,
    status: ToolCallStatus,
    call_item_id: &str,
) -> usize {
    events
        .iter()
        .filter(|event| match event {
            ThreadEvent::ItemCompleted(ItemCompletedEvent { item }) => match &item.details {
                ThreadItemDetails::ToolOutput(details) => {
                    details.tool_call_id.as_deref() == Some(tool_call_id)
                        && details.status == status
                        && details.call_id == call_item_id
                }
                _ => false,
            },
            _ => false,
        })
        .count()
}