Skip to main content

nexo_plugin_browser/
plugin.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use async_trait::async_trait;
5use base64::Engine;
6use tokio::sync::Mutex;
7use tokio_util::sync::CancellationToken;
8
9use uuid::Uuid;
10
11use nexo_broker::{AnyBroker, BrokerHandle, Event};
12use nexo_config::BrowserConfig;
13use nexo_core::agent::{Command, Plugin, Response};
14use nexo_resilience::{CircuitBreaker, CircuitBreakerConfig};
15
16use crate::cdp::{CdpClient, CdpSession};
17use crate::chrome::ChromeLauncher;
18use crate::chrome::RunningChrome;
19use crate::command::{BrowserCmd, BrowserResult};
20
21/// All shared mutable state used by both the direct `send_command` path and
22/// the broker-driven task spawned in `start`. Held behind `Arc` so cloning
23/// the plugin into a background task is cheap and doesn't duplicate state.
24pub(crate) struct BrowserInner {
25    pub(crate) config: BrowserConfig,
26    pub(crate) session: Mutex<Option<CdpSession>>,
27    pub(crate) chrome: Mutex<Option<RunningChrome>>,
28    pub(crate) circuit: CircuitBreaker,
29    pub(crate) broker: Mutex<Option<AnyBroker>>,
30    pub(crate) event_forwarder_started: Mutex<bool>,
31}
32
33impl BrowserInner {
34    fn new(config: BrowserConfig) -> Self {
35        Self {
36            config,
37            session: Mutex::new(None),
38            chrome: Mutex::new(None),
39            circuit: CircuitBreaker::new("plugin.browser", CircuitBreakerConfig::default()),
40            broker: Mutex::new(None),
41            event_forwarder_started: Mutex::new(false),
42        }
43    }
44
45    async fn ensure_session(self: &Arc<Self>) -> anyhow::Result<()> {
46        let mut session_lock = self.session.lock().await;
47        if session_lock.is_some() {
48            return Ok(());
49        }
50
51        let ws_url = if self.config.cdp_url.is_empty() {
52            let chrome = ChromeLauncher::launch(&self.config).await?;
53            let ws = chrome.ws_url.clone();
54            *self.chrome.lock().await = Some(chrome);
55            ws
56        } else {
57            ChromeLauncher::connect_existing(&self.config.cdp_url, self.config.connect_timeout_ms)
58                .await?
59        };
60
61        let client = Arc::new(CdpClient::connect(&ws_url).await?);
62
63        // Enable Page domain so Chrome emits navigation/load events. Errors
64        // here are non-fatal — the forwarder still starts, just quieter.
65        if let Err(e) = client.send("Page.enable", serde_json::json!({})).await {
66            tracing::warn!(error = %e, "Page.enable failed — navigation events may be missing");
67        }
68
69        let target_id = get_first_target_id(&ws_url, self.config.connect_timeout_ms).await?;
70        let session = CdpSession::new(
71            Arc::clone(&client),
72            &target_id,
73            self.config.command_timeout_ms,
74        )
75        .await?;
76        *session_lock = Some(session);
77        drop(session_lock);
78
79        self.spawn_event_forwarder(client).await;
80        Ok(())
81    }
82
83    /// Subscribe to every CDP notification and republish as broker events on
84    /// `plugin.events.browser.{method_suffix}`. Started at most once per plugin
85    /// instance, and only once the broker is available — otherwise the forwarder
86    /// would be silently skipped forever.
87    async fn spawn_event_forwarder(self: &Arc<Self>, client: Arc<CdpClient>) {
88        let mut started = self.event_forwarder_started.lock().await;
89        if *started {
90            return;
91        }
92
93        let broker_guard = self.broker.lock().await;
94        let Some(broker) = broker_guard.clone() else {
95            tracing::debug!("browser plugin has no broker yet — deferring CDP event forwarder");
96            return;
97        };
98        drop(broker_guard);
99
100        *started = true;
101        drop(started);
102
103        let mut rx = client.subscribe_events();
104        tokio::spawn(async move {
105            loop {
106                match rx.recv().await {
107                    Ok(ev) => {
108                        let suffix = ev
109                            .method
110                            .split('.')
111                            .next_back()
112                            .unwrap_or("unknown")
113                            .to_ascii_lowercase();
114                        let topic = format!("plugin.events.browser.{suffix}");
115                        let payload = serde_json::json!({
116                            "method":     ev.method,
117                            "params":     ev.params,
118                            "session_id": ev.session_id,
119                        });
120                        let evt = Event::new(&topic, "browser", payload);
121                        if let Err(e) = broker.publish(&topic, evt).await {
122                            tracing::debug!(error = %e, topic = %topic, "failed to forward CDP event");
123                        }
124                    }
125                    Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
126                        tracing::warn!(dropped = n, "CDP event forwarder lagged");
127                    }
128                    Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
129                }
130            }
131        });
132    }
133
134    /// Execute one CDP command against the managed Chrome session.
135    /// Public so the `BrowserTool` family (registered as LLM tools) can
136    /// drive the browser directly — otherwise callers would have to
137    /// round-trip through the broker.
138    pub async fn execute(self: &Arc<Self>, cmd: BrowserCmd) -> BrowserResult {
139        if !self.circuit.allow() {
140            return BrowserResult::err(format!(
141                "circuit breaker `{}` is open",
142                self.circuit.name()
143            ));
144        }
145
146        if let Err(e) = self.ensure_session().await {
147            self.circuit.on_failure();
148            return BrowserResult::err(format!("session init failed: {e}"));
149        }
150
151        let mut lock = self.session.lock().await;
152        let session = match lock.as_mut() {
153            Some(s) => s,
154            None => {
155                self.circuit.on_failure();
156                return BrowserResult::err("no active session");
157            }
158        };
159
160        let timeout = Duration::from_millis(self.config.command_timeout_ms);
161        let result = match cmd {
162            BrowserCmd::Navigate { url } => {
163                match tokio::time::timeout(timeout, session.navigate(&url)).await {
164                    Ok(Ok(())) => BrowserResult::ok(),
165                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
166                    Err(_) => BrowserResult::err("navigate timed out"),
167                }
168            }
169            BrowserCmd::Click { target } => {
170                match tokio::time::timeout(timeout, session.click(&target)).await {
171                    Ok(Ok(())) => BrowserResult::ok(),
172                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
173                    Err(_) => BrowserResult::err("click timed out"),
174                }
175            }
176            BrowserCmd::Fill { target, value } => {
177                match tokio::time::timeout(timeout, session.fill(&target, &value)).await {
178                    Ok(Ok(())) => BrowserResult::ok(),
179                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
180                    Err(_) => BrowserResult::err("fill timed out"),
181                }
182            }
183            BrowserCmd::Screenshot => {
184                match tokio::time::timeout(timeout, session.screenshot()).await {
185                    Ok(Ok(bytes)) => {
186                        let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
187                        BrowserResult::ok_screenshot(b64)
188                    }
189                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
190                    Err(_) => BrowserResult::err("screenshot timed out"),
191                }
192            }
193            BrowserCmd::Evaluate { script } => {
194                match tokio::time::timeout(timeout, session.evaluate(&script)).await {
195                    Ok(Ok(v)) => BrowserResult::ok_value(v),
196                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
197                    Err(_) => BrowserResult::err("evaluate timed out"),
198                }
199            }
200            BrowserCmd::Snapshot => match tokio::time::timeout(timeout, session.snapshot()).await {
201                Ok(Ok(text)) => BrowserResult::ok_snapshot(text),
202                Ok(Err(e)) => BrowserResult::err(e.to_string()),
203                Err(_) => BrowserResult::err("snapshot timed out"),
204            },
205            BrowserCmd::ScrollTo { target } => {
206                match tokio::time::timeout(timeout, session.scroll_to(&target)).await {
207                    Ok(Ok(())) => BrowserResult::ok(),
208                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
209                    Err(_) => BrowserResult::err("scroll_to timed out"),
210                }
211            }
212        };
213
214        if result.ok {
215            self.circuit.on_success();
216        } else {
217            self.circuit.on_failure();
218        }
219        result
220    }
221}
222
223pub struct BrowserPlugin {
224    inner: Arc<BrowserInner>,
225    shutdown: CancellationToken,
226}
227
228impl BrowserPlugin {
229    pub fn new(config: BrowserConfig) -> Self {
230        Self {
231            inner: Arc::new(BrowserInner::new(config)),
232            shutdown: CancellationToken::new(),
233        }
234    }
235
236    /// Execute one browser command directly (no broker roundtrip). The
237    /// `BrowserTool` family calls this from inside LLM tool handlers so
238    /// each tool call runs exactly once per request — sending through
239    /// the broker would pile inbound events on top of whatever the
240    /// plugin's own subscriber is doing.
241    pub async fn execute(&self, cmd: BrowserCmd) -> BrowserResult {
242        self.inner.execute(cmd).await
243    }
244}
245
246#[async_trait]
247impl Plugin for BrowserPlugin {
248    fn name(&self) -> &str {
249        "browser"
250    }
251
252    async fn start(&self, broker: AnyBroker) -> anyhow::Result<()> {
253        *self.inner.broker.lock().await = Some(broker.clone());
254
255        // If a CDP session was opened before `start()` (e.g. via a direct
256        // `send_command` call), the event forwarder was skipped because the
257        // broker wasn't available yet. Retry now that it is.
258        if let Some(session) = self.inner.session.lock().await.as_ref() {
259            let client = session.client();
260            self.inner.spawn_event_forwarder(client).await;
261        }
262
263        let mut sub = broker.subscribe("plugin.inbound.browser").await?;
264        let inner = Arc::clone(&self.inner);
265        let shutdown = self.shutdown.clone();
266
267        tokio::spawn(async move {
268            loop {
269                tokio::select! {
270                    event = sub.next() => {
271                        let Some(event) = event else { break };
272                        let session_id = event.session_id;
273
274                        let cmd: BrowserCmd = match serde_json::from_value(event.payload.clone()) {
275                            Ok(c) => c,
276                            Err(e) => {
277                                let result = BrowserResult::err(format!("invalid command: {e}"));
278                                publish_result(&broker, session_id, result).await;
279                                continue;
280                            }
281                        };
282
283                        let result = inner.execute(cmd).await;
284                        publish_result(&broker, session_id, result).await;
285                    }
286                    _ = shutdown.cancelled() => break,
287                }
288            }
289        });
290
291        Ok(())
292    }
293
294    async fn stop(&self) -> anyhow::Result<()> {
295        self.shutdown.cancel();
296        *self.inner.session.lock().await = None;
297        *self.inner.chrome.lock().await = None;
298        Ok(())
299    }
300
301    async fn send_command(&self, cmd: Command) -> anyhow::Result<Response> {
302        match cmd {
303            Command::Custom { name, payload } if name == "browser" => {
304                let browser_cmd: BrowserCmd = serde_json::from_value(payload)
305                    .map_err(|e| anyhow::anyhow!("invalid browser payload: {e}"))?;
306                let result = self.inner.execute(browser_cmd).await;
307                let payload = serde_json::to_value(&result)?;
308                Ok(Response::Custom { payload })
309            }
310            Command::Custom { name, .. } => {
311                anyhow::bail!("browser plugin does not handle Custom command `{name}`");
312            }
313            Command::SendMessage { .. } | Command::SendMedia { .. } => {
314                anyhow::bail!("browser plugin does not handle messaging commands");
315            }
316        }
317    }
318}
319
320async fn publish_result(broker: &AnyBroker, session_id: Option<Uuid>, result: BrowserResult) {
321    let payload = serde_json::to_value(&result).unwrap_or(serde_json::json!({"ok": false}));
322    let mut event = Event::new("plugin.outbound.browser", "browser", payload);
323    event.session_id = session_id;
324    if let Err(e) = broker.publish("plugin.outbound.browser", event).await {
325        tracing::error!(error = %e, "failed to publish browser result");
326    }
327}
328
329async fn get_first_target_id(ws_url: &str, timeout_ms: u64) -> anyhow::Result<String> {
330    // Convert ws:// to http:// for /json endpoint
331    let http_url = ws_url
332        .replace("ws://", "http://")
333        .replace("wss://", "https://");
334    // Strip path (keep only host:port)
335    let base = if let Some(idx) = http_url.find("/devtools/") {
336        http_url[..idx].to_string()
337    } else {
338        http_url
339    };
340
341    let client = reqwest::Client::builder()
342        .timeout(std::time::Duration::from_millis(timeout_ms))
343        .build()?;
344    // Chrome DevTools HTTP endpoint requires Host: localhost.
345    let targets: Vec<serde_json::Value> = client
346        .get(format!("{base}/json/list"))
347        .header(reqwest::header::HOST, "localhost")
348        .send()
349        .await?
350        .json()
351        .await?;
352
353    targets
354        .iter()
355        .find(|t| t.get("type").and_then(|v| v.as_str()) == Some("page"))
356        .and_then(|t| t.get("id").and_then(|v| v.as_str()))
357        .map(|s| s.to_string())
358        .ok_or_else(|| anyhow::anyhow!("no page target found in Chrome"))
359}