spider_agent 2.51.33

A concurrent-safe multimodal agent for web automation and research.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Browser automation module for spider_agent.
//!
//! Provides Chrome page management with support for:
//! - Page cloning
//! - Opening new pages/tabs
//! - Screenshot capture
//! - Navigation and interaction

use std::sync::Arc;

// Re-export chromey types
pub use chromiumoxide::browser::Browser;
pub use chromiumoxide::error::CdpError;
pub use chromiumoxide::page::Page;

/// Browser context for managing Chrome pages.
///
/// Wraps a chromey Page with additional utilities for agent operations.
#[derive(Clone)]
pub struct BrowserContext {
    /// The browser instance.
    browser: Arc<Browser>,
    /// The current page.
    page: Arc<Page>,
}

impl BrowserContext {
    /// Create a new browser context from an existing browser and page.
    pub fn new(browser: Arc<Browser>, page: Arc<Page>) -> Self {
        Self { browser, page }
    }

    /// Get the current page.
    pub fn page(&self) -> &Arc<Page> {
        &self.page
    }

    /// Get the browser instance.
    pub fn browser(&self) -> &Arc<Browser> {
        &self.browser
    }

    /// Open a new page/tab in the browser.
    pub async fn new_page(&self) -> Result<Arc<Page>, CdpError> {
        let page = self.browser.new_page("about:blank").await?;
        Ok(Arc::new(page))
    }

    /// Open a new page and navigate to URL.
    pub async fn new_page_with_url(&self, url: &str) -> Result<Arc<Page>, CdpError> {
        let page = self.browser.new_page(url).await?;
        Ok(Arc::new(page))
    }

    /// Clone the current page context (opens a new page with same URL).
    pub async fn clone_page(&self) -> Result<BrowserContext, CdpError> {
        let url = self
            .page
            .url()
            .await?
            .unwrap_or_else(|| "about:blank".to_string());
        let new_page = self.browser.new_page(&url).await?;
        Ok(BrowserContext {
            browser: self.browser.clone(),
            page: Arc::new(new_page),
        })
    }

    /// Navigate to a URL.
    pub async fn navigate(&self, url: &str) -> Result<(), CdpError> {
        self.page.goto(url).await?;
        Ok(())
    }

    /// Get the current URL.
    pub async fn url(&self) -> Result<Option<String>, CdpError> {
        self.page.url().await
    }

    /// Get the page HTML content.
    pub async fn html(&self) -> Result<String, CdpError> {
        self.page.content().await
    }

    /// Take a screenshot and return PNG bytes.
    pub async fn screenshot(&self) -> Result<Vec<u8>, CdpError> {
        self.page
            .screenshot(
                chromiumoxide::page::ScreenshotParams::builder()
                    .full_page(true)
                    .build(),
            )
            .await
    }

    /// Take a screenshot of the visible viewport.
    pub async fn screenshot_viewport(&self) -> Result<Vec<u8>, CdpError> {
        self.page
            .screenshot(
                chromiumoxide::page::ScreenshotParams::builder()
                    .full_page(false)
                    .build(),
            )
            .await
    }

    /// Click an element by selector.
    pub async fn click(&self, selector: &str) -> Result<(), CdpError> {
        let element = self.page.find_element(selector).await?;
        element.click().await?;
        Ok(())
    }

    /// Click all elements matching a selector.
    /// Returns the number of elements clicked.
    pub async fn click_all(&self, selector: &str) -> Result<usize, CdpError> {
        let elements = self.page.find_elements(selector).await?;
        let count = elements.len();
        for element in elements {
            let _ = element.click().await;
        }
        Ok(count)
    }

    /// Click at specific x,y coordinates with smooth human-like mouse movement.
    pub async fn click_point(&self, x: f64, y: f64) -> Result<(), CdpError> {
        use chromiumoxide::layout::Point;
        self.page.click_smooth(Point::new(x, y)).await?;
        Ok(())
    }

    /// Click and hold on an element with smooth mouse movement.
    pub async fn click_hold(&self, selector: &str, hold_ms: u64) -> Result<(), CdpError> {
        let element = self.page.find_element(selector).await?;
        let point = element.clickable_point().await?;
        self.page.move_mouse_smooth(point).await?;
        self.page
            .click_and_hold(point, std::time::Duration::from_millis(hold_ms))
            .await?;
        Ok(())
    }

    /// Click and hold at a specific point with smooth mouse movement.
    pub async fn click_hold_point(&self, x: f64, y: f64, hold_ms: u64) -> Result<(), CdpError> {
        use chromiumoxide::layout::Point;
        let point = Point::new(x, y);
        self.page.move_mouse_smooth(point).await?;
        self.page
            .click_and_hold(point, std::time::Duration::from_millis(hold_ms))
            .await?;
        Ok(())
    }

