Skip to main content

ag_runtime/
runtime.rs

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