Skip to main content

car_multi/
shared.rs

1//! Shared infrastructure — creates Runtimes that share state, log, and policies.
2
3use car_engine::Runtime;
4use car_eventlog::EventLog;
5use car_policy::PolicyEngine;
6use car_state::StateStore;
7use std::sync::Arc;
8use tokio::sync::{Mutex as TokioMutex, RwLock as TokioRwLock};
9
10/// Factory for creating Runtime instances with shared state, event log, and policies.
11///
12/// In a multi-agent system, all agents see the same state store and write to the
13/// same event log. Each agent gets its own tool set and executor.
14pub struct SharedInfra {
15    pub state: Arc<StateStore>,
16    pub log: Arc<TokioMutex<EventLog>>,
17    pub policies: Arc<TokioRwLock<PolicyEngine>>,
18}
19
20impl SharedInfra {
21    pub fn new() -> Self {
22        Self {
23            state: Arc::new(StateStore::new()),
24            log: Arc::new(TokioMutex::new(EventLog::new())),
25            policies: Arc::new(TokioRwLock::new(PolicyEngine::new())),
26        }
27    }
28
29    /// Create a Runtime that shares this infra's state, log, and policies.
30    ///
31    /// Each runtime gets its own tool set, executor, and idempotency cache.
32    pub fn make_runtime(&self) -> Runtime {
33        Runtime::with_shared(
34            Arc::clone(&self.state),
35            Arc::clone(&self.log),
36            Arc::clone(&self.policies),
37        )
38    }
39
40    /// Create a Runtime with per-agent isolated state overlay.
41    /// Writes go to a local StateStore; reads fall through to shared state.
42    /// Call `AgentContext::merge_to_parent()` after the agent completes.
43    pub fn make_isolated_runtime(
44        &self,
45        agent_name: &str,
46    ) -> (Runtime, crate::task_context::AgentContext) {
47        let ctx = crate::task_context::AgentContext::new(agent_name, Arc::clone(&self.state));
48        let rt = Runtime::with_shared(
49            Arc::clone(&ctx.local_state),
50            Arc::clone(&ctx.local_log),
51            Arc::clone(&self.policies),
52        );
53        (rt, ctx)
54    }
55}
56
57impl Default for SharedInfra {
58    fn default() -> Self {
59        Self::new()
60    }
61}