1#![warn(missing_docs)]
2
3use infinity_agent_core::message::InputMessage;
10use infinity_agent_core::system::local::ChannelSender;
11use infinity_agent_core::tools::Tool;
12use infinity_agent_core::tools::rap_tool::RapTool;
13use infinity_agent_core::traits::InputSender;
14use rap_client::callback_server::{bind_callback_listener, start_callback_server_on};
15use rap_client::http::{InMemoryToolsetCache, SimpleHttpClient};
16use rap_client::notifier::RapNotifier;
17use rap_client::toolset_loader::ToolsetLoader;
18use rap_protocol::{RapCallback, RapViewUpdate};
19
20mod callback;
21use callback::convert_callback;
22use tokio::sync::mpsc;
23
24pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
26
27#[derive(Debug)]
29pub enum CallbackDelivery {
30 Input {
32 message: Box<InputMessage>,
34 dedup_id: String,
36 },
37 ViewUpdate(RapViewUpdate),
39}
40
41pub fn prepare_callback(callback: RapCallback) -> CallbackDelivery {
43 if let RapCallback::ViewUpdate(update) = callback {
44 return CallbackDelivery::ViewUpdate(update);
45 }
46
47 let dedup_id = match &callback {
48 RapCallback::ToolResult(result) => format!("rap-tool-result-{}", result.id),
49 RapCallback::OAuth(oauth) => format!("rap-oauth-{}", oauth.id),
50 RapCallback::UserChoice(choice) => format!("rap-user-choice-{}", choice.id),
51 RapCallback::SubscriptionEvent(_) => uuid::Uuid::new_v4().to_string(),
54 RapCallback::ViewUpdate(_) => unreachable!("view update returned above"),
55 };
56 let message = convert_callback(callback).expect("bug: non-view RAP callback must convert");
57 CallbackDelivery::Input {
58 message: Box::new(message),
59 dedup_id,
60 }
61}
62
63pub struct RapCallbackBridge {
65 listener: tokio::net::TcpListener,
66 callback_url: String,
67}
68
69impl RapCallbackBridge {
70 pub async fn bind() -> Result<Self, BoxError> {
72 let (listener, callback_url) = bind_callback_listener().await?;
73 Ok(Self {
74 listener,
75 callback_url,
76 })
77 }
78
79 pub fn from_listener(listener: tokio::net::TcpListener) -> Result<Self, BoxError> {
81 let callback_url = format!("http://127.0.0.1:{}", listener.local_addr()?.port());
82 Ok(Self {
83 listener,
84 callback_url,
85 })
86 }
87
88 pub fn callback_url(&self) -> &str {
90 &self.callback_url
91 }
92
93 pub fn serve_into<S>(
104 self,
105 sender: S,
106 ) -> (
107 mpsc::UnboundedReceiver<RapViewUpdate>,
108 tokio::task::JoinHandle<()>,
109 )
110 where
111 S: InputSender + 'static,
112 {
113 let (view_tx, view_rx) = mpsc::unbounded_channel();
114 let task = start_callback_server_on(self.listener, move |callback| {
115 let sender = sender.clone();
116 let view_tx = view_tx.clone();
117 async move {
118 match prepare_callback(callback) {
119 CallbackDelivery::Input { message, dedup_id } => {
120 if let Err(error) = sender.send_to_input_queue(*message, &dedup_id).await {
121 tracing::warn!(%error, "failed to route RAP callback");
122 }
123 }
124 CallbackDelivery::ViewUpdate(update) => {
125 if view_tx.send(update).is_err() {
126 tracing::warn!("RAP view-update destination has stopped");
127 }
128 }
129 }
130 }
131 });
132 (view_rx, task)
133 }
134}
135
136pub struct RapToolSet {
142 tools: Vec<RapTool<SimpleHttpClient>>,
143 server_urls: Vec<String>,
144}
145
146impl RapToolSet {
147 pub async fn connect(
153 server_urls: impl IntoIterator<Item = String>,
154 session_id: &rap_protocol::ThreadId<str>,
155 callback_url: impl Into<String>,
156 ) -> Result<Self, BoxError> {
157 let server_urls: Vec<String> = server_urls.into_iter().collect();
158 let callback_url = callback_url.into();
159 let http = SimpleHttpClient::new();
160 let loaded = ToolsetLoader::new(http.clone(), InMemoryToolsetCache::new())
161 .load_toolsets(&server_urls, session_id)
162 .await?;
163
164 let mut tools = Vec::new();
165 for toolset in loaded {
166 let endpoint = toolset.manifest.endpoint;
167 for definition in toolset.manifest.tools {
168 tools.push(RapTool {
169 descriptor: definition.into(),
170 endpoint: endpoint.clone(),
171 http_client: http.clone(),
172 callback_url: Some(callback_url.clone()),
173 });
174 }
175 }
176
177 Ok(Self { tools, server_urls })
178 }
179
180 pub fn tools(&self) -> Vec<Box<dyn Tool<ChannelSender>>> {
182 self.tools
183 .iter()
184 .cloned()
185 .map(|tool| Box::new(tool) as Box<dyn Tool<ChannelSender>>)
186 .collect()
187 }
188
189 pub fn notifier(&self) -> RapNotifier<SimpleHttpClient> {
191 RapNotifier::new(self.server_urls.clone(), SimpleHttpClient::new())
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198 use async_trait::async_trait;
199 use rap_protocol::{
200 RapOAuth, RapSubscriptionEvent, RapToolResult, RapUserChoice, RapViewUpdate,
201 };
202 use std::sync::{Arc, Mutex};
203
204 #[test]
205 fn stable_dedup_for_single_callbacks() {
206 let cases = [
207 (
208 RapCallback::ToolResult(RapToolResult {
209 group_id: "g".into(),
210 id: "call".into(),
211 call_id: None,
212 text: Some("done".into()),
213 content: None,
214 display_as: None,
215 subscription: None,
216 }),
217 "rap-tool-result-call",
218 ),
219 (
220 RapCallback::OAuth(RapOAuth {
221 group_id: "g".into(),
222 id: "auth".into(),
223 call_id: None,
224 auth_url: "https://example.com".into(),
225 }),
226 "rap-oauth-auth",
227 ),
228 (
229 RapCallback::UserChoice(RapUserChoice {
230 group_id: "g".into(),
231 id: "choice".into(),
232 call_id: None,
233 prompt: "pick".into(),
234 choices: vec!["a".into()],
235 default: 0,
236 response_url: "https://example.com".into(),
237 }),
238 "rap-user-choice-choice",
239 ),
240 ];
241 for (callback, expected) in cases {
242 let CallbackDelivery::Input { dedup_id, .. } = prepare_callback(callback) else {
243 panic!("expected agent input")
244 };
245 assert_eq!(dedup_id, expected);
246 }
247 }
248
249 #[test]
250 fn repeated_subscription_events_are_not_deduplicated() {
251 let callback = || {
252 RapCallback::SubscriptionEvent(RapSubscriptionEvent {
253 group_id: "g".into(),
254 tool_call_id: "call".into(),
255 text: "tick".into(),
256 associative: false,
257 r#final: None,
258 })
259 };
260 let CallbackDelivery::Input {
261 dedup_id: first, ..
262 } = prepare_callback(callback())
263 else {
264 panic!("expected agent input")
265 };
266 let CallbackDelivery::Input {
267 dedup_id: second, ..
268 } = prepare_callback(callback())
269 else {
270 panic!("expected agent input")
271 };
272 assert_ne!(first, second);
273 }
274
275 #[test]
276 fn view_update_remains_out_of_agent_history() {
277 let CallbackDelivery::ViewUpdate(update) =
278 prepare_callback(RapCallback::ViewUpdate(RapViewUpdate {
279 group_id: "g".into(),
280 view_type: "diff".into(),
281 content: serde_json::json!({}),
282 }))
283 else {
284 panic!("expected view update")
285 };
286 assert_eq!(update.view_type, "diff");
287 }
288
289 #[derive(Clone, Default)]
291 struct RecordingSender {
292 sent: Arc<Mutex<Vec<(rap_protocol::ThreadId, String)>>>,
293 }
294
295 #[derive(Debug)]
296 struct RecordingSendError;
297
298 impl std::fmt::Display for RecordingSendError {
299 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
300 write!(f, "recording sender never fails")
301 }
302 }
303
304 impl std::error::Error for RecordingSendError {}
305
306 #[async_trait]
307 impl InputSender for RecordingSender {
308 type Error = RecordingSendError;
309
310 async fn send_to_input_queue(
311 &self,
312 message: InputMessage,
313 dedup_id: &str,
314 ) -> Result<(), RecordingSendError> {
315 self.sent
316 .lock()
317 .expect("bug: test mutex poisoned")
318 .push((message.group_id, dedup_id.to_owned()));
319 Ok(())
320 }
321 }
322
323 #[tokio::test]
326 async fn serve_into_forwards_inputs_and_emits_views() {
327 use rap_client::http::HttpClient;
328
329 let bridge = RapCallbackBridge::bind().await.expect("bind listener");
330 let url = bridge.callback_url().to_owned();
331 let sender = RecordingSender::default();
332 let (mut views, _server_task) = bridge.serve_into(sender.clone());
333
334 let http = SimpleHttpClient::new();
335 let tool_result = serde_json::to_string(&RapCallback::ToolResult(RapToolResult {
336 group_id: "t1".into(),
337 id: "call-1".into(),
338 call_id: None,
339 text: Some("done".into()),
340 content: None,
341 display_as: None,
342 subscription: None,
343 }))
344 .expect("serialize tool result callback");
345 assert_eq!(http.post(&url, &tool_result).await.expect("post"), 200);
348 assert_eq!(
349 sender
350 .sent
351 .lock()
352 .expect("bug: test mutex poisoned")
353 .as_slice(),
354 &[("t1".into(), "rap-tool-result-call-1".to_owned())]
355 );
356
357 let view = serde_json::to_string(&RapCallback::ViewUpdate(RapViewUpdate {
358 group_id: "t1".into(),
359 view_type: "diff".into(),
360 content: serde_json::json!({ "lines": 3 }),
361 }))
362 .expect("serialize view update callback");
363 assert_eq!(http.post(&url, &view).await.expect("post"), 200);
364 let update = tokio::time::timeout(std::time::Duration::from_secs(5), views.recv())
365 .await
366 .expect("timed out waiting for the view update")
367 .expect("view channel closed");
368 assert_eq!(update.view_type, "diff");
369 assert_eq!(
370 sender.sent.lock().expect("bug: test mutex poisoned").len(),
371 1,
372 "view updates must not become agent input"
373 );
374 }
375}