terraphim_multi_agent 1.0.0

Multi-agent system for Terraphim built on roles with rust-genai integration
Documentation
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
use reqwest::Client;
use serde_json::json;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::timeout;
use tracing::{debug, error, info, warn};

use super::fcctl_bridge::FcctlBridge;
use super::hooks::*;
use super::models::*;
use crate::MultiAgentError;

/// HTTP client for communicating with fcctl-web VM execution API
#[derive(Clone)]
pub struct VmExecutionClient {
    /// HTTP client
    client: Client,
    /// Base URL for the fcctl-web API
    base_url: String,
    /// Default timeout for requests
    timeout: Duration,
    /// Authentication token (if required)
    auth_token: Option<String>,
    /// History bridge (if history tracking is enabled)
    history_bridge: Option<Arc<FcctlBridge>>,
    /// History configuration
    history_config: HistoryConfig,
    /// Hook manager for pre/post processing
    hook_manager: Arc<HookManager>,
}

impl VmExecutionClient {
    /// Create a new VM execution client
    pub fn new(config: &VmExecutionConfig) -> Self {
        let client = Client::builder()
            .timeout(Duration::from_millis(config.execution_timeout_ms))
            .build()
            .expect("Failed to create HTTP client");

        let history_bridge = if config.history.enabled {
            Some(Arc::new(FcctlBridge::new(
                config.history.clone(),
                config.api_base_url.clone(),
            )))
        } else {
            None
        };

        let mut hook_manager = HookManager::new();
        hook_manager.add_hook(Arc::new(DangerousPatternHook::new()));
        hook_manager.add_hook(Arc::new(SyntaxValidationHook::new()));
        hook_manager.add_hook(Arc::new(ExecutionLoggerHook));
        hook_manager.add_hook(Arc::new(OutputSanitizerHook));

        Self {
            client,
            base_url: config.api_base_url.clone(),
            timeout: Duration::from_millis(config.execution_timeout_ms),
            auth_token: None,
            history_bridge,
            history_config: config.history.clone(),
            hook_manager: Arc::new(hook_manager),
        }
    }

    pub fn with_hook_manager(mut self, hook_manager: Arc<HookManager>) -> Self {
        self.hook_manager = hook_manager;
        self
    }

    /// Set authentication token
    pub fn with_auth_token(mut self, token: String) -> Self {
        self.auth_token = Some(token);
        self
    }

    /// Execute code in a VM
    pub async fn execute_code(
        &self,
        request: VmExecuteRequest,
    ) -> Result<VmExecuteResponse, VmExecutionError> {
        let start_time = std::time::Instant::now();

        let pre_context = PreToolContext {
            code: request.code.clone(),
            language: request.language.clone(),
            agent_id: request.agent_id.clone(),
            vm_id: request
                .vm_id
                .clone()
                .unwrap_or_else(|| "default".to_string()),
            metadata: HashMap::new(),
        };

        let pre_decision = self.hook_manager.run_pre_tool(&pre_context).await?;

        let final_code = match pre_decision {
            HookDecision::Block { reason } => {
                return Err(VmExecutionError::ValidationFailed(reason));
            }
            HookDecision::Modify { transformed_code } => {
                info!("Code transformed by hook");
                transformed_code
            }
            HookDecision::AskUser { prompt } => {
                warn!("User confirmation required: {}", prompt);
                request.code.clone()
            }
            HookDecision::Allow => request.code.clone(),
        };

        let final_request = VmExecuteRequest {
            code: final_code,
            ..request
        };

        let url = format!("{}/api/llm/execute", self.base_url);

        debug!(
            "Executing code in VM: language={}, vm_id={:?}",
            final_request.language, final_request.vm_id
        );

        let mut req_builder = self.client.post(&url).json(&final_request);

        if let Some(ref token) = self.auth_token {
            req_builder = req_builder.bearer_auth(token);
        }

        let response = timeout(self.timeout, req_builder.send())
            .await
            .map_err(|_| VmExecutionError::Timeout(self.timeout.as_millis() as u64))?
            .map_err(|e| VmExecutionError::ApiError(e.to_string()))?;

        if response.status().is_success() {
            let execution_result: VmExecuteResponse = response.json().await.map_err(|e| {
                VmExecutionError::ApiError(format!("Failed to parse response: {}", e))
            })?;

            info!(
                "Code execution completed: execution_id={}, exit_code={}",
                execution_result.execution_id, execution_result.exit_code
            );

            let duration_ms = start_time.elapsed().as_millis() as u64;

            let post_context = PostToolContext {
                original_code: final_request.code.clone(),
                output: format!("{}{}", execution_result.stdout, execution_result.stderr),
                exit_code: execution_result.exit_code,
                duration_ms,
                agent_id: final_request.agent_id.clone(),
                vm_id: execution_result.vm_id.clone(),
            };

            let post_decision = self.hook_manager.run_post_tool(&post_context).await?;

            if let HookDecision::Block { reason } = post_decision {
                warn!("Execution output blocked by hook: {}", reason);
                return Err(VmExecutionError::ValidationFailed(reason));
            }

            if let Some(ref bridge) = self.history_bridge {
                if let Err(e) = bridge
                    .track_execution(
                        &execution_result.vm_id,
                        &final_request.agent_id,
                        &final_request,
                        &execution_result,
                    )
                    .await
                {
                    warn!("Failed to track execution in history: {}", e);
                }

                if execution_result.exit_code != 0 && self.history_config.auto_rollback_on_failure {
                    info!(
                        "Execution failed, attempting auto-rollback for VM {}",
                        execution_result.vm_id
                    );
                    if let Err(e) = bridge
                        .auto_rollback_on_failure(&execution_result.vm_id, &final_request.agent_id)
                        .await
                    {
                        error!("Auto-rollback failed: {}", e);
                    }
                }
            }

            Ok(execution_result)
        } else {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            error!("VM execution API error: {}", error_text);
            Err(VmExecutionError::ApiError(format!(
                "HTTP {}: {}",
                status, error_text
            )))
        }
    }

