Skip to main content

vtcode_core/tools/registry/
harness_facade.rs

1//! Harness context accessors for ToolRegistry.
2
3use std::sync::Arc;
4
5use anyhow::Result;
6use serde_json::Value;
7
8use super::HarnessContextSnapshot;
9use super::ToolRegistry;
10use crate::config::constants::tools;
11
12impl ToolRegistry {
13    /// Begin a genuine request, optionally restoring adoption from its persisted
14    /// history or explicit continuation. Internal turns must not reset this latch.
15    pub fn begin_tracker_request(&self, adopted: bool) {
16        self.execution_history.begin_tracker_request();
17        self.harness_context.fetch_origin_attempts.clear();
18        if !adopted {
19            self.set_required_completion_verifiers(Vec::new());
20        }
21        self.harness_context
22            .tracker_adopted
23            .store(adopted, std::sync::atomic::Ordering::Relaxed);
24    }
25
26    /// Successful current-request adoption is independent of compactable history.
27    pub fn tracker_adopted_for_request(&self) -> bool {
28        self.harness_context.tracker_adopted.load(std::sync::atomic::Ordering::Relaxed)
29    }
30
31    /// Attach the canonical queue barrier used by public decision recording.
32    pub fn set_decision_evidence_validator(&self, validator: crate::core::agent::events::DecisionEvidenceValidator) {
33        *self.harness_context.decision_validator.write() = Some(validator);
34    }
35    async fn process_harness_command_session_output(&self, value: Value) -> Result<Value> {
36        let processed = self
37            .process_tool_output(
38                tools::UNIFIED_EXEC,
39                value,
40                false,
41                vtcode_utility_tool_specs::DEFAULT_MAX_OUTPUT_TOKENS,
42            )
43            .await;
44        Ok(super::normalize_tool_output(processed))
45    }
46
47    /// Update harness session identifier used for structured tool telemetry
48    pub fn set_harness_session(&self, session_id: impl Into<String>) {
49        self.harness_context.set_session_id(session_id);
50    }
51
52    /// Update current task identifier used for structured tool telemetry
53    pub fn set_harness_task(&self, task_id: Option<String>) {
54        self.harness_context.set_task_id(task_id);
55    }
56
57    /// Snapshot harness context metadata.
58    pub fn harness_context_snapshot(&self) -> HarnessContextSnapshot {
59        self.harness_context.snapshot()
60    }
61
62    /// Attach the runloop's shared per-tool circuit breaker.
63    pub fn set_shared_circuit_breaker(&self, circuit_breaker: Arc<crate::tools::circuit_breaker::CircuitBreaker>) {
64        if let Ok(mut slot) = self.shared_circuit_breaker.write() {
65            *slot = Some(circuit_breaker);
66        }
67    }
68
69    /// Return the shared per-tool circuit breaker when configured.
70    pub fn shared_circuit_breaker(&self) -> Option<Arc<crate::tools::circuit_breaker::CircuitBreaker>> {
71        self.shared_circuit_breaker.read().unwrap_or_else(|e| e.into_inner()).clone()
72    }
73
74    /// Grant an exact, single-use inspection exemption for a command supplied
75    /// directly by a trusted user. Model tool approval must never call this.
76    pub fn trusted_user_command_exemption(
77        &self,
78        args: &Value,
79    ) -> Result<crate::tools::source_inspection::TrustedCommandExemption> {
80        let cwd = self
81            .pty_manager()
82            .working_dir_candidate(crate::tools::command_args::working_dir_text(args))?;
83        Ok(self
84            .edited_file_monitor_ref()
85            .source_inspection()
86            .scoped_user_command(args, &cwd))
87    }
88
89    /// Execute a harness-owned verification command through the same exec/sandbox
90    /// runtime used by the public `command_session` tool while bypassing the
91    /// model-facing full-auto allow-list gate.
92    pub async fn execute_harness_command_session(&self, args: Value) -> Result<Value> {
93        let value = self.execute_command_session(args).await?;
94        self.process_harness_command_session_output(value).await
95    }
96
97    /// Start a harness-owned PTY command session while retaining the session metadata even when
98    /// the command exits immediately. ACP terminal sessions use explicit release semantics.
99    pub async fn execute_harness_command_session_terminal_run(&self, args: Value) -> Result<Value> {
100        let launch = self.begin_completion_verifier(&args);
101        let result = self.execute_harness_command_session_terminal_run_raw(args.clone()).await;
102        self.observe_completion_verifier(launch, &args, &result);
103        let value = result?;
104        self.observe_completion_mutation(tools::EXEC_COMMAND, &args, &value);
105        self.process_harness_command_session_output(value).await
106    }
107
108    pub async fn read_harness_exec_session_output(&self, session_id: &str, drain: bool) -> Result<Option<String>> {
109        self.exec_sessions.read_session_output(session_id, drain).await
110    }
111
112    /// Observe the owned native terminal session's actual exit for runtime verification.
113    pub async fn harness_exec_session_completed(&self, session_id: &str) -> Result<Option<i32>> {
114        let result = self.exec_sessions.is_session_completed(session_id).await;
115        if let Ok(Some(exit_code)) = result {
116            self.observe_completion_verifier(
117                None,
118                &serde_json::json!({"action":"wait", "session_id":session_id}),
119                &Ok(serde_json::json!({"exit_code":exit_code})),
120            );
121        }
122        result
123    }
124
125    /// Terminate an owned session and retire any active mutation boundary.
126    pub async fn terminate_harness_exec_session(&self, session_id: &str) -> Result<()> {
127        let result = self.exec_sessions.terminate_session(session_id).await;
128        if result.is_ok() {
129            self.observe_completion_verifier(
130                None,
131                &serde_json::json!({"action":"close", "session_id":session_id}),
132                &Ok(serde_json::json!({"success":true})),
133            );
134        }
135        result
136    }
137
138    pub async fn close_harness_exec_session(&self, session_id: &str) -> Result<()> {
139        self.close_exec_session(session_id).await?;
140        self.observe_completion_verifier(
141            None,
142            &serde_json::json!({"action":"close", "session_id":session_id}),
143            &Ok(serde_json::json!({"success":true})),
144        );
145        Ok(())
146    }
147
148    /// Bounded snapshot of all exec sessions still running for turn-end
149    /// diagnostics and telemetry. Newest first; capped by the caller.
150    pub async fn in_progress_exec_sessions(&self, cap: usize) -> Vec<crate::tools::types::VTCodeExecSession> {
151        self.exec_sessions.in_progress_exec_sessions(cap).await
152    }
153
154    pub async fn in_progress_foreground_exec_sessions(
155        &self,
156        cap: usize,
157    ) -> Vec<crate::tools::types::VTCodeExecSession> {
158        self.exec_sessions.in_progress_foreground_exec_sessions(cap).await
159    }
160}