Skip to main content

rpi_agent/
tool_execution_scope.rs

1//! Host-managed child execution identity and background FFI driver lifetime.
2use std::future::Future;
3use std::sync::atomic::{AtomicUsize, Ordering};
4use std::sync::Arc;
5use tokio::sync::Notify;
6
7tokio::task_local! {
8    static CURRENT: Arc<ToolExecutionScope>;
9    static INVOCATION_SIGNAL: tokio_util::sync::CancellationToken;
10}
11
12/// Bind a runtime action to the originating tool invocation, even after its
13/// dispatch has moved off the foreign thread. This is host-only state, not JSON.
14pub async fn with_invocation_signal<F: Future>(
15    signal: tokio_util::sync::CancellationToken,
16    future: F,
17) -> F::Output {
18    INVOCATION_SIGNAL.scope(signal, future).await
19}
20
21pub fn invocation_signal() -> Option<tokio_util::sync::CancellationToken> {
22    INVOCATION_SIGNAL.try_with(Clone::clone).ok()
23}
24
25/// Shared by a child's run, tools, providers and detached foreign callbacks.
26#[derive(Default)]
27pub struct ToolExecutionScope {
28    pending: AtomicUsize,
29    idle: Notify,
30    context: Option<serde_json::Value>,
31}
32impl ToolExecutionScope {
33    pub fn with_context(context: serde_json::Value) -> Self {
34        Self {
35            context: Some(context),
36            ..Default::default()
37        }
38    }
39    /// Bind the task-local identity without an extra async state machine. An
40    /// async wrapper would reserve storage for both `future` and its moved copy
41    /// inside `TaskLocalFuture`, doubling large callers' inline future size.
42    /// Tokio installs the identity only while polling or dropping the future.
43    pub fn run<F: Future>(self: &Arc<Self>, future: F) -> impl Future<Output = F::Output> {
44        CURRENT.scope(self.clone(), future)
45    }
46
47    /// Foreground cancellation is not proof that foreign code has returned.
48    pub async fn wait_idle(&self) {
49        loop {
50            let notified = self.idle.notified();
51            tokio::pin!(notified);
52            notified.as_mut().enable();
53            if self.pending.load(Ordering::Acquire) == 0 {
54                return;
55            }
56            notified.await;
57        }
58    }
59}
60
61pub fn current_scope() -> Option<Arc<ToolExecutionScope>> {
62    CURRENT.try_with(Clone::clone).ok()
63}
64
65pub fn is_child_execution() -> bool {
66    CURRENT.try_with(|_| ()).is_ok()
67}
68pub fn execution_context() -> Option<serde_json::Value> {
69    CURRENT
70        .try_with(|scope| scope.context.clone())
71        .ok()
72        .flatten()
73}
74
75/// Tool bindings exposed by GetExecutionContext. The scope also carries
76/// host-only state used by built-in tools and access checks.
77pub fn public_execution_context() -> Option<serde_json::Value> {
78    let mut context = execution_context()?;
79    context
80        .as_object_mut()?
81        .retain(|key, _| matches!(key.as_str(), "model" | "thinkingLevel" | "tools"));
82    Some(context)
83}
84
85/// A blocking driver owns this guard until its final foreign callback returns.
86pub struct BackgroundToolGuard(Arc<ToolExecutionScope>);
87impl Drop for BackgroundToolGuard {
88    fn drop(&mut self) {
89        if self.0.pending.fetch_sub(1, Ordering::AcqRel) == 1 {
90            self.0.idle.notify_waiters();
91        }
92    }
93}
94pub fn track_background_tool() -> Option<BackgroundToolGuard> {
95    CURRENT
96        .try_with(|scope| {
97            scope.pending.fetch_add(1, Ordering::AcqRel);
98            BackgroundToolGuard(scope.clone())
99        })
100        .ok()
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[tokio::test]
108    async fn scoping_does_not_duplicate_the_inner_future_storage() {
109        let scope = Arc::new(ToolExecutionScope::default());
110        let future = scope.run(std::future::ready([7_u8; 16 * 1024]));
111        // A task-local binding needs a little metadata, not another payload-sized
112        // slot for moving an async function's argument into its awaited future.
113        assert!(std::mem::size_of_val(&future) <= 16 * 1024 + 128);
114        assert!(!is_child_execution());
115        assert_eq!(future.await, [7_u8; 16 * 1024]);
116        assert!(!is_child_execution());
117    }
118
119    #[tokio::test]
120    async fn identity_and_context_are_scoped_and_never_leak_to_the_parent() {
121        let scope = Arc::new(ToolExecutionScope::with_context(
122            serde_json::json!({"nativeDurableActor":"child-1","tools":["read"]}),
123        ));
124        assert!(!is_child_execution());
125        scope
126            .run(async {
127                assert!(is_child_execution());
128                assert_eq!(
129                    execution_context().unwrap()["nativeDurableActor"],
130                    "child-1"
131                );
132                assert_eq!(
133                    public_execution_context().unwrap(),
134                    serde_json::json!({"tools":["read"]})
135                );
136                tokio::task::yield_now().await;
137                assert!(Arc::ptr_eq(&current_scope().unwrap(), &scope));
138            })
139            .await;
140        assert!(!is_child_execution());
141        assert!(execution_context().is_none());
142        assert!(track_background_tool().is_none());
143    }
144    #[tokio::test]
145    async fn invocation_cancellation_crosses_dispatch_without_changing_child_identity() {
146        let token = tokio_util::sync::CancellationToken::new();
147        assert!(invocation_signal().is_none());
148        let captured = with_invocation_signal(token.clone(), async {
149            assert!(!is_child_execution());
150            let child = Arc::new(ToolExecutionScope::default());
151            child
152                .run(async {
153                    assert!(is_child_execution());
154                    invocation_signal().unwrap()
155                })
156                .await
157        })
158        .await;
159        assert!(invocation_signal().is_none());
160        assert!(!captured.is_cancelled());
161        token.cancel();
162        assert!(captured.is_cancelled());
163    }
164    #[tokio::test]
165    async fn cancellation_drops_under_the_scope_and_allows_reuse() {
166        struct CheckDrop(Arc<AtomicUsize>);
167        impl Drop for CheckDrop {
168            fn drop(&mut self) {
169                assert!(is_child_execution());
170                self.0.fetch_add(1, Ordering::Relaxed);
171            }
172        }
173        let scope = Arc::new(ToolExecutionScope::default());
174        let drops = Arc::new(AtomicUsize::new(0));
175        let future = scope.run(async {
176            let _guard = CheckDrop(drops.clone());
177            std::future::pending::<()>().await;
178        });
179        assert!(!is_child_execution());
180        assert!(
181            tokio::time::timeout(std::time::Duration::from_millis(5), future)
182                .await
183                .is_err()
184        );
185        assert_eq!(drops.load(Ordering::Relaxed), 1);
186        assert!(!is_child_execution());
187        scope.run(async { assert!(is_child_execution()) }).await;
188        assert!(!is_child_execution());
189    }
190
191    #[tokio::test]
192    async fn dropping_the_foreground_scope_does_not_finish_its_background_work() {
193        let scope = Arc::new(ToolExecutionScope::default());
194        let guard = scope.run(async { track_background_tool().unwrap() }).await;
195        assert!(
196            tokio::time::timeout(std::time::Duration::from_millis(5), scope.wait_idle())
197                .await
198                .is_err()
199        );
200        drop(guard);
201        tokio::time::timeout(std::time::Duration::from_secs(1), scope.wait_idle())
202            .await
203            .unwrap();
204    }
205}