    /// Parse LLM response and potentially execute extracted code
    pub async fn parse_and_execute(
        &self,
        request: ParseExecuteRequest,
    ) -> Result<ParseExecuteResponse, VmExecutionError> {
        let url = format!("{}/api/llm/parse-execute", self.base_url);

        debug!(
            "Parsing LLM response for code execution: auto_execute={}",
            request.auto_execute
        );

        let mut req_builder = self.client.post(&url).json(&request);

        if let Some(ref token) = self.auth_token {
            req_builder = req_builder.bearer_auth(token);
        }

        let response = timeout(self.timeout, req_builder.send())
            .await
            .map_err(|_| VmExecutionError::Timeout(self.timeout.as_millis() as u64))?
            .map_err(|e| VmExecutionError::ApiError(e.to_string()))?;

        if response.status().is_success() {
            let parse_result: ParseExecuteResponse = response.json().await.map_err(|e| {
                VmExecutionError::ApiError(format!("Failed to parse response: {}", e))
            })?;

            info!(
                "Parse-execute completed: found {} code blocks, {} executions",
                parse_result.code_blocks.len(),
                parse_result.execution_results.len()
            );

            Ok(parse_result)
        } else {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            error!("Parse-execute API error: {}", error_text);
            Err(VmExecutionError::ApiError(format!(
                "HTTP {}: {}",
                status, error_text
            )))
        }
    }

    /// Get available VMs for an agent
    pub async fn get_vm_pool(&self, agent_id: &str) -> Result<VmPoolResponse, VmExecutionError> {
        let url = format!("{}/api/llm/vm-pool/{}", self.base_url, agent_id);

        debug!("Getting VM pool for agent: {}", agent_id);

        let mut req_builder = self.client.get(&url);

        if let Some(ref token) = self.auth_token {
            req_builder = req_builder.bearer_auth(token);
        }

        let response = timeout(self.timeout, req_builder.send())
            .await
            .map_err(|_| VmExecutionError::Timeout(self.timeout.as_millis() as u64))?
            .map_err(|e| VmExecutionError::ApiError(e.to_string()))?;

        if response.status().is_success() {
            let pool_info: VmPoolResponse = response.json().await.map_err(|e| {
                VmExecutionError::ApiError(format!("Failed to parse response: {}", e))
            })?;

            debug!(
                "Got VM pool: {} available, {} in use",
                pool_info.available_vms.len(),
                pool_info.in_use_vms.len()
            );

            Ok(pool_info)
        } else {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            error!("VM pool API error: {}", error_text);
            Err(VmExecutionError::ApiError(format!(
                "HTTP {}: {}",
                status, error_text
            )))
        }
    }

