Skip to main content

autoagents_core/
environment.rs

1use crate::error::Error;
2use crate::protocol::{Event, RuntimeID};
3use crate::runtime::manager::RuntimeManager;
4use crate::runtime::{Runtime, RuntimeError};
5use crate::utils::BoxEventStream;
6use std::path::PathBuf;
7use std::sync::Arc;
8use tokio::task::JoinHandle;
9
10/// Errors emitted when managing runtimes and consuming event receivers
11#[derive(Debug, thiserror::Error)]
12pub enum EnvironmentError {
13    #[error("Runtime not found: {0}")]
14    RuntimeNotFound(RuntimeID),
15
16    #[error("Runtime error: {0}")]
17    RuntimeError(#[from] RuntimeError),
18
19    #[error("Error when consuming receiver")]
20    EventError,
21}
22
23/// Configuration for the process environment that owns one or more runtimes.
24#[derive(Clone)]
25pub struct EnvironmentConfig {
26    pub working_dir: PathBuf,
27}
28
29impl Default for EnvironmentConfig {
30    fn default() -> Self {
31        Self {
32            working_dir: std::env::current_dir().unwrap_or_default(),
33        }
34    }
35}
36
37/// High-level container that owns one or more runtimes, exposes a unified
38/// event receiver, and provides lifecycle helpers for running and shutting down
39/// the underlying actor system.
40pub struct Environment {
41    config: EnvironmentConfig,
42    runtime_manager: Arc<RuntimeManager>,
43    default_runtime: Option<RuntimeID>,
44    handle: Option<JoinHandle<Result<(), RuntimeError>>>,
45}
46
47impl Environment {
48    /// Create a new environment with optional configuration.
49    pub fn new(config: Option<EnvironmentConfig>) -> Self {
50        let config = config.unwrap_or_default();
51        let runtime_manager = Arc::new(RuntimeManager::new());
52
53        Self {
54            config,
55            runtime_manager,
56            default_runtime: None,
57            handle: None,
58        }
59    }
60
61    /// Register a runtime with this environment and make it the default if none
62    /// is set yet.
63    pub async fn register_runtime(&mut self, runtime: Arc<dyn Runtime>) -> Result<(), Error> {
64        self.runtime_manager
65            .register_runtime(runtime.clone())
66            .await?;
67        if self.default_runtime.is_none() {
68            self.default_runtime = Some(runtime.id());
69        }
70        Ok(())
71    }
72
73    /// Access the environment configuration.
74    pub fn config(&self) -> &EnvironmentConfig {
75        &self.config
76    }
77
78    /// Get a runtime by its id, if present.
79    pub async fn get_runtime(&self, runtime_id: &RuntimeID) -> Option<Arc<dyn Runtime>> {
80        self.runtime_manager.get_runtime(runtime_id).await
81    }
82
83    /// Get the specified runtime or the default one when `None` is passed.
84    pub async fn get_runtime_or_default(
85        &self,
86        runtime_id: Option<RuntimeID>,
87    ) -> Result<Arc<dyn Runtime>, Error> {
88        let rid = runtime_id.unwrap_or(self.default_runtime.unwrap());
89        self.get_runtime(&rid)
90            .await
91            .ok_or_else(|| EnvironmentError::RuntimeNotFound(rid).into())
92    }
93
94    /// Start all registered runtimes and return a handle that resolves when
95    /// they finish. This will typically run until shutdown is requested.
96    pub fn run(&mut self) -> JoinHandle<Result<(), RuntimeError>> {
97        let manager = self.runtime_manager.clone();
98        // Spawn background task to run the runtimes. This will wait indefinitely
99        tokio::spawn(async move { manager.run().await })
100    }
101
102    /// Start all registered runtimes and return immediately without waiting
103    /// for completion.
104    pub async fn run_background(&mut self) -> Result<(), RuntimeError> {
105        let manager = self.runtime_manager.clone();
106        // Spawn background task to run the runtimes.
107        manager.run_background().await
108    }
109
110    /// Take the event receiver for a specific runtime (or the default one) so
111    /// the caller can consume protocol events. This can only be taken once.
112    pub async fn take_event_receiver(
113        &mut self,
114        runtime_id: Option<RuntimeID>,
115    ) -> Result<BoxEventStream<Event>, EnvironmentError> {
116        if let Ok(runtime) = self.get_runtime_or_default(runtime_id).await {
117            runtime
118                .take_event_receiver()
119                .await
120                .ok_or_else(|| EnvironmentError::EventError)
121        } else {
122            Err(EnvironmentError::RuntimeNotFound(runtime_id.unwrap()))
123        }
124    }
125
126    /// Request shutdown on all runtimes and await the run handle if present.
127    pub async fn shutdown(&mut self) {
128        let _ = self.runtime_manager.stop().await;
129
130        if let Some(handle) = self.handle.take() {
131            let _ = handle.await;
132        }
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use crate::runtime::SingleThreadedRuntime;
139
140    use super::*;
141    use uuid::Uuid;
142
143    #[test]
144    fn test_environment_config_default() {
145        let config = EnvironmentConfig::default();
146        assert_eq!(
147            config.working_dir,
148            std::env::current_dir().unwrap_or_default()
149        );
150    }
151
152    #[test]
153    fn test_environment_config_custom() {
154        let config = EnvironmentConfig {
155            working_dir: std::path::PathBuf::from("/tmp"),
156        };
157        assert_eq!(config.working_dir, std::path::PathBuf::from("/tmp"));
158    }
159
160    #[tokio::test]
161    async fn test_environment_get_runtime() {
162        let mut env = Environment::new(None);
163        let runtime = SingleThreadedRuntime::new(None);
164        let runtime_id = runtime.id;
165        env.register_runtime(runtime).await.unwrap();
166
167        // Test getting default runtime
168        let runtime = env.get_runtime(&runtime_id).await;
169
170        assert!(runtime.is_some());
171
172        // Test getting non-existent runtime
173        let non_existent_id = Uuid::new_v4();
174        let runtime = env.get_runtime(&non_existent_id).await;
175        assert!(runtime.is_none());
176    }
177
178    #[tokio::test]
179    async fn test_environment_take_event_receiver() {
180        let mut env = Environment::new(None);
181        let runtime = SingleThreadedRuntime::new(None);
182        let _ = runtime.id;
183        env.register_runtime(runtime).await.unwrap();
184        let receiver = env.take_event_receiver(None).await;
185        assert!(receiver.is_ok());
186
187        // Second call should return None
188        let receiver2 = env.take_event_receiver(None).await;
189        assert!(receiver2.is_err());
190    }
191
192    #[tokio::test]
193    async fn test_environment_shutdown() {
194        let mut env = Environment::new(None);
195        env.shutdown().await;
196        // Should not panic
197    }
198
199    #[tokio::test]
200    async fn test_environment_error_runtime_not_found() {
201        let mut env = Environment::new(None);
202        let runtime = SingleThreadedRuntime::new(None);
203        let _ = runtime.id;
204        env.register_runtime(runtime).await.unwrap();
205        let non_existent_id = Uuid::new_v4();
206
207        let result = env.get_runtime_or_default(Some(non_existent_id)).await;
208        assert!(result.is_err());
209
210        assert!(result.is_err());
211        // Just test that it's an error, not the specific variant
212        assert!(result.is_err());
213    }
214
215    #[test]
216    fn test_environment_error_display() {
217        let runtime_id = Uuid::new_v4();
218        let error = EnvironmentError::RuntimeNotFound(runtime_id);
219        assert!(error.to_string().contains("Runtime not found"));
220        assert!(error.to_string().contains(&runtime_id.to_string()));
221    }
222}