1use std::sync::Arc;
4use uuid::Uuid;
5
6use crate::gate::Gate;
7use serde::Deserialize;
8use vex_adversarial::{
9 Consensus, ConsensusProtocol, Debate, DebateRound, ShadowAgent, ShadowConfig, Vote,
10};
11use vex_core::{Agent, ContextPacket, Hash};
12use vex_hardware::api::AgentIdentity;
13use vex_llm::Capability;
14use vex_persist::{AuditStore, StorageBackend};
15
16#[derive(Debug, Deserialize)]
17struct ChallengeResponse {
18 is_challenge: bool,
19 confidence: f64,
20 reasoning: String,
21 suggested_revision: Option<String>,
22}
23
24#[derive(Debug, Deserialize)]
25struct VoteResponse {
26 agrees: bool,
27 reflection: String,
28 confidence: f64,
29}
30
31#[derive(Debug, Clone)]
33pub struct ExecutorConfig {
34 pub max_debate_rounds: u32,
36 pub consensus_protocol: ConsensusProtocol,
38 pub enable_adversarial: bool,
40}
41
42impl Default for ExecutorConfig {
43 fn default() -> Self {
44 Self {
45 max_debate_rounds: 3,
46 consensus_protocol: ConsensusProtocol::Majority,
47 enable_adversarial: true,
48 }
49 }
50}
51
52#[derive(Debug, Clone)]
54pub struct ExecutionResult {
55 pub agent_id: Uuid,
57 pub response: String,
59 pub verified: bool,
61 pub confidence: f64,
63 pub context: ContextPacket,
65 pub trace_root: Option<Hash>,
67 pub debate: Option<Debate>,
69 pub evidence: Option<vex_core::audit::EvidenceCapsule>,
71}
72
73use vex_llm::{LlmProvider, LlmRequest};
74
75pub struct AgentExecutor<L: LlmProvider + ?Sized> {
77 pub config: ExecutorConfig,
79 llm: Arc<L>,
81 gate: Arc<dyn Gate>,
83 pub audit_store: Option<Arc<AuditStore<dyn StorageBackend>>>,
85 pub identity: Option<Arc<AgentIdentity>>,
87}
88
89impl<L: LlmProvider + ?Sized> std::fmt::Debug for AgentExecutor<L> {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 f.debug_struct("AgentExecutor")
92 .field("config", &self.config)
93 .field("identity", &self.identity)
94 .finish()
95 }
96}
97
98impl<L: LlmProvider + ?Sized> Clone for AgentExecutor<L> {
99 fn clone(&self) -> Self {
100 Self {
101 config: self.config.clone(),
102 llm: self.llm.clone(),
103 gate: self.gate.clone(),
104 audit_store: self.audit_store.clone(),
105 identity: self.identity.clone(),
106 }
107 }
108}
109
110impl<L: LlmProvider + ?Sized> AgentExecutor<L> {
111 pub fn new(llm: Arc<L>, config: ExecutorConfig, gate: Arc<dyn Gate>) -> Self {
113 Self {
114 config,
115 llm,
116 gate,
117 audit_store: None,
118 identity: None,
119 }
120 }
121
122 pub fn with_identity(
124 mut self,
125 identity: Arc<AgentIdentity>,
126 audit_store: Arc<AuditStore<dyn StorageBackend>>,
127 ) -> Self {
128 self.identity = Some(identity);
129 self.audit_store = Some(audit_store);
130 self
131 }
132
133 pub async fn execute(
135 &self,
136 tenant_id: &str, agent: &mut Agent,
138 prompt: &str,
139 capabilities: Vec<Capability>,
140 ) -> Result<ExecutionResult, String> {
141 let full_prompt = if !agent.context.content.is_empty() {
143 format!(
144 "Previous Context (Time: {}):\n\"{}\"\n\nActive Prompt:\n\"{}\"",
145 agent.context.created_at, agent.context.content, prompt
146 )
147 } else {
148 prompt.to_string()
149 };
150
151 let blue_response = self
152 .llm
153 .complete(LlmRequest::with_role(&agent.config.role, &full_prompt))
154 .await
155 .map_err(|e| e.to_string())?
156 .content;
157
158 let (final_response, verified, confidence, debate) = if self.config.enable_adversarial {
160 self.run_adversarial_verification(agent, prompt, &blue_response)
161 .await?
162 } else {
163 (blue_response, false, 0.5, None)
164 };
165
166 let capsule = self
168 .gate
169 .execute_gate(agent.id, prompt, &final_response, confidence, capabilities)
170 .await;
171
172 if capsule.outcome == "HALT" {
173 return Err(format!("Gate Blocking: {}", capsule.reason_code));
174 }
175
176 let mut context = ContextPacket::new(&final_response);
178 context.source_agent = Some(agent.id);
179 context.importance = confidence;
180
181 agent.context = context.clone();
183 agent.fitness = confidence;
184
185 let result = ExecutionResult {
186 agent_id: agent.id,
187 response: final_response,
188 verified,
189 confidence,
190 trace_root: context.trace_root.clone(),
191 context: context.clone(),
192 debate,
193 evidence: Some(capsule.clone()),
194 };
195
196 if let Some(store) = &self.audit_store {
198 let _ = store
199 .log(
200 tenant_id,
201 vex_core::audit::AuditEventType::AgentExecuted,
202 vex_core::audit::ActorType::Bot(agent.id),
203 Some(agent.id),
204 serde_json::json!({
205 "prompt": prompt,
206 "confidence": confidence,
207 "verified": verified,
208 }),
209 self.identity.as_ref().map(|id| id.as_ref()),
210 Some(capsule.witness_receipt.clone()),
211 capsule.vep_blob.clone(),
212 )
213 .await;
214 }
215
216 Ok(result)
217 }
218
219 async fn run_adversarial_verification(
221 &self,
222 blue_agent: &Agent,
223 _original_prompt: &str,
224 blue_response: &str,
225 ) -> Result<(String, bool, f64, Option<Debate>), String> {
226 let shadow = ShadowAgent::new(blue_agent, ShadowConfig::default());
228
229 let mut debate = Debate::new(blue_agent.id, shadow.agent.id, blue_response);
231
232 let mut consensus = Consensus::new(ConsensusProtocol::WeightedConfidence);
234
235 for round_num in 1..=self.config.max_debate_rounds {
237 let mut challenge_prompt = shadow.challenge_prompt(blue_response);
239 challenge_prompt.push_str("\n\nIMPORTANT: Respond in valid JSON format: {\"is_challenge\": boolean, \"confidence\": float (0.0-1.0), \"reasoning\": \"string\", \"suggested_revision\": \"string\" | null}. If you agree with the statement, set is_challenge to false.");
240
241 let red_output = self
242 .llm
243 .complete(LlmRequest::with_role(
244 &shadow.agent.config.role,
245 &challenge_prompt,
246 ))
247 .await
248 .map_err(|e| e.to_string())?
249 .content;
250
251 let (is_challenge, red_confidence, red_reasoning, _suggested_revision) =
253 if let Some(start) = red_output.find('{') {
254 if let Some(end) = red_output.rfind('}') {
255 if let Ok(res) =
256 serde_json::from_str::<ChallengeResponse>(&red_output[start..=end])
257 {
258 (
259 res.is_challenge,
260 res.confidence,
261 res.reasoning,
262 res.suggested_revision,
263 )
264 } else {
265 (
266 red_output.to_lowercase().contains("disagree"),
267 0.5,
268 red_output.clone(),
269 None,
270 )
271 }
272 } else {
273 (false, 0.0, "Parsing failed".to_string(), None)
274 }
275 } else {
276 (false, 0.0, "No JSON found".to_string(), None)
277 };
278
279 let rebuttal = if is_challenge {
280 let rebuttal_prompt = format!(
281 "Your previous response was challenged by a Red agent:\n\n\
282 Original: \"{}\"\n\n\
283 Challenge: \"{}\"\n\n\
284 Please address these concerns or provide a revised response.",
285 blue_response, red_reasoning
286 );
287 Some(
288 self.llm
289 .complete(LlmRequest::with_role(
290 &blue_agent.config.role,
291 &rebuttal_prompt,
292 ))
293 .await
294 .map_err(|e| e.to_string())?
295 .content,
296 )
297 } else {
298 None
299 };
300
301 debate.add_round(DebateRound {
302 round: round_num,
303 blue_claim: blue_response.to_string(),
304 red_challenge: red_reasoning.clone(),
305 blue_rebuttal: rebuttal,
306 });
307
308 consensus.add_vote(Vote {
310 agent_id: shadow.agent.id,
311 agrees: !is_challenge,
312 confidence: red_confidence,
313 reasoning: Some(red_reasoning),
314 });
315
316 if !is_challenge {
317 break;
318 }
319 }
320
321 let mut reflection_prompt = format!(
323 "You have just finished an adversarial debate about your original response.\n\n\
324 Original Response: \"{}\"\n\n\
325 Debate Rounds:\n",
326 blue_response
327 );
328
329 for (i, round) in debate.rounds.iter().enumerate() {
330 reflection_prompt.push_str(&format!(
331 "Round {}: Red challenged: \"{}\" -> You rebutted: \"{}\"\n",
332 i + 1,
333 round.red_challenge,
334 round.blue_rebuttal.as_deref().unwrap_or("N/A")
335 ));
336 }
337
338 reflection_prompt.push_str("\nBased on this debate, do you still stand by your original response? \
339 Respond in valid JSON: {\"agrees\": boolean, \"confidence\": float (0.0-1.0), \"reasoning\": \"string\"}.");
340
341 let blue_vote_res = self
342 .llm
343 .complete(LlmRequest::with_role(
344 &blue_agent.config.role,
345 &reflection_prompt,
346 ))
347 .await;
348
349 let (blue_agrees, blue_confidence, blue_reasoning) = if let Ok(resp) = blue_vote_res {
350 if let Some(start) = resp.content.find('{') {
351 if let Some(end) = resp.content.rfind('}') {
352 if let Ok(vote) =
353 serde_json::from_str::<VoteResponse>(&resp.content[start..=end])
354 {
355 (vote.agrees, vote.confidence, vote.reflection)
356 } else {
357 (
358 true,
359 blue_agent.fitness.max(0.5f64),
360 "Failed to parse reflection JSON".to_string(),
361 )
362 }
363 } else {
364 (
365 true,
366 blue_agent.fitness.max(0.5f64),
367 "No JSON in reflection".to_string(),
368 )
369 }
370 } else {
371 (
372 true,
373 blue_agent.fitness.max(0.5f64),
374 "No reflection content".to_string(),
375 )
376 }
377 } else {
378 (
379 true,
380 blue_agent.fitness.max(0.5f64),
381 "Reflection LLM call failed".to_string(),
382 )
383 };
384
385 consensus.add_vote(Vote {
386 agent_id: blue_agent.id,
387 agrees: blue_agrees,
388 confidence: blue_confidence.max(0.5f64),
389 reasoning: Some(blue_reasoning),
390 });
391
392 consensus.evaluate();
393
394 let final_response = if consensus.reached && consensus.decision == Some(true) {
396 blue_response.to_string()
397 } else if let Some(last_round) = debate.rounds.last() {
398 last_round
400 .blue_rebuttal
401 .clone()
402 .unwrap_or_else(|| blue_response.to_string())
403 } else {
404 blue_response.to_string()
405 };
406
407 let verified = consensus.reached;
408 let confidence = consensus.confidence;
409
410 debate.conclude(consensus.decision.unwrap_or(true), confidence);
411
412 Ok((final_response, verified, confidence, Some(debate)))
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419 use vex_core::AgentConfig;
420
421 #[tokio::test]
422 async fn test_executor() {
423 use crate::gate::GenericGateMock;
424 use vex_llm::MockProvider;
425 let llm = Arc::new(MockProvider::smart());
426 let gate = Arc::new(GenericGateMock);
427 let config = ExecutorConfig {
428 enable_adversarial: false,
429 ..Default::default()
430 };
431 let executor = AgentExecutor::new(llm, config, gate);
432 let mut agent = Agent::new(AgentConfig::default());
433
434 let result = executor
435 .execute("test-tenant", &mut agent, "Test prompt", vec![])
436 .await
437 .unwrap();
438 assert!(!result.response.is_empty());
439 assert!(!result.verified);
441 }
442}