    /// Provision a new VM for an agent
    pub async fn provision_vm(
        &self,
        agent_id: &str,
        vm_type: Option<&str>,
    ) -> Result<VmInstance, VmExecutionError> {
        let url = format!("{}/api/vms", self.base_url);

        let vm_type = vm_type.unwrap_or("focal-optimized");
        debug!("Provisioning VM for agent {}: type={}", agent_id, vm_type);

        let request_body = json!({
            "vm_type": vm_type,
            "vm_name": format!("agent-{}-vm", agent_id)
        });

        let mut req_builder = self.client.post(&url).json(&request_body);

        if let Some(ref token) = self.auth_token {
            req_builder = req_builder.bearer_auth(token);
        }

        let response = timeout(self.timeout, req_builder.send())
            .await
            .map_err(|_| VmExecutionError::Timeout(self.timeout.as_millis() as u64))?
            .map_err(|e| VmExecutionError::ApiError(e.to_string()))?;

        if response.status().is_success() {
            let vm_response: serde_json::Value = response.json().await.map_err(|e| {
                VmExecutionError::ApiError(format!("Failed to parse response: {}", e))
            })?;

            let vm_instance = VmInstance {
                id: vm_response["id"].as_str().unwrap_or_default().to_string(),
                name: vm_response["name"].as_str().unwrap_or_default().to_string(),
                vm_type: vm_response["vm_type"]
                    .as_str()
                    .unwrap_or_default()
                    .to_string(),
                status: vm_response["status"]
                    .as_str()
                    .unwrap_or("unknown")
                    .to_string(),
                ip_address: None, // Will be populated when VM is ready
                created_at: chrono::Utc::now(),
                last_activity: None,
            };

            info!(
                "VM provisioned successfully: id={}, name={}",
                vm_instance.id, vm_instance.name
            );
            Ok(vm_instance)
        } else {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            error!("VM provisioning error: {}", error_text);
            Err(VmExecutionError::ApiError(format!(
                "HTTP {}: {}",
                status, error_text
            )))
        }
    }

    /// Wait for VM to be ready
    pub async fn wait_for_vm_ready(
        &self,
        vm_id: &str,
        max_wait_seconds: u64,
    ) -> Result<VmInstance, VmExecutionError> {
        let url = format!("{}/api/vms/{}", self.base_url, vm_id);
        let start_time = std::time::Instant::now();
        let max_duration = Duration::from_secs(max_wait_seconds);

        debug!(
            "Waiting for VM {} to be ready (max wait: {}s)",
            vm_id, max_wait_seconds
        );

        loop {
            if start_time.elapsed() > max_duration {
                return Err(VmExecutionError::Timeout(max_wait_seconds * 1000));
            }

            let mut req_builder = self.client.get(&url);

            if let Some(ref token) = self.auth_token {
                req_builder = req_builder.bearer_auth(token);
            }

            match req_builder.send().await {
                Ok(response) if response.status().is_success() => {
                    if let Ok(vm_data) = response.json::<serde_json::Value>().await {
                        let status = vm_data["status"].as_str().unwrap_or("unknown");

                        if status == "running" || status == "ready" {
                            let vm_instance = VmInstance {
                                id: vm_data["id"].as_str().unwrap_or_default().to_string(),
                                name: vm_data["name"].as_str().unwrap_or_default().to_string(),
                                vm_type: vm_data["vm_type"]
                                    .as_str()
                                    .unwrap_or_default()
                                    .to_string(),
                                status: status.to_string(),
                                ip_address: vm_data["ip_address"].as_str().map(|s| s.to_string()),
                                created_at: chrono::Utc::now(),
                                last_activity: Some(chrono::Utc::now()),
                            };

                            info!("VM {} is ready", vm_id);
                            return Ok(vm_instance);
                        } else {
                            debug!("VM {} status: {} (waiting...)", vm_id, status);
                        }
                    }
                }
                Ok(response) => {
                    warn!("VM status check failed: HTTP {}", response.status());
                }
                Err(e) => {
                    warn!("VM status check error: {}", e);
                }
            }

            // Wait 2 seconds before next check
            tokio::time::sleep(Duration::from_secs(2)).await;
        }
    }

    /// Health check for the VM execution service
    pub async fn health_check(&self) -> Result<bool, VmExecutionError> {
        let url = format!("{}/health", self.base_url);

        let response = timeout(Duration::from_secs(5), self.client.get(&url).send())
            .await
            .map_err(|_| VmExecutionError::Timeout(5000))?
            .map_err(|e| VmExecutionError::ApiError(e.to_string()))?;

        Ok(response.status().is_success())
    }

