Skip to main content

ag_runtime/
runtime.rs

1use std::sync::Arc;
2
3use ag_contracts::{
4    AgentChannel, AgentError, AgentFuture, OneShotClient, OneShotError, OneShotRequest,
5    OneShotSubmission, TurnEvent, TurnRequest, TurnResult,
6};
7use ag_session::AgentKind;
8use tokio::sync::mpsc;
9use tokio_util::sync::CancellationToken;
10
11/// Provider composition configuration. Constructing it starts no processes.
12#[derive(Clone, Default)]
13pub struct RuntimeFactory {
14    app_server: Option<Arc<dyn ag_agent::AppServerClient>>,
15}
16
17impl RuntimeFactory {
18    /// Composes a fresh runtime for one worker-owned session.
19    pub fn session(&self, kind: AgentKind) -> SessionRuntime {
20        SessionRuntime {
21            channel: ag_agent::create_agent_channel(kind, self.app_server.clone()),
22        }
23    }
24
25    /// Composes pooled utility execution with adapter-owned cleanup.
26    pub fn utility(&self) -> UtilityRuntime {
27        UtilityRuntime {
28            client: Arc::new(ag_agent::RealOneShotClient::pooled(self.app_server.clone())),
29        }
30    }
31}
32
33/// Session runtime whose concrete adapter never escapes to application code.
34#[derive(Clone)]
35pub struct SessionRuntime {
36    channel: Arc<dyn AgentChannel>,
37}
38
39impl SessionRuntime {
40    /// Dispatches an admitted turn to the selected harness adapter.
41    pub fn run_turn(
42        &self,
43        id: String,
44        request: TurnRequest,
45        events: mpsc::UnboundedSender<TurnEvent>,
46    ) -> AgentFuture<Result<TurnResult, AgentError>> {
47        self.channel.run_turn(id, request, events)
48    }
49
50    /// Releases resources belonging to the selected harness session.
51    pub fn shutdown(&self, id: String) -> AgentFuture<Result<(), AgentError>> {
52        self.channel.shutdown_session(id)
53    }
54}
55
56/// Runtime-owned isolated execution and provider cleanup.
57pub struct UtilityRuntime {
58    client: Arc<dyn OneShotClient>,
59}
60
61impl UtilityRuntime {
62    /// Runs one worker-admitted utility request and awaits cancellation
63    /// cleanup.
64    ///
65    /// # Errors
66    /// Returns the provider failure or cancellation diagnostic.
67    pub async fn submit_cancellable(
68        &self,
69        request: OneShotRequest,
70        cancellation: CancellationToken,
71    ) -> Result<OneShotSubmission, OneShotError> {
72        self.client.submit_cancellable(request, cancellation).await
73    }
74
75    /// Releases pooled runtimes after admitted utility work settles.
76    pub async fn close(&self) {
77        self.client.close().await;
78    }
79
80    /// Escalates cleanup after the worker's graceful shutdown deadline.
81    pub fn force_shutdown(&self) {
82        self.client.force_shutdown();
83    }
84}
85
86#[cfg(feature = "test-utils")]
87#[path = "test_support_test.rs"]
88pub mod test_support;