Skip to main content

ag_runtime/
runtime.rs

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