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    /// Makes in-process [`AgentKind::Harness`] session turns copy from the
35    /// per-project Cargo caches under `cache_root`; call it after
36    /// [`Self::with_native_harness`], without which it has no effect.
37    #[must_use]
38    pub fn with_trusted_cargo_cache(mut self, cache_root: PathBuf) -> Self {
39        self.native_harness = self
40            .native_harness
41            .map(|config| config.with_trusted_cargo_cache(cache_root));
42
43        self
44    }
45
46    /// Composes a fresh runtime for one worker-owned session.
47    pub fn session(&self, kind: AgentKind) -> SessionRuntime {
48        SessionRuntime {
49            channel: ag_agent::create_agent_channel(
50                kind,
51                self.app_server.clone(),
52                self.native_harness.as_ref(),
53            ),
54        }
55    }
56
57    /// Composes pooled utility execution with adapter-owned cleanup.
58    pub fn utility(&self) -> UtilityRuntime {
59        let client = ag_agent::RealOneShotClient::pooled(self.app_server.clone());
60        let client = match &self.native_harness {
61            Some(config) => client.with_native_harness(config.clone()),
62            None => client,
63        };
64
65        UtilityRuntime {
66            client: Arc::new(client),
67        }
68    }
69}
70
71/// Session runtime whose concrete adapter never escapes to application code.
72#[derive(Clone)]
73pub struct SessionRuntime {
74    channel: Arc<dyn AgentChannel>,
75}
76
77impl SessionRuntime {
78    /// Dispatches an admitted turn to the selected harness adapter.
79    pub fn run_turn(
80        &self,
81        id: String,
82        request: TurnRequest,
83        events: mpsc::UnboundedSender<TurnEvent>,
84    ) -> AgentFuture<Result<TurnResult, AgentError>> {
85        self.channel.run_turn(id, request, events)
86    }
87
88    /// Delivers one user prompt into the selected harness's running session
89    /// turn; errors leave the prompt undelivered.
90    pub fn steer_turn(
91        &self,
92        id: String,
93        prompt: TurnPrompt,
94    ) -> AgentFuture<Result<(), AgentError>> {
95        self.channel.steer_turn(id, prompt)
96    }
97
98    /// Releases resources belonging to the selected harness session.
99    pub fn shutdown(&self, id: String) -> AgentFuture<Result<(), AgentError>> {
100        self.channel.shutdown_session(id)
101    }
102}
103
104/// Runtime-owned isolated execution and provider cleanup.
105pub struct UtilityRuntime {
106    client: Arc<dyn OneShotClient>,
107}
108
109impl UtilityRuntime {
110    /// Runs one worker-admitted utility request and awaits cancellation
111    /// cleanup.
112    ///
113    /// # Errors
114    /// Returns the provider failure or cancellation diagnostic.
115    pub async fn submit_cancellable(
116        &self,
117        request: OneShotRequest,
118        cancellation: CancellationToken,
119    ) -> Result<OneShotSubmission, OneShotError> {
120        self.client.submit_cancellable(request, cancellation).await
121    }
122
123    /// Releases pooled runtimes after admitted utility work settles.
124    pub async fn close(&self) {
125        self.client.close().await;
126    }
127
128    /// Escalates cleanup after the worker's graceful shutdown deadline.
129    pub fn force_shutdown(&self) {
130        self.client.force_shutdown();
131    }
132}
133
134#[cfg(feature = "test-utils")]
135#[path = "test_support_test.rs"]
136pub mod test_support;