Skip to main content

everruns_capabilities/
platform_store.rs

1// Platform Store trait: the hosted seam behind agent delegation.
2//
3// Decision: Trait lives in this crate; implementations in server/worker crates
4// Decision: PlatformMessage is a simplified view (role + text + timestamp)
5// Decision: scope is the catalog-backed `platform` command surface plus the
6//   narrow session/agent/harness reads delegation needs. The org-scoped CRUD
7//   half was retired with `platform_management` (EVE-953); management flows
8//   go through the domain-command catalog instead.
9
10use async_trait::async_trait;
11use everruns_contracts::error::Result;
12use everruns_contracts::typed_id::SessionParticipantId;
13use everruns_core::{AgentDefinition, ExecutionSession, HarnessDefinition};
14
15use everruns_contracts::typed_id::{AgentId, HarnessId, SessionId};
16
17// The narrow session-delegation DTOs live in `everruns-core` (they are part of
18// the `SubagentSessionDelegate` contract portable code depends on); the full
19// `PlatformStore` reuses them. See EVE-839.
20pub use everruns_core::subagent_delegation::{PlatformCreateSessionRequest, PlatformMessage};
21
22/// Hosted command and delegation services, phrased entirely in runtime views.
23///
24/// Hosts resolve persistence records, inheritance, and authorization at their
25/// edge. Capability code never needs a control-plane agent, harness, or session.
26#[async_trait]
27pub trait PlatformStore: Send + Sync {
28    fn for_execution(
29        &self,
30        _input_message_id: uuid::Uuid,
31    ) -> Option<std::sync::Arc<dyn PlatformStore>> {
32        None
33    }
34
35    // =========================================================================
36    // Catalog-backed command surface
37    // =========================================================================
38
39    /// Search the authoritative domain-command catalog.
40    async fn platform_discover(&self, _arguments: serde_json::Value) -> Result<String> {
41        Err(everruns_contracts::error::AgentLoopError::config(
42            "Platform command surface is not available in this host",
43        ))
44    }
45
46    /// Execute a bounded script against read-only domain commands.
47    async fn platform_query(&self, _arguments: serde_json::Value) -> Result<String> {
48        Err(everruns_contracts::error::AgentLoopError::config(
49            "Platform command surface is not available in this host",
50        ))
51    }
52
53    /// Execute a bounded script against the full authorized command catalog.
54    async fn platform_execute(&self, _arguments: serde_json::Value) -> Result<String> {
55        Err(everruns_contracts::error::AgentLoopError::config(
56            "Platform command surface is not available in this host",
57        ))
58    }
59
60    // =========================================================================
61    // Harness Operations
62    // =========================================================================
63
64    /// Resolve the effective, inheritance-folded harness configuration by ID.
65    async fn get_harness(&self, id: HarnessId) -> Result<Option<HarnessDefinition>>;
66
67    // =========================================================================
68    // Agent Operations
69    // =========================================================================
70
71    /// Get an agent by public ID.
72    async fn get_agent_by_id(&self, id: AgentId) -> Result<Option<AgentDefinition>>;
73
74    // =========================================================================
75    // Session Operations
76    // =========================================================================
77
78    /// Create a session for delegation (subagents, handoff, A2A).
79    ///
80    /// Required rather than defaulted: the flat `create_session` it used to
81    /// delegate to was legacy CRUD with no remaining callers, and every
82    /// implementation already overrode this method to honour the fields that
83    /// default could not express (goal, lineage, budget root, seed mode).
84    async fn create_session_with_options(
85        &self,
86        request: PlatformCreateSessionRequest,
87    ) -> Result<ExecutionSession>;
88
89    /// Get a session by ID.
90    async fn get_session_by_id(&self, id: SessionId) -> Result<Option<ExecutionSession>>;
91
92    /// Add an agent as a member participant in an existing session.
93    async fn add_agent_session_participant(
94        &self,
95        session_id: SessionId,
96        agent_id: AgentId,
97    ) -> Result<SessionParticipantId>;
98
99    // =========================================================================
100    // Messaging
101    // =========================================================================
102
103    /// Send a user message to a session, triggering a turn.
104    async fn send_message(&self, session_id: SessionId, content: &str) -> Result<()>;
105
106    /// Get messages from a session (most recent first).
107    /// Default limit is 10.
108    async fn get_messages(
109        &self,
110        session_id: SessionId,
111        limit: Option<usize>,
112    ) -> Result<Vec<PlatformMessage>>;
113
114    // =========================================================================
115    // Turn Management
116    // =========================================================================
117
118    /// Wait for a session to become idle (turn completed).
119    /// Returns the final session status as a string.
120    /// Default timeout is 120 seconds.
121    async fn wait_for_idle(
122        &self,
123        session_id: SessionId,
124        timeout_secs: Option<u64>,
125    ) -> Result<String>;
126}
127
128/// Typed [`ToolContext`](everruns_core::tool_context::ToolContext) extension carrying the
129/// hosted `PlatformStore` (EVE-839). Replaces the former
130/// `ToolContext::platform_store` field; hosted capabilities resolve it via
131/// `context.extension::<PlatformStoreExt>()`.
132#[derive(Clone)]
133pub struct PlatformStoreExt(pub std::sync::Arc<dyn PlatformStore>);
134
135/// Adapter implementing core's narrow
136/// [`SubagentSessionDelegate`](everruns_core::subagent_delegation::SubagentSessionDelegate)
137/// over a runtime-only `PlatformStore`, so hosted subagent/handoff orchestration can
138/// drive child sessions without depending on the hosted seam.
139pub struct PlatformStoreSubagentDelegate(pub std::sync::Arc<dyn PlatformStore>);
140
141#[async_trait]
142impl everruns_core::subagent_delegation::SubagentSessionDelegate for PlatformStoreSubagentDelegate {
143    async fn get_agent_by_id(&self, id: AgentId) -> Result<Option<everruns_core::AgentDefinition>> {
144        self.0.get_agent_by_id(id).await
145    }
146    async fn get_harness(&self, id: HarnessId) -> Result<Option<HarnessDefinition>> {
147        self.0.get_harness(id).await
148    }
149    async fn add_agent_session_participant(
150        &self,
151        session_id: SessionId,
152        agent_id: AgentId,
153    ) -> Result<SessionParticipantId> {
154        self.0
155            .add_agent_session_participant(session_id, agent_id)
156            .await
157    }
158    async fn create_session_with_options(
159        &self,
160        request: PlatformCreateSessionRequest,
161    ) -> Result<ExecutionSession> {
162        self.0.create_session_with_options(request).await
163    }
164    async fn get_session_by_id(&self, id: SessionId) -> Result<Option<ExecutionSession>> {
165        self.0.get_session_by_id(id).await
166    }
167    async fn send_message(&self, session_id: SessionId, content: &str) -> Result<()> {
168        self.0.send_message(session_id, content).await
169    }
170    async fn get_messages(
171        &self,
172        session_id: SessionId,
173        limit: Option<usize>,
174    ) -> Result<Vec<PlatformMessage>> {
175        self.0.get_messages(session_id, limit).await
176    }
177    async fn wait_for_idle(
178        &self,
179        session_id: SessionId,
180        timeout_secs: Option<u64>,
181    ) -> Result<String> {
182        self.0.wait_for_idle(session_id, timeout_secs).await
183    }
184}
185
186#[cfg(test)]
187pub mod tests {
188    use super::*;
189    use everruns_contracts::CapabilityRef as AgentCapabilityConfig;
190
191    /// Mock PlatformStore for unit tests.
192    ///
193    /// Shared across test modules so that any test exercising
194    /// platform management tools (directly or via ActAtom) uses
195    /// the same mock. This prevents wiring bugs where a tool is
196    /// registered but the store is not passed through.
197    pub struct MockPlatformStore {
198        pub harness: HarnessDefinition,
199        pub extra_harnesses:
200            std::sync::Mutex<std::collections::HashMap<HarnessId, HarnessDefinition>>,
201        pub agent: AgentDefinition,
202        pub session: ExecutionSession,
203        pub extra_sessions:
204            std::sync::Mutex<std::collections::HashMap<SessionId, ExecutionSession>>,
205        pub joined_participants: std::sync::Mutex<Vec<(SessionId, AgentId)>>,
206        /// Records the `harness_id` argument of every `create_session`
207        /// call so tests can assert which harness a child session was
208        /// created against. See `start_handoff_uses_target_harness_not_parent`.
209        pub created_session_harness_ids: std::sync::Mutex<Vec<HarnessId>>,
210        /// Records internal budget-root overrides supplied to session creation.
211        pub created_session_budget_roots: std::sync::Mutex<Vec<Option<SessionId>>>,
212        /// Status returned by `wait_for_idle` ("idle" by default). Tests set
213        /// a terminal turn status (e.g. "completed") to exercise settle paths.
214        pub wait_for_idle_status: std::sync::Mutex<String>,
215        /// Records every `send_message` call as `(session_id, content)` so
216        /// tests can assert which session was signaled (e.g. a detached peer
217        /// receiving a cooperative-cancel message).
218        pub sent_messages: std::sync::Mutex<Vec<(SessionId, String)>>,
219    }
220
221    impl Default for MockPlatformStore {
222        fn default() -> Self {
223            Self::new()
224        }
225    }
226
227    impl MockPlatformStore {
228        pub fn new() -> Self {
229            Self {
230                harness: HarnessDefinition {
231                    capabilities: vec![AgentCapabilityConfig::new("session")],
232                    ..HarnessDefinition::new("test-harness", "You are helpful.")
233                },
234                extra_harnesses: std::sync::Mutex::new(std::collections::HashMap::new()),
235                agent: AgentDefinition {
236                    display_name: Some("Test Agent".to_string()),
237                    description: Some("test agent".to_string()),
238                    ..AgentDefinition::new(AgentId::new(), "test-agent", "You are helpful.")
239                },
240                session: {
241                    let id = SessionId::new();
242                    let mut session = ExecutionSession::new(
243                        id,
244                        everruns_contracts::typed_id::WorkspaceId::from_uuid(id.uuid()),
245                        HarnessId::new(),
246                    );
247                    session.title = Some("Test Session".to_string());
248                    session.status = everruns_core::session::SessionExecutionState::Idle;
249                    session
250                },
251                extra_sessions: std::sync::Mutex::new(std::collections::HashMap::new()),
252                joined_participants: std::sync::Mutex::new(Vec::new()),
253                created_session_harness_ids: std::sync::Mutex::new(Vec::new()),
254                created_session_budget_roots: std::sync::Mutex::new(Vec::new()),
255                wait_for_idle_status: std::sync::Mutex::new("idle".to_string()),
256                sent_messages: std::sync::Mutex::new(Vec::new()),
257            }
258        }
259    }
260
261    #[async_trait]
262    impl PlatformStore for MockPlatformStore {
263        async fn platform_discover(&self, arguments: serde_json::Value) -> Result<String> {
264            Ok(arguments.to_string())
265        }
266
267        async fn platform_query(&self, arguments: serde_json::Value) -> Result<String> {
268            Ok(arguments.to_string())
269        }
270
271        async fn platform_execute(&self, arguments: serde_json::Value) -> Result<String> {
272            Ok(arguments.to_string())
273        }
274
275        async fn get_harness(&self, id: HarnessId) -> Result<Option<HarnessDefinition>> {
276            if let Some(harness) = self.extra_harnesses.lock().unwrap().get(&id).cloned() {
277                return Ok(Some(harness));
278            }
279            Ok(Some(self.harness.clone()))
280        }
281        async fn get_agent_by_id(
282            &self,
283            _id: everruns_contracts::typed_id::AgentId,
284        ) -> Result<Option<AgentDefinition>> {
285            Ok(Some(self.agent.clone()))
286        }
287        async fn create_session_with_options(
288            &self,
289            request: PlatformCreateSessionRequest,
290        ) -> Result<ExecutionSession> {
291            self.created_session_budget_roots
292                .lock()
293                .expect("budget root recorder")
294                .push(request.budget_root_session_id);
295            if let Ok(mut recorder) = self.created_session_harness_ids.lock() {
296                recorder.push(request.harness_id);
297            }
298            let mut session = self.session.clone();
299            session.id = SessionId::new();
300            session.harness_id = request.harness_id;
301            session.agent_id = request.agent_id;
302            session.title = request.title.clone();
303            session.locale = request.locale.clone();
304            session.blueprint_id = request.blueprint_id.clone();
305            session.blueprint_config = request.blueprint_config.clone();
306            session.parent_session_id = request.parent_session_id;
307            session.goal = request.goal;
308            session.forked_from_session_id = request.forked_from_session_id;
309            if let Ok(mut sessions) = self.extra_sessions.lock() {
310                sessions.insert(session.id, session.clone());
311            }
312            Ok(session)
313        }
314        async fn get_session_by_id(&self, id: SessionId) -> Result<Option<ExecutionSession>> {
315            if id == self.session.id {
316                return Ok(Some(self.session.clone()));
317            }
318            if let Some(session) = self
319                .extra_sessions
320                .lock()
321                .ok()
322                .and_then(|sessions| sessions.get(&id).cloned())
323            {
324                return Ok(Some(session));
325            }
326            Ok(Some(self.session.clone()))
327        }
328        async fn add_agent_session_participant(
329            &self,
330            session_id: SessionId,
331            agent_id: AgentId,
332        ) -> Result<SessionParticipantId> {
333            self.joined_participants
334                .lock()
335                .unwrap()
336                .push((session_id, agent_id));
337            Ok(SessionParticipantId::new())
338        }
339        async fn send_message(&self, id: SessionId, content: &str) -> Result<()> {
340            self.sent_messages
341                .lock()
342                .unwrap()
343                .push((id, content.to_string()));
344            Ok(())
345        }
346        async fn get_messages(
347            &self,
348            _id: SessionId,
349            _limit: Option<usize>,
350        ) -> Result<Vec<PlatformMessage>> {
351            Ok(vec![
352                PlatformMessage {
353                    role: "user".into(),
354                    content: "Hello".into(),
355                    created_at: chrono::Utc::now(),
356                },
357                PlatformMessage {
358                    role: "agent".into(),
359                    content: "Hi!".into(),
360                    created_at: chrono::Utc::now(),
361                },
362            ])
363        }
364        async fn wait_for_idle(&self, _id: SessionId, _t: Option<u64>) -> Result<String> {
365            Ok(self.wait_for_idle_status.lock().unwrap().clone())
366        }
367    }
368}