Skip to main content

aither_agent/
tool_request.rs

1//! Generic request/response channel helpers for UI-mediated tools.
2
3use std::collections::{BTreeMap, HashMap};
4use std::sync::atomic::{AtomicU64, Ordering};
5
6use arc_swap::{ArcSwap, Guard};
7use async_channel::{Receiver, Sender};
8
9const ERR_TOOL_REQUEST_UNAVAILABLE: &str = include_str!("texts/tool_request_unavailable.txt");
10const ERR_TOOL_REQUEST_CANCELLED: &str = include_str!("texts/tool_request_cancelled.txt");
11
12/// A UI-bound request carrying tool arguments and a response sender.
13#[derive(Debug)]
14pub struct ToolRequest<Args, Response> {
15    /// Tool arguments provided by the agent.
16    pub args: Args,
17    response_tx: Sender<Response>,
18}
19
20impl<Args, Response> ToolRequest<Args, Response> {
21    /// Create a new request with its response channel.
22    #[must_use]
23    pub const fn new(args: Args, response_tx: Sender<Response>) -> Self {
24        Self { args, response_tx }
25    }
26
27    /// Respond to the request without blocking the UI thread.
28    ///
29    /// # Errors
30    ///
31    /// Returns the response back if the requester has already given up waiting.
32    pub fn respond(self, response: Response) -> Result<(), async_channel::TrySendError<Response>> {
33        self.response_tx.try_send(response)
34    }
35}
36
37/// Request broker for UI-mediated tools.
38#[derive(Debug, Clone)]
39pub struct ToolRequestBroker<Args, Response> {
40    tx: Sender<ToolRequest<Args, Response>>,
41}
42
43impl<Args, Response> ToolRequestBroker<Args, Response> {
44    /// Send a request and await the response.
45    ///
46    /// # Errors
47    ///
48    /// Returns an error if the queue has been dropped, which means no UI is
49    /// listening for tool requests any more.
50    pub async fn request(&self, args: Args) -> anyhow::Result<Response> {
51        let (response_tx, response_rx) = async_channel::bounded(1);
52        self.tx
53            .send(ToolRequest::new(args, response_tx))
54            .await
55            .map_err(|_| anyhow::anyhow!(ERR_TOOL_REQUEST_UNAVAILABLE.trim()))?;
56
57        response_rx
58            .recv()
59            .await
60            .map_err(|_| anyhow::anyhow!(ERR_TOOL_REQUEST_CANCELLED.trim()))
61    }
62}
63
64/// Queue for pending tool requests.
65#[derive(Debug)]
66pub struct ToolRequestQueue<Args, Response> {
67    rx: Receiver<ToolRequest<Args, Response>>,
68}
69
70impl<Args, Response> ToolRequestQueue<Args, Response> {
71    /// Await the next request.
72    pub async fn next(&self) -> Option<ToolRequest<Args, Response>> {
73        self.rx.recv().await.ok()
74    }
75
76    /// Returns true if there are no pending requests.
77    #[must_use]
78    pub fn is_empty(&self) -> bool {
79        self.rx.is_empty()
80    }
81}
82
83/// Create a new request broker/queue pair.
84#[must_use]
85pub fn channel<Args, Response>() -> (
86    ToolRequestBroker<Args, Response>,
87    ToolRequestQueue<Args, Response>,
88) {
89    let (tx, rx) = async_channel::unbounded();
90    (ToolRequestBroker { tx }, ToolRequestQueue { rx })
91}
92
93/// Create a bounded request broker/queue pair with explicit backpressure.
94///
95/// # Panics
96///
97/// Panics if `capacity` is zero, which would deadlock every request.
98#[must_use]
99pub fn bounded_channel<Args, Response>(
100    capacity: usize,
101) -> (
102    ToolRequestBroker<Args, Response>,
103    ToolRequestQueue<Args, Response>,
104) {
105    assert!(capacity > 0, "tool request queue capacity must be > 0");
106    let (tx, rx) = async_channel::bounded(capacity);
107    (ToolRequestBroker { tx }, ToolRequestQueue { rx })
108}
109
110// ── RequestApprover ─────────────────────────────────────────
111
112struct PendingEntry<P, R> {
113    order: u64,
114    payload: P,
115    tx: Sender<R>,
116}
117
118struct RequestApproverState<P, R> {
119    order: BTreeMap<u64, String>,
120    pending: HashMap<String, PendingEntry<P, R>>,
121}
122
123impl<P: Clone, R> Clone for PendingEntry<P, R> {
124    fn clone(&self) -> Self {
125        Self {
126            order: self.order,
127            payload: self.payload.clone(),
128            tx: self.tx.clone(),
129        }
130    }
131}
132
133impl<P: Clone, R> Clone for RequestApproverState<P, R> {
134    fn clone(&self) -> Self {
135        Self {
136            order: self.order.clone(),
137            pending: self.pending.clone(),
138        }
139    }
140}
141
142/// An ID-tracked, multi-request approval queue for server contexts.
143///
144/// Each request is assigned a unique ID, stored in FIFO order, and awaits
145/// a response from the UI/caller side. Designed for web-server polling patterns
146/// where the UI fetches pending requests and responds asynchronously.
147///
148/// Use [`event_listener::EventListener`] from [`listen`](Self::listen) to
149/// efficiently wait for state changes without polling.
150///
151/// # Type Parameters
152///
153/// - `P`: Payload type (cloneable request data visible to the UI).
154/// - `R`: Response type sent back to the requester.
155pub struct RequestApprover<P, R> {
156    state: ArcSwap<RequestApproverState<P, R>>,
157    event: event_listener::Event,
158    next_id: AtomicU64,
159}
160
161impl<P, R> std::fmt::Debug for RequestApprover<P, R> {
162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        let pending_count = self.state.load().pending.len();
164        f.debug_struct("RequestApprover")
165            .field("pending_count", &pending_count)
166            .field("next_id", &self.next_id.load(Ordering::Relaxed))
167            .finish_non_exhaustive()
168    }
169}
170
171impl<P: Clone, R> Default for RequestApprover<P, R> {
172    fn default() -> Self {
173        Self::new()
174    }
175}
176
177impl<P: Clone, R> RequestApprover<P, R> {
178    /// Create a new empty approver.
179    #[must_use]
180    pub fn new() -> Self {
181        Self {
182            state: ArcSwap::from_pointee(RequestApproverState {
183                order: BTreeMap::new(),
184                pending: HashMap::new(),
185            }),
186            event: event_listener::Event::new(),
187            next_id: AtomicU64::new(0),
188        }
189    }
190
191    /// Enqueue a request and return its ID and a receiver for the response.
192    ///
193    /// The returned [`Receiver`] yields the response once [`respond`](Self::respond)
194    /// is called with the matching ID.
195    ///
196    /// # Panics
197    ///
198    /// Panics if the request lock was poisoned by a panic in another thread.
199    pub fn enqueue(&self, payload: P) -> (String, Receiver<R>) {
200        let order = self.next_id.fetch_add(1, Ordering::Relaxed);
201        let id = order.to_string();
202        let (tx, rx) = async_channel::bounded(1);
203        let entry = PendingEntry { order, payload, tx };
204        self.state.rcu(|state| {
205            let mut next = state.as_ref().clone();
206            next.order.insert(order, id.clone());
207            next.pending.insert(id.clone(), entry.clone());
208            next
209        });
210        self.event.notify(usize::MAX);
211        (id, rx)
212    }
213
214    /// Respond to a pending request by ID.
215    ///
216    /// Returns `true` if the request was found and the response was sent.
217    ///
218    /// # Panics
219    ///
220    /// Panics if the request lock was poisoned by a panic in another thread.
221    pub fn respond(&self, id: &str, response: R) -> bool {
222        let mut found = None;
223        loop {
224            let current = self.state.load_full();
225            let Some(entry) = current.pending.get(id).cloned() else {
226                break;
227            };
228            let mut next = current.as_ref().clone();
229            next.pending.remove(id);
230            next.order.remove(&entry.order);
231            let previous = Guard::into_inner(
232                self.state
233                    .compare_and_swap(&current, std::sync::Arc::new(next)),
234            );
235            if std::sync::Arc::ptr_eq(&current, &previous) {
236                found = Some(entry);
237                break;
238            }
239        }
240        self.event.notify(usize::MAX);
241        found.is_some_and(|entry| entry.tx.try_send(response).is_ok())
242    }
243
244    /// Return the oldest pending request (ID + cloned payload) without removing it.
245    ///
246    /// # Panics
247    ///
248    /// Panics if the request lock was poisoned by a panic in another thread.
249    #[must_use]
250    pub fn peek(&self) -> Option<(String, P)> {
251        let state = self.state.load();
252        let (_order, id) = state.order.iter().next()?;
253        state
254            .pending
255            .get(id.as_str())
256            .map(|entry| (id.clone(), entry.payload.clone()))
257    }
258
259    /// Return the oldest pending request matching a predicate.
260    ///
261    /// # Panics
262    ///
263    /// Panics if the request lock was poisoned by a panic in another thread.
264    #[must_use]
265    pub fn peek_filtered(&self, predicate: impl Fn(&P) -> bool) -> Option<(String, P)> {
266        let state = self.state.load();
267        for id in state.order.values() {
268            let Some(entry) = state.pending.get(id.as_str()) else {
269                continue;
270            };
271            if predicate(&entry.payload) {
272                return Some((id.clone(), entry.payload.clone()));
273            }
274        }
275        None
276    }
277
278    /// Get a cloned payload by request ID.
279    ///
280    /// # Panics
281    ///
282    /// Panics if the request lock was poisoned by a panic in another thread.
283    #[must_use]
284    pub fn get_payload(&self, id: &str) -> Option<P> {
285        self.state
286            .load()
287            .pending
288            .get(id)
289            .map(|entry| entry.payload.clone())
290    }
291
292    /// Returns `true` if there are no pending requests.
293    ///
294    /// # Panics
295    ///
296    /// Panics if the request lock was poisoned by a panic in another thread.
297    #[must_use]
298    pub fn is_empty(&self) -> bool {
299        self.state.load().pending.is_empty()
300    }
301
302    /// Create a listener that resolves when the approver state changes.
303    ///
304    /// Use this for efficient async polling:
305    /// ```rust,ignore
306    /// loop {
307    ///     if let Some((id, payload)) = approver.peek() {
308    ///         // handle request
309    ///     }
310    ///     approver.listen().await;
311    /// }
312    /// ```
313    pub fn listen(&self) -> event_listener::EventListener {
314        self.event.listen()
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::RequestApprover;
321
322    #[test]
323    fn peek_returns_requests_in_fifo_order() {
324        let approver = RequestApprover::<&'static str, ()>::new();
325        let _first = approver.enqueue("first");
326        let _second = approver.enqueue("second");
327
328        let peeked = approver.peek().expect("first request should be visible");
329        assert_eq!(peeked, ("0".to_string(), "first"));
330    }
331
332    #[test]
333    fn peek_skips_resolved_requests() {
334        let approver = RequestApprover::<&'static str, ()>::new();
335        let (first_id, first_rx) = approver.enqueue("first");
336        let _second = approver.enqueue("second");
337
338        assert!(approver.respond(&first_id, ()));
339        drop(first_rx);
340
341        let peeked = approver.peek().expect("second request should remain");
342        assert_eq!(peeked, ("1".to_string(), "second"));
343    }
344}