    /// Click and drag from one element to another.
    pub async fn click_drag(
        &self,
        from_selector: &str,
        to_selector: &str,
        modifier: Option<i64>,
    ) -> Result<(), CdpError> {
        let from_elem = self.page.find_element(from_selector).await?;
        let to_elem = self.page.find_element(to_selector).await?;

        let from_point = from_elem.clickable_point().await?;
        let to_point = to_elem.clickable_point().await?;

        self.click_drag_point(
            (from_point.x, from_point.y),
            (to_point.x, to_point.y),
            modifier,
        )
        .await
    }

    /// Click and drag from one point to another with smooth bezier movement.
    pub async fn click_drag_point(
        &self,
        from: (f64, f64),
        to: (f64, f64),
        modifier: Option<i64>,
    ) -> Result<(), CdpError> {
        use chromiumoxide::layout::Point;
        let from_point = Point::new(from.0, from.1);
        let to_point = Point::new(to.0, to.1);
        match modifier {
            Some(m) => {
                self.page
                    .click_and_drag_smooth_with_modifier(from_point, to_point, m)
                    .await?
            }
            None => {
                self.page
                    .click_and_drag_smooth(from_point, to_point)
                    .await?
            }
        };
        Ok(())
    }

    /// Click all clickable elements on the page.
    pub async fn click_all_clickable(&self) -> Result<usize, CdpError> {
        // Find common clickable elements
        let script = r#"
            Array.from(document.querySelectorAll('a, button, [onclick], [role="button"], input[type="submit"], input[type="button"]'))
                .filter(el => {
                    const style = window.getComputedStyle(el);
                    return style.display !== 'none' && style.visibility !== 'hidden' && el.offsetParent !== null;
                })
                .length
        "#;

        let count: usize = self
            .page
            .evaluate(script)
            .await?
            .into_value()
            .map_err(|e| {
                CdpError::ChromeMessage(format!("Failed to count clickable elements: {}", e))
            })?;

        // Click each one (with error handling)
        let click_script = r#"
            const elements = Array.from(document.querySelectorAll('a, button, [onclick], [role="button"], input[type="submit"], input[type="button"]'))
                .filter(el => {
                    const style = window.getComputedStyle(el);
                    return style.display !== 'none' && style.visibility !== 'hidden' && el.offsetParent !== null;
                });
            elements.forEach(el => { try { el.click(); } catch(e) {} });
            elements.length
        "#;

        let clicked: usize = self
            .page
            .evaluate(click_script)
            .await?
            .into_value()
            .unwrap_or(0);

        Ok(clicked.min(count))
    }

    /// Type text into an element.
    pub async fn type_text(&self, selector: &str, text: &str) -> Result<(), CdpError> {
        let element = self.page.find_element(selector).await?;
        element.click().await?;
        element.type_str(text).await?;
        Ok(())
    }

    /// Wait for a selector to appear.
    pub async fn wait_for(&self, selector: &str) -> Result<(), CdpError> {
        self.page.find_element(selector).await?;
        Ok(())
    }

    /// Wait for a selector with timeout.
    pub async fn wait_for_timeout(&self, selector: &str, timeout_ms: u64) -> Result<(), CdpError> {
        let timeout = std::time::Duration::from_millis(timeout_ms);
        tokio::time::timeout(timeout, self.page.find_element(selector))
            .await
            .map_err(|_| CdpError::Timeout)?
            .map(|_| ())
    }

    /// Wait for navigation to complete.
    pub async fn wait_for_navigation(&self) -> Result<(), CdpError> {
        // Wait for load event
        self.page.evaluate("new Promise(r => { if (document.readyState === 'complete') r(); else window.addEventListener('load', r); })").await?;
        Ok(())
    }

    /// Wait for DOM to stabilize (no mutations for a period).
    pub async fn wait_for_dom(
        &self,
        selector: Option<&str>,
        timeout_ms: u32,
    ) -> Result<(), CdpError> {
        let sel = selector.unwrap_or("body");
        let script = format!(
            r#"
            new Promise((resolve, reject) => {{
                const timeout = {};
                const target = document.querySelector('{}');
                if (!target) {{ resolve(); return; }}

                let timer;
                const observer = new MutationObserver(() => {{
                    clearTimeout(timer);
                    timer = setTimeout(() => {{
                        observer.disconnect();
                        resolve();
                    }}, 100);
                }});

                observer.observe(target, {{ childList: true, subtree: true, attributes: true }});

                timer = setTimeout(() => {{
                    observer.disconnect();
                    resolve();
                }}, 100);

                setTimeout(() => {{
                    observer.disconnect();
                    resolve();
                }}, timeout);
            }})
        "#,
            timeout_ms, sel
        );

        self.page.evaluate(script).await?;
        Ok(())
    }

    /// Wait for element then click it.
    pub async fn wait_and_click(&self, selector: &str) -> Result<(), CdpError> {
        let element = self.page.find_element(selector).await?;
        element.click().await?;
        Ok(())
    }

    /// Evaluate JavaScript and return the result.
    pub async fn evaluate<T: serde::de::DeserializeOwned>(
        &self,
        script: &str,
    ) -> Result<T, CdpError> {
        self.page
            .evaluate(script)
            .await?
            .into_value()
            .map_err(|e| CdpError::ChromeMessage(format!("JSON conversion error: {}", e)))
    }