    /// Query command history for a VM
    pub async fn query_history(
        &self,
        request: HistoryQueryRequest,
    ) -> Result<HistoryQueryResponse, VmExecutionError> {
        if let Some(ref bridge) = self.history_bridge {
            bridge.query_history(request).await
        } else {
            Err(VmExecutionError::HistoryError(
                "History tracking is not enabled".to_string(),
            ))
        }
    }

    /// Rollback VM to a previous snapshot
    pub async fn rollback_to_snapshot(
        &self,
        request: RollbackRequest,
    ) -> Result<RollbackResponse, VmExecutionError> {
        if let Some(ref bridge) = self.history_bridge {
            bridge.rollback_to_snapshot(request).await
        } else {
            Err(VmExecutionError::HistoryError(
                "History tracking is not enabled".to_string(),
            ))
        }
    }

    /// Get the last successful snapshot for a VM
    pub async fn get_last_successful_snapshot(
        &self,
        vm_id: &str,
        agent_id: &str,
    ) -> Option<String> {
        if let Some(ref bridge) = self.history_bridge {
            bridge.get_last_successful_snapshot(vm_id, agent_id).await
        } else {
            None
        }
    }

    /// Query command history failures only
    pub async fn query_failures(
        &self,
        vm_id: &str,
        agent_id: Option<String>,
        limit: Option<usize>,
    ) -> Result<HistoryQueryResponse, VmExecutionError> {
        let request = HistoryQueryRequest {
            vm_id: vm_id.to_string(),
            agent_id,
            limit,
            failures_only: true,
            start_date: None,
            end_date: None,
        };
        self.query_history(request).await
    }

    /// Quick rollback to last successful state
    pub async fn rollback_to_last_success(
        &self,
        vm_id: &str,
        agent_id: &str,
    ) -> Result<RollbackResponse, VmExecutionError> {
        let snapshot_id = self
            .get_last_successful_snapshot(vm_id, agent_id)
            .await
            .ok_or_else(|| {
                VmExecutionError::SnapshotNotFound("No successful snapshot found".to_string())
            })?;

        let request = RollbackRequest {
            vm_id: vm_id.to_string(),
            snapshot_id,
            create_pre_rollback_snapshot: true,
        };

        self.rollback_to_snapshot(request).await
    }
}

/// Convenience methods for common operations
impl VmExecutionClient {
    /// Execute Python code with automatic VM provisioning
    pub async fn execute_python(
        &self,
        agent_id: &str,
        code: &str,
    ) -> Result<VmExecuteResponse, VmExecutionError> {
        let request = VmExecuteRequest {
            agent_id: agent_id.to_string(),
            language: "python".to_string(),
            code: code.to_string(),
            vm_id: None, // Auto-provision
            requirements: vec![],
            timeout_seconds: Some(30),
            working_dir: None,
            metadata: None,
        };

        self.execute_code(request).await
    }

    /// Execute JavaScript code with automatic VM provisioning
    pub async fn execute_javascript(
        &self,
        agent_id: &str,
        code: &str,
    ) -> Result<VmExecuteResponse, VmExecutionError> {
        let request = VmExecuteRequest {
            agent_id: agent_id.to_string(),
            language: "javascript".to_string(),
            code: code.to_string(),
            vm_id: None,
            requirements: vec![],
            timeout_seconds: Some(30),
            working_dir: None,
            metadata: None,
        };

        self.execute_code(request).await
    }

    /// Execute bash command with automatic VM provisioning
    pub async fn execute_bash(
        &self,
        agent_id: &str,
        command: &str,
    ) -> Result<VmExecuteResponse, VmExecutionError> {
        let request = VmExecuteRequest {
            agent_id: agent_id.to_string(),
            language: "bash".to_string(),
            code: command.to_string(),
            vm_id: None,
            requirements: vec![],
            timeout_seconds: Some(30),
            working_dir: None,
            metadata: None,
        };

        self.execute_code(request).await
    }
}

/// Convert VmExecutionError to MultiAgentError
impl From<VmExecutionError> for MultiAgentError {
    fn from(error: VmExecutionError) -> Self {
        MultiAgentError::External(format!("VM execution error: {}", error))
    }
}

impl std::fmt::Debug for VmExecutionClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VmExecutionClient")
            .field("base_url", &self.base_url)
            .field("timeout", &self.timeout)
            .field("has_auth_token", &self.auth_token.is_some())
            .field("has_history_bridge", &self.history_bridge.is_some())
            .field("history_config", &self.history_config)
            .field("hooks_count", &"<hook_manager>")
            .finish()
    }
}