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