    /// Execute JavaScript without returning a value.
    pub async fn execute(&self, script: &str) -> Result<(), CdpError> {
        self.page.evaluate(script).await?;
        Ok(())
    }

    /// Scroll horizontally by pixels.
    pub async fn scroll_x(&self, pixels: i32) -> Result<(), CdpError> {
        let script = format!("window.scrollBy({}, 0)", pixels);
        self.page.evaluate(script).await?;
        Ok(())
    }

    /// Scroll vertically by pixels.
    pub async fn scroll_y(&self, pixels: i32) -> Result<(), CdpError> {
        let script = format!("window.scrollBy(0, {})", pixels);
        self.page.evaluate(script).await?;
        Ok(())
    }

    /// Infinite scroll - scroll to the bottom of the page repeatedly.
    /// Returns when no new content is loaded after scrolling.
    pub async fn infinite_scroll(&self, max_scrolls: u32) -> Result<usize, CdpError> {
        let script = r#"
            (async function() {
                const maxScrolls = arguments[0];
                let lastHeight = document.body.scrollHeight;
                let scrollCount = 0;

                while (scrollCount < maxScrolls) {
                    window.scrollTo(0, document.body.scrollHeight);
                    await new Promise(r => setTimeout(r, 1000));
                    const newHeight = document.body.scrollHeight;
                    if (newHeight === lastHeight) break;
                    lastHeight = newHeight;
                    scrollCount++;
                }
                return scrollCount;
            })
        "#;

        let count: usize = self
            .page
            .evaluate(format!("({script})({max_scrolls})"))
            .await?
            .into_value()
            .unwrap_or(0);

        Ok(count)
    }

    /// Fill an input element with a value (clears existing content first).
    pub async fn fill(&self, selector: &str, value: &str) -> Result<(), CdpError> {
        let element = self.page.find_element(selector).await?;

        // Clear existing value via triple-click + delete
        element.click().await?;
        element.click().await?;
        element.click().await?;

        // Clear with keyboard
        use chromiumoxide::cdp::browser_protocol::input::{
            DispatchKeyEventParams, DispatchKeyEventType,
        };
        self.page
            .execute(
                DispatchKeyEventParams::builder()
                    .r#type(DispatchKeyEventType::KeyDown)
                    .key("a")
                    .modifiers(2) // Ctrl/Cmd
                    .build()
                    .map_err(|e| CdpError::ChromeMessage(format!("key event build: {e}")))?,
            )
            .await?;
        self.page
            .execute(
                DispatchKeyEventParams::builder()
                    .r#type(DispatchKeyEventType::KeyUp)
                    .key("a")
                    .build()
                    .map_err(|e| CdpError::ChromeMessage(format!("key event build: {e}")))?,
            )
            .await?;

        // Type new value
        element.type_str(value).await?;
        Ok(())
    }

    /// Find all elements matching a selector.
    pub async fn find_elements(
        &self,
        selector: &str,
    ) -> Result<Vec<chromiumoxide::element::Element>, CdpError> {
        self.page.find_elements(selector).await
    }

    /// Get element bounding box via JavaScript.
    pub async fn get_element_bounds(
        &self,
        selector: &str,
    ) -> Result<Option<(f64, f64, f64, f64)>, CdpError> {
        let escaped_selector = serde_json::to_string(selector).unwrap_or_else(|_| {
            format!(
                "\"{}\"",
                selector.replace('\\', "\\\\").replace('"', "\\\"")
            )
        });
        let script = format!(
            r#"
            (function() {{
                const el = document.querySelector({});
                if (!el) return null;
                const rect = el.getBoundingClientRect();
                return [rect.x, rect.y, rect.width, rect.height];
            }})()
            "#,
            escaped_selector
        );

        let result: Option<Vec<f64>> = self
            .page
            .evaluate(script)
            .await?
            .into_value()
            .map_err(|e| CdpError::ChromeMessage(format!("Failed to get bounds: {}", e)))?;

        Ok(result.and_then(|v| {
            if v.len() >= 4 {
                Some((v[0], v[1], v[2], v[3]))
            } else {
                None
            }
        }))
    }

    /// Close the current page.
    /// Note: This clones the page internally since close() takes ownership.
    pub async fn close(&self) -> Result<(), CdpError> {
        // Chrome pages need to be explicitly closed via the browser
        // Since Page::close takes ownership, we use evaluate to close
        self.page.evaluate("window.close()").await?;
        Ok(())
    }

    /// Set the current page (switch to a different page).
    pub fn set_page(&mut self, page: Arc<Page>) {
        self.page = page;
    }

    /// Create a new context with a different page (immutable version).
    pub fn with_page(&self, page: Arc<Page>) -> Self {
        Self {
            browser: self.browser.clone(),
            page,
        }
    }
}

impl std::fmt::Debug for BrowserContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BrowserContext")
            .field("browser", &"Browser { ... }")
            .field("page", &"Page { ... }")
            .finish()
    }
}