Skip to main content

cdp_driver/
agent.rs

1//! High-level, serializable browser actions built on top of [`crate::client::CdpClient`],
2//! suited to driving the browser from tool calls (LLM agents) or a fluent builder.
3
4use serde::{Deserialize, Serialize};
5use serde_json::{json, Value};
6use tokio::sync::broadcast;
7
8use crate::client::CdpClient;
9use crate::config::Config;
10use crate::error::{CdpError, Result};
11use crate::types::ConsoleMessage;
12
13fn quote(s: &str) -> String {
14    serde_json::to_string(s).unwrap_or_else(|_| format!("\"{}\"", s.replace('"', "\\\"")))
15}
16
17/// A single browser operation, dispatched by [`BrowserAgent::execute`].
18///
19/// Serializes to/from the same shape [`BrowserAgent::execute_json`] parses (field
20/// names map to lower_snake_case action names, e.g. `Navigate { url }` <->
21/// `{"action": "navigate", "url": "..."}`), so it doubles as an LLM tool-call schema.
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub enum BrowserAction {
24    Navigate {
25        url: String,
26    },
27    GoBack,
28    GoForward,
29    Reload,
30
31    Click {
32        selector: Option<String>,
33        x: Option<f64>,
34        y: Option<f64>,
35    },
36    Type {
37        text: String,
38        selector: Option<String>,
39    },
40    Fill {
41        selector: String,
42        value: String,
43    },
44    Submit {
45        selector: Option<String>,
46    },
47    PressKey {
48        key: String,
49    },
50
51    GetTitle,
52    GetUrl,
53    GetText,
54    GetContent {
55        selector: Option<String>,
56    },
57    GetLinks,
58    GetAttributes {
59        selector: String,
60    },
61    Exists {
62        selector: String,
63    },
64
65    Screenshot {
66        path: Option<String>,
67    },
68    Evaluate {
69        expression: String,
70    },
71
72    Wait {
73        ms: u64,
74    },
75    WaitForSelector {
76        selector: String,
77        timeout_ms: u64,
78    },
79
80    Scroll {
81        x: f64,
82        y: f64,
83    },
84    SetViewport {
85        width: i32,
86        height: i32,
87        mobile: bool,
88    },
89    GetMetrics,
90}
91
92/// Outcome of [`BrowserAgent::execute`]. Errors are captured as strings rather than
93/// propagated so a batch of actions ([`BrowserAgent::execute_many`]) can run to
94/// completion and report per-action success/failure.
95#[derive(Debug, Clone)]
96pub struct ActionResult {
97    /// Whether the action completed without error.
98    pub success: bool,
99    /// The action's return value, when it produces one and succeeded.
100    pub value: Option<Value>,
101    /// The error message, when `success` is `false`.
102    pub error: Option<String>,
103}
104
105impl ActionResult {
106    /// Shorthand for `self.success`.
107    pub fn is_success(&self) -> bool {
108        self.success
109    }
110}
111
112impl std::fmt::Display for ActionResult {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        if self.success {
115            write!(f, "Ok({:?})", self.value)
116        } else {
117            write!(f, "Err({})", self.error.as_deref().unwrap_or("unknown"))
118        }
119    }
120}
121
122/// Drives a single browser tab via [`BrowserAction`]s. Wraps a [`CdpClient`] with
123/// `Page`, `Runtime`, `DOM`, and `Network` already enabled.
124pub struct BrowserAgent {
125    client: CdpClient,
126}
127
128impl BrowserAgent {
129    /// Connect to the first available page target and enable the domains actions
130    /// depend on.
131    pub async fn connect(host: &str, port: u16) -> Result<Self> {
132        let client = CdpClient::connect_to_page(host, port).await?;
133        for domain in ["Page", "Runtime", "DOM", "Network"] {
134            client.enable_domain(domain).await?;
135        }
136        Ok(BrowserAgent { client })
137    }
138
139    /// [`connect`](Self::connect) using `config.host`/`config.port`, then apply
140    /// `config`'s viewport size.
141    pub async fn connect_with_config(config: &Config) -> Result<Self> {
142        let agent = Self::connect(&config.host, config.port).await?;
143        agent
144            .client
145            .set_viewport(config.viewport_width, config.viewport_height, false)
146            .await?;
147        Ok(agent)
148    }
149
150    /// Wrap an already-connected client (domains are the caller's responsibility).
151    pub fn from_client(client: CdpClient) -> Self {
152        BrowserAgent { client }
153    }
154
155    /// Close the underlying tab.
156    pub async fn close(&self) -> Result<()> {
157        self.client.close().await
158    }
159
160    /// Start capturing `console.*` calls from the page. Returns a receiver that
161    /// yields each call as a [`ConsoleMessage`]; capture continues until the agent
162    /// (and its underlying client) is dropped.
163    pub fn capture_console(&self) -> broadcast::Receiver<ConsoleMessage> {
164        let (tx, rx) = broadcast::channel(64);
165        let mut events = self.client.subscribe_events();
166        tokio::spawn(async move {
167            while let Ok((method, params)) = events.recv().await {
168                if method != "Runtime.consoleAPICalled" {
169                    continue;
170                }
171                let level = params["type"].as_str().unwrap_or("log").to_string();
172                let text = params["args"]
173                    .as_array()
174                    .and_then(|args| args.first())
175                    .and_then(|a| a["value"].as_str())
176                    .unwrap_or("")
177                    .to_string();
178                let url = params["stackTrace"]["callFrames"][0]["url"]
179                    .as_str()
180                    .map(str::to_owned);
181                let line = params["stackTrace"]["callFrames"][0]["lineNumber"].as_u64();
182                let _ = tx.send(ConsoleMessage {
183                    level,
184                    text,
185                    url,
186                    line,
187                });
188            }
189        });
190        rx
191    }
192
193    /// Run one action, capturing success/failure into an [`ActionResult`] instead of
194    /// returning `Result`.
195    pub async fn execute(&self, action: BrowserAction) -> ActionResult {
196        match self.dispatch(action).await {
197            Ok(value) => ActionResult {
198                success: true,
199                value: Some(value),
200                error: None,
201            },
202            Err(e) => ActionResult {
203                success: false,
204                value: None,
205                error: Some(e.to_string()),
206            },
207        }
208    }
209
210    /// Run each action in `actions` in order, continuing even if one fails.
211    pub async fn execute_many(&self, actions: Vec<BrowserAction>) -> Vec<ActionResult> {
212        let mut results = Vec::with_capacity(actions.len());
213        for action in actions {
214            results.push(self.execute(action).await);
215        }
216        results
217    }
218
219    /// Parse `json_str` as a [`BrowserAction`] (e.g. `{"action": "navigate", "url":
220    /// "..."}`) and run it. Suited for dispatching LLM tool calls directly.
221    pub async fn execute_json(&self, json_str: &str) -> ActionResult {
222        match parse_action(json_str) {
223            Ok(action) => self.execute(action).await,
224            Err(e) => ActionResult {
225                success: false,
226                value: None,
227                error: Some(e.to_string()),
228            },
229        }
230    }
231
232    async fn dispatch(&self, action: BrowserAction) -> Result<Value> {
233        match action {
234            BrowserAction::Navigate { url } => {
235                let nav = self.client.navigate(&url).await?;
236                Ok(json!({ "frameId": nav.frame_id }))
237            }
238            BrowserAction::GoBack => self.client.send_command("Page.goBack", json!({})).await,
239            BrowserAction::GoForward => self.client.send_command("Page.goForward", json!({})).await,
240            BrowserAction::Reload => self.client.send_command("Page.reload", json!({})).await,
241
242            BrowserAction::Click { selector, x, y } => {
243                if let Some(sel) = selector {
244                    self.client
245                        .eval(&format!("document.querySelector({})?.click()", quote(&sel)))
246                        .await?;
247                } else if let (Some(cx), Some(cy)) = (x, y) {
248                    for event_type in ["mousePressed", "mouseReleased"] {
249                        self.client
250                            .send_command(
251                                "Input.dispatchMouseEvent",
252                                json!({
253                                    "type": event_type, "x": cx, "y": cy,
254                                    "button": "left", "clickCount": 1,
255                                }),
256                            )
257                            .await?;
258                    }
259                } else {
260                    return Err(CdpError::Protocol("click: need selector or (x, y)".into()));
261                }
262                Ok(json!(null))
263            }
264
265            BrowserAction::Type { text, selector } => {
266                if let Some(sel) = selector {
267                    self.client
268                        .eval(&format!("document.querySelector({})?.focus()", quote(&sel)))
269                        .await?;
270                }
271                self.client
272                    .send_command("Input.insertText", json!({ "text": text }))
273                    .await?;
274                Ok(json!(null))
275            }
276
277            BrowserAction::Fill { selector, value } => {
278                self.client
279                    .eval(&format!(
280                        "(sel => {{ \
281                        let el = document.querySelector(sel); \
282                        if (!el) return; \
283                        el.focus(); \
284                        el.value = {}; \
285                        el.dispatchEvent(new Event('input', {{bubbles:true}})); \
286                        el.dispatchEvent(new Event('change', {{bubbles:true}})); \
287                    }})({})",
288                        quote(&value),
289                        quote(&selector),
290                    ))
291                    .await?;
292                Ok(json!(null))
293            }
294
295            BrowserAction::Submit { selector } => {
296                let sel = selector.as_deref().unwrap_or("form");
297                self.client
298                    .eval(&format!("document.querySelector({})?.submit()", quote(sel)))
299                    .await?;
300                Ok(json!(null))
301            }
302
303            BrowserAction::PressKey { key } => {
304                let (code, vk) = key_info(&key);
305                self.client
306                    .send_command(
307                        "Input.dispatchKeyEvent",
308                        json!({
309                            "type": "keyDown", "key": key, "code": code,
310                            "windowsVirtualKeyCode": vk,
311                        }),
312                    )
313                    .await?;
314                self.client
315                    .send_command(
316                        "Input.dispatchKeyEvent",
317                        json!({
318                            "type": "keyUp", "key": key, "code": code,
319                        }),
320                    )
321                    .await?;
322                Ok(json!(null))
323            }
324
325            BrowserAction::GetTitle => Ok(json!(self.client.eval("document.title").await?)),
326            BrowserAction::GetUrl => Ok(json!(self.client.eval("window.location.href").await?)),
327            BrowserAction::GetText => Ok(json!(self.client.eval("document.body.innerText").await?)),
328
329            BrowserAction::GetContent { selector } => {
330                let expr = match selector {
331                    Some(sel) => format!("document.querySelector({})?.innerHTML", quote(&sel)),
332                    None => "document.documentElement.outerHTML".into(),
333                };
334                Ok(json!(self.client.eval(&expr).await?))
335            }
336
337            BrowserAction::GetLinks => {
338                let ev = self
339                    .client
340                    .evaluate(
341                        "Array.from(document.querySelectorAll('a'))\
342                     .map(a => ({ href: a.href, text: a.innerText.trim() }))",
343                    )
344                    .await?;
345                Ok(ev.result.value.unwrap_or(json!([])))
346            }
347
348            BrowserAction::GetAttributes { selector } => {
349                let ev = self
350                    .client
351                    .evaluate(&format!(
352                        "(sel => {{ \
353                        let el = document.querySelector(sel); \
354                        if (!el) return null; \
355                        let attrs = {{}}; \
356                        for (let a of el.attributes) attrs[a.name] = a.value; \
357                        return attrs; \
358                    }})({})",
359                        quote(&selector)
360                    ))
361                    .await?;
362                Ok(ev.result.value.unwrap_or(json!(null)))
363            }
364
365            BrowserAction::Exists { selector } => {
366                let ev = self
367                    .client
368                    .evaluate(&format!("!!document.querySelector({})", quote(&selector)))
369                    .await?;
370                Ok(ev.result.value.unwrap_or(json!(false)))
371            }
372
373            BrowserAction::Screenshot { path } => match path {
374                Some(p) => {
375                    self.client.full_page_screenshot_to_file(&p).await?;
376                    Ok(json!(p))
377                }
378                None => Ok(json!(self.client.full_page_screenshot().await?.len())),
379            },
380
381            BrowserAction::Evaluate { expression } => {
382                let ev = self.client.evaluate(&expression).await?;
383                Ok(ev.result.value.unwrap_or(json!(null)))
384            }
385
386            BrowserAction::Wait { ms } => {
387                tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
388                Ok(json!(null))
389            }
390
391            BrowserAction::WaitForSelector {
392                selector,
393                timeout_ms,
394            } => {
395                let deadline =
396                    std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
397                let expr = format!("!!document.querySelector({})", quote(&selector));
398                loop {
399                    let ev = self.client.evaluate(&expr).await?;
400                    if ev.result.value == Some(json!(true)) {
401                        return Ok(json!(true));
402                    }
403                    if std::time::Instant::now() >= deadline {
404                        return Err(CdpError::Timeout);
405                    }
406                    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
407                }
408            }
409
410            BrowserAction::Scroll { x, y } => {
411                self.client
412                    .eval(&format!("window.scrollTo({x}, {y})"))
413                    .await?;
414                Ok(json!(null))
415            }
416
417            BrowserAction::SetViewport {
418                width,
419                height,
420                mobile,
421            } => {
422                self.client.set_viewport(width, height, mobile).await?;
423                Ok(json!(null))
424            }
425
426            BrowserAction::GetMetrics => {
427                self.client
428                    .send_command("Performance.getMetrics", json!({}))
429                    .await
430            }
431        }
432    }
433}
434
435fn key_info(key: &str) -> (&str, u32) {
436    match key {
437        "Enter" => ("Enter", 13),
438        "Tab" => ("Tab", 9),
439        "Backspace" => ("Backspace", 8),
440        "Delete" => ("Delete", 46),
441        "Escape" => ("Escape", 27),
442        " " | "Space" => ("Space", 32),
443        "ArrowLeft" => ("ArrowLeft", 37),
444        "ArrowUp" => ("ArrowUp", 38),
445        "ArrowRight" => ("ArrowRight", 39),
446        "ArrowDown" => ("ArrowDown", 40),
447        _ => (key, 0),
448    }
449}
450
451#[derive(Debug, Deserialize)]
452struct RawAction {
453    action: String,
454    url: Option<String>,
455    selector: Option<String>,
456    value: Option<String>,
457    text: Option<String>,
458    key: Option<String>,
459    path: Option<String>,
460    ms: Option<u64>,
461    x: Option<f64>,
462    y: Option<f64>,
463    expression: Option<String>,
464    width: Option<i32>,
465    height: Option<i32>,
466    mobile: Option<bool>,
467    timeout_ms: Option<u64>,
468}
469
470fn parse_action(json_str: &str) -> Result<BrowserAction> {
471    let a: RawAction = serde_json::from_str(json_str)?;
472
473    macro_rules! need {
474        ($field:expr, $name:literal) => {
475            $field.ok_or_else(|| CdpError::Protocol(concat!($name, " is required").into()))?
476        };
477    }
478
479    Ok(match a.action.as_str() {
480        "navigate" => BrowserAction::Navigate {
481            url: need!(a.url, "url"),
482        },
483        "back" | "go_back" => BrowserAction::GoBack,
484        "forward" | "go_forward" => BrowserAction::GoForward,
485        "reload" => BrowserAction::Reload,
486        "click" => BrowserAction::Click {
487            selector: a.selector,
488            x: a.x,
489            y: a.y,
490        },
491        "type" => BrowserAction::Type {
492            text: need!(a.text, "text"),
493            selector: a.selector,
494        },
495        "fill" => BrowserAction::Fill {
496            selector: need!(a.selector, "selector"),
497            value: need!(a.value, "value"),
498        },
499        "submit" => BrowserAction::Submit {
500            selector: a.selector,
501        },
502        "press_key" | "key" => BrowserAction::PressKey {
503            key: need!(a.key, "key"),
504        },
505        "get_title" | "title" => BrowserAction::GetTitle,
506        "get_url" | "url" => BrowserAction::GetUrl,
507        "get_text" | "text" => BrowserAction::GetText,
508        "get_content" | "content" => BrowserAction::GetContent {
509            selector: a.selector,
510        },
511        "get_links" | "links" => BrowserAction::GetLinks,
512        "get_attributes" | "attributes" => BrowserAction::GetAttributes {
513            selector: need!(a.selector, "selector"),
514        },
515        "exists" => BrowserAction::Exists {
516            selector: need!(a.selector, "selector"),
517        },
518        "screenshot" => BrowserAction::Screenshot { path: a.path },
519        "evaluate" | "eval" => BrowserAction::Evaluate {
520            expression: need!(a.expression, "expression"),
521        },
522        "wait" => BrowserAction::Wait {
523            ms: need!(a.ms, "ms"),
524        },
525        "wait_for_selector" => BrowserAction::WaitForSelector {
526            selector: need!(a.selector, "selector"),
527            timeout_ms: a.timeout_ms.unwrap_or(5000),
528        },
529        "scroll" => BrowserAction::Scroll {
530            x: a.x.unwrap_or(0.0),
531            y: a.y.unwrap_or(0.0),
532        },
533        "set_viewport" => BrowserAction::SetViewport {
534            width: need!(a.width, "width"),
535            height: need!(a.height, "height"),
536            mobile: a.mobile.unwrap_or(false),
537        },
538        "get_metrics" | "metrics" => BrowserAction::GetMetrics,
539        other => return Err(CdpError::Protocol(format!("unknown action: {other}"))),
540    })
541}
542
543/// Fluent builder for a sequence of [`BrowserAction`]s, run with
544/// [`BrowserAgent::execute_many`].
545pub struct ActionBuilder {
546    actions: Vec<BrowserAction>,
547}
548
549impl ActionBuilder {
550    /// Start an empty action sequence.
551    pub fn new() -> Self {
552        ActionBuilder {
553            actions: Vec::new(),
554        }
555    }
556
557    /// Append [`BrowserAction::Navigate`].
558    pub fn navigate(mut self, url: &str) -> Self {
559        self.actions
560            .push(BrowserAction::Navigate { url: url.into() });
561        self
562    }
563
564    /// Append [`BrowserAction::Wait`].
565    pub fn wait(mut self, ms: u64) -> Self {
566        self.actions.push(BrowserAction::Wait { ms });
567        self
568    }
569
570    /// Append [`BrowserAction::Click`] targeting a CSS selector.
571    pub fn click(mut self, selector: &str) -> Self {
572        self.actions.push(BrowserAction::Click {
573            selector: Some(selector.into()),
574            x: None,
575            y: None,
576        });
577        self
578    }
579
580    /// Append [`BrowserAction::Fill`].
581    pub fn fill(mut self, selector: &str, value: &str) -> Self {
582        self.actions.push(BrowserAction::Fill {
583            selector: selector.into(),
584            value: value.into(),
585        });
586        self
587    }
588
589    /// Append [`BrowserAction::PressKey`].
590    pub fn press_key(mut self, key: &str) -> Self {
591        self.actions
592            .push(BrowserAction::PressKey { key: key.into() });
593        self
594    }
595
596    /// Append [`BrowserAction::Screenshot`].
597    pub fn screenshot(mut self, path: Option<&str>) -> Self {
598        self.actions.push(BrowserAction::Screenshot {
599            path: path.map(Into::into),
600        });
601        self
602    }
603
604    /// Append [`BrowserAction::Evaluate`].
605    pub fn evaluate(mut self, expr: &str) -> Self {
606        self.actions.push(BrowserAction::Evaluate {
607            expression: expr.into(),
608        });
609        self
610    }
611
612    /// Append [`BrowserAction::Scroll`].
613    pub fn scroll(mut self, x: f64, y: f64) -> Self {
614        self.actions.push(BrowserAction::Scroll { x, y });
615        self
616    }
617
618    /// Append [`BrowserAction::GetTitle`].
619    pub fn get_title(mut self) -> Self {
620        self.actions.push(BrowserAction::GetTitle);
621        self
622    }
623
624    /// Finish building and return the action sequence.
625    pub fn build(self) -> Vec<BrowserAction> {
626        self.actions
627    }
628}
629
630impl Default for ActionBuilder {
631    fn default() -> Self {
632        Self::new()
633    }
634}