adk-browser 3.0.0

Browser automation tools for Rust Agent Development Kit (ADK-Rust) agents using WebDriver
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Navigate tool for browser navigation.

use crate::session::BrowserSession;
use adk_core::egress::{ContextUrls, UrlSources, is_non_public};
use adk_core::{Result, Tool, ToolContext};
use async_trait::async_trait;
use serde_json::{Value, json};
use std::sync::Arc;

/// Error code of a navigation refused because its URL did not appear in the conversation.
pub const URL_NOT_IN_CONTEXT_CODE: &str = "browser.url_not_in_context";

/// URL schemes the navigation tools accept unless configured otherwise.
///
/// `file:`, `javascript:`, `data:`, and browser-internal schemes such as `chrome:`
/// are excluded: they read the host filesystem, run script, or reach browser
/// settings rather than load a web page.
pub const DEFAULT_ALLOWED_SCHEMES: &[&str] = &["http", "https"];

/// The default scheme allowlist as owned strings.
pub(crate) fn default_allowed_schemes() -> Vec<String> {
    DEFAULT_ALLOWED_SCHEMES.iter().map(|scheme| (*scheme).to_string()).collect()
}

/// Host names that reach the local machine or a cloud metadata service without resolving to a
/// public address.
const PRIVATE_HOST_NAMES: &[&str] = &["localhost", "metadata.google.internal"];

/// How long a navigation waits for the preflight DNS lookup.
const RESOLVE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// What a model-supplied URL may point at.
#[derive(Debug, Clone)]
pub(crate) struct UrlPolicy {
    pub(crate) allowed_schemes: Vec<String>,
    pub(crate) allow_private_network: bool,
    pub(crate) allow_unresolved_hosts: bool,
    /// With sources, a URL is opened only when it appeared in them (the exfiltration rule).
    pub(crate) url_sources: Option<UrlSources>,
}

impl Default for UrlPolicy {
    fn default() -> Self {
        Self {
            allowed_schemes: default_allowed_schemes(),
            allow_private_network: false,
            allow_unresolved_hosts: false,
            url_sources: None,
        }
    }
}

/// Why a URL's host was refused.
enum HostRefusal {
    /// The host is, or resolves to, a non-public address.
    Private,
    /// The host name does not resolve on the agent host, so its address is unknown.
    Unresolved(String),
}

impl UrlPolicy {
    /// Refuses `url` when the exfiltration rule is on and the URL did not appear in the
    /// conversation `ctx` belongs to, so a model cannot carry data out in a URL it composed.
    ///
    /// Runs before any lookup, since a composed host name carries data to the resolver.
    pub(crate) fn check_in_context(&self, url: &str, ctx: &dyn ToolContext) -> Result<()> {
        let Some(sources) = &self.url_sources else { return Ok(()) };
        if ContextUrls::from_tool_context(ctx, sources).contains(url) {
            return Ok(());
        }
        Err(adk_core::AdkError::new(
            adk_core::ErrorComponent::Tool,
            adk_core::ErrorCategory::Forbidden,
            URL_NOT_IN_CONTEXT_CODE,
            "The URL did not appear earlier in the conversation, so the browser does not open \
             it: only a URL a user message or a tool result already holds is opened, exactly as \
             written there (query string included). Open a URL exactly as it appeared, or ask \
             the user for the URL.",
        ))
    }

    /// Rejects a URL that does not parse, whose scheme is not allowed, or — unless private
    /// network access is enabled — whose host is loopback, private, link-local, or a cloud
    /// metadata endpoint.
    ///
    /// A host name is resolved and refused when any address it resolves to is non-public, or
    /// when it does not resolve here at all, unless unresolved hosts are allowed: the browser
    /// may resolve such a name to a private address through its own resolver or a proxy.
    pub(crate) async fn check(&self, url: &str) -> Result<()> {
        let parsed = url::Url::parse(url)
            .map_err(|e| adk_core::AdkError::tool(format!("Invalid URL '{url}': {e}")))?;
        let scheme = parsed.scheme();
        if !self.allowed_schemes.iter().any(|candidate| candidate.eq_ignore_ascii_case(scheme)) {
            return Err(adk_core::AdkError::tool(format!(
                "URL scheme '{scheme}' is not allowed; allowed schemes: {}. Configure \
                 BrowserToolset::with_allowed_schemes to permit others.",
                self.allowed_schemes.join(", ")
            )));
        }
        match self.host_refusal(&parsed).await {
            None => Ok(()),
            Some(refusal) => Err(adk_core::AdkError::tool(refusal_message(url, &refusal))),
        }
    }

    /// Checks the page the browser ended on after a navigation, which differs from the
    /// requested URL when the site redirected. A refused page is replaced with
    /// `about:blank` before the error returns, so later tools cannot read it.
    ///
    /// Returns the page's URL when it is allowed. The browser has already sent the request
    /// by the time this runs, so this keeps the response from the model; only network
    /// isolation keeps the request from reaching the address.
    ///
    /// # Errors
    ///
    /// Returns an error when the current URL cannot be read or points at a refused address.
    pub(crate) async fn check_landing(&self, browser: &BrowserSession) -> Result<String> {
        let current = browser.current_url().await?;
        if self.allow_private_network {
            return Ok(current);
        }
        // Pages without a host, such as `about:blank` or a browser error page, reach nothing.
        let refusal = match url::Url::parse(&current) {
            Ok(parsed) => match self.host_refusal(&parsed).await {
                None => return Ok(current),
                Some(refusal) => refusal_message(&current, &refusal),
            },
            Err(e) => format!("The browser reported a URL that does not parse: {e}."),
        };
        let cleared = match browser.navigate("about:blank").await {
            Ok(()) => "The page was replaced with about:blank.".to_string(),
            Err(e) => format!("Replacing the page with about:blank failed: {e}"),
        };
        Err(adk_core::AdkError::tool(format!(
            "The browser ended on '{current}' after the navigation. {refusal} {cleared}"
        )))
    }

    /// Returns why `parsed`'s host is refused, if it is.
    async fn host_refusal(&self, parsed: &url::Url) -> Option<HostRefusal> {
        if self.allow_private_network {
            return None;
        }
        let private = match parsed.host()? {
            url::Host::Ipv4(ip) => is_non_public(ip.into()),
            url::Host::Ipv6(ip) => is_non_public(ip.into()),
            url::Host::Domain(domain) => {
                let domain = domain.trim_end_matches('.').to_ascii_lowercase();
                if PRIVATE_HOST_NAMES.contains(&domain.as_str()) || domain.ends_with(".localhost") {
                    true
                } else {
                    match resolve(&domain, parsed.port_or_known_default()).await {
                        Some(addresses) => addresses.iter().any(|address| is_non_public(*address)),
                        None if self.allow_unresolved_hosts => false,
                        None => return Some(HostRefusal::Unresolved(domain)),
                    }
                }
            }
        };
        private.then_some(HostRefusal::Private)
    }
}

fn refusal_message(url: &str, refusal: &HostRefusal) -> String {
    match refusal {
        HostRefusal::Private => format!(
            "URL '{url}' points at a private network address (loopback, private, \
             link-local, or cloud metadata) and is not allowed. Configure \
             BrowserToolset::with_private_network_access to permit it."
        ),
        HostRefusal::Unresolved(host) => format!(
            "URL '{url}' was refused: its host '{host}' does not resolve on the agent host, \
             so it cannot be checked against the private network policy. Configure \
             BrowserToolset::with_unresolved_hosts to let the browser resolve it."
        ),
    }
}

/// Resolves `domain` within [`RESOLVE_TIMEOUT`]. Returns `None` when the lookup fails, times
/// out, or yields no address.
async fn resolve(domain: &str, port: Option<u16>) -> Option<Vec<std::net::IpAddr>> {
    let lookup = tokio::net::lookup_host((domain, port.unwrap_or(80)));
    match tokio::time::timeout(RESOLVE_TIMEOUT, lookup).await {
        Ok(Ok(addresses)) => {
            let addresses: Vec<_> = addresses.map(|address| address.ip()).collect();
            (!addresses.is_empty()).then_some(addresses)
        }
        Ok(Err(_)) | Err(_) => None,
    }
}

/// Tool for navigating to URLs.
///
/// Only URLs whose scheme is in the allowlist are opened; the default is
/// [`DEFAULT_ALLOWED_SCHEMES`] (`http` and `https`). URLs that point at loopback,
/// private, link-local, or cloud metadata addresses are refused until
/// [`with_private_network_access`](Self::with_private_network_access) permits them, and so
/// are host names that do not resolve on the agent host until
/// [`with_unresolved_hosts`](Self::with_unresolved_hosts) permits them.
///
/// The page the browser ends on is checked again, so a redirect to a refused address fails
/// the call and the page is replaced with `about:blank`.
pub struct NavigateTool {
    browser: Arc<BrowserSession>,
    policy: UrlPolicy,
}

impl NavigateTool {
    /// Create a new navigate tool with a shared browser session.
    ///
    /// The tool accepts [`DEFAULT_ALLOWED_SCHEMES`] until
    /// [`with_allowed_schemes`](Self::with_allowed_schemes) replaces them, and refuses
    /// private network addresses.
    pub fn new(browser: Arc<BrowserSession>) -> Self {
        Self { browser, policy: UrlPolicy::default() }
    }

    /// Permit or refuse URLs that point at a private network address.
    ///
    /// Refused by default: a page the model opens on `localhost`, a private range, or
    /// `169.254.169.254` reaches services the agent's operator never exposed, such as an
    /// admin console or a cloud metadata endpoint holding credentials. Enable this only for
    /// an agent meant to browse an internal network.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_browser::{BrowserSession, NavigateTool};
    /// use std::sync::Arc;
    ///
    /// let browser = Arc::new(BrowserSession::with_defaults());
    /// let tool = NavigateTool::new(browser).with_private_network_access(true);
    /// ```
    #[must_use]
    pub fn with_private_network_access(mut self, enabled: bool) -> Self {
        self.policy.allow_private_network = enabled;
        self
    }

    /// Permit or refuse URLs whose host name does not resolve on the agent host.
    ///
    /// Refused by default: the agent cannot tell whether such a name reaches a private
    /// address, and the browser may resolve it differently, through its own resolver or a
    /// proxy. Enable this when the browser runs behind a proxy or on a remote WebDriver host
    /// whose network the agent host cannot see; redirects are still checked against the page
    /// the browser ends on.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_browser::{BrowserSession, NavigateTool};
    /// use std::sync::Arc;
    ///
    /// let browser = Arc::new(BrowserSession::with_defaults());
    /// let tool = NavigateTool::new(browser).with_unresolved_hosts(true);
    /// ```
    #[must_use]
    pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
        self.policy.allow_unresolved_hosts = enabled;
        self
    }

    /// Replace the URL schemes this tool accepts.
    ///
    /// Schemes are compared case-insensitively. Allowing `file` exposes the host
    /// filesystem to the model, and allowing `javascript` or `data` lets it run
    /// script outside `browser_evaluate_js`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_browser::{BrowserSession, NavigateTool};
    /// use std::sync::Arc;
    ///
    /// let browser = Arc::new(BrowserSession::with_defaults());
    /// let tool = NavigateTool::new(browser).with_allowed_schemes(["https"]);
    /// ```
    #[must_use]
    pub fn with_allowed_schemes<I, S>(mut self, schemes: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.policy.allowed_schemes = schemes.into_iter().map(Into::into).collect();
        self
    }

    /// Opens only a URL that already appeared in the conversation's `sources`: a user
    /// message or a tool result, exactly as written there. Off by default.
    ///
    /// A model that has read untrusted text can be told to put data it holds into a URL and
    /// open it; under this rule a URL found only in what the model wrote is refused with
    /// [`URL_NOT_IN_CONTEXT_CODE`] before the browser moves or any name is resolved. See
    /// [`ContextUrls`] for the sources and the matching rule.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_browser::{BrowserSession, NavigateTool};
    /// use adk_core::egress::UrlSources;
    /// use std::sync::Arc;
    ///
    /// let browser = Arc::new(BrowserSession::with_defaults());
    /// let tool = NavigateTool::new(browser).with_url_provenance(Some(UrlSources::default()));
    /// ```
    #[must_use]
    pub fn with_url_provenance(mut self, sources: Option<UrlSources>) -> Self {
        self.policy.url_sources = sources;
        self
    }
}

#[async_trait]
impl Tool for NavigateTool {
    fn name(&self) -> &str {
        "browser_navigate"
    }

    fn description(&self) -> &str {
        "Navigate the browser to a specified URL. Use this to open web pages \
         (http and https URLs by default)."
    }

    fn parameters_schema(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {
                "url": {
                    "type": "string",
                    "description": "The URL to navigate to (e.g., 'https://example.com')"
                }
            },
            "required": ["url"]
        }))
    }

    fn response_schema(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {
                "success": { "type": "boolean" },
                "url": { "type": "string" },
                "title": { "type": "string" }
            }
        }))
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        let url = args
            .get("url")
            .and_then(|v| v.as_str())
            .ok_or_else(|| adk_core::AdkError::tool("Missing 'url' parameter"))?;

        self.policy.check_in_context(url, ctx.as_ref())?;
        self.policy.check(url).await?;

        // Navigate
        self.browser.navigate(url).await?;
        let current_url = self.policy.check_landing(&self.browser).await?;

        // Get result info
        let title = self.browser.title().await.unwrap_or_default();

        // Include page context like interaction tools do
        match self.browser.page_context().await {
            Ok(page) => Ok(json!({
                "success": true,
                "url": current_url,
                "title": title,
                "page": page
            })),
            Err(e) => Ok(json!({
                "success": true,
                "url": current_url,
                "title": title,
                "page_context_error": e.to_string()
            })),
        }
    }
}

/// Tool for going back in browser history.
///
/// The page the browser lands on is checked like a navigation: one that points at a
/// private network address fails the call and is replaced with `about:blank`, unless
/// [`with_private_network_access`](Self::with_private_network_access) permits it.
pub struct BackTool {
    browser: Arc<BrowserSession>,
    policy: UrlPolicy,
}

impl BackTool {
    pub fn new(browser: Arc<BrowserSession>) -> Self {
        Self { browser, policy: UrlPolicy::default() }
    }

    /// Permit or refuse landing on a private network address. Refused by default.
    ///
    /// See [`NavigateTool::with_private_network_access`].
    #[must_use]
    pub fn with_private_network_access(mut self, enabled: bool) -> Self {
        self.policy.allow_private_network = enabled;
        self
    }

    /// Permit or refuse landing on a host name that does not resolve on the agent host.
    /// Refused by default.
    ///
    /// See [`NavigateTool::with_unresolved_hosts`].
    #[must_use]
    pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
        self.policy.allow_unresolved_hosts = enabled;
        self
    }
}

#[async_trait]
impl Tool for BackTool {
    fn name(&self) -> &str {
        "browser_back"
    }

    fn description(&self) -> &str {
        "Go back to the previous page in browser history."
    }

    fn parameters_schema(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {}
        }))
    }

    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
        self.browser.back().await?;

        let url = self.policy.check_landing(&self.browser).await?;
        let title = self.browser.title().await.unwrap_or_default();

        // Include page context like interaction tools do
        match self.browser.page_context().await {
            Ok(page) => Ok(json!({
                "success": true,
                "url": url,
                "title": title,
                "page": page
            })),
            Err(e) => Ok(json!({
                "success": true,
                "url": url,
                "title": title,
                "page_context_error": e.to_string()
            })),
        }
    }
}

/// Tool for going forward in browser history.
///
/// The page the browser lands on is checked like a navigation: one that points at a
/// private network address fails the call and is replaced with `about:blank`, unless
/// [`with_private_network_access`](Self::with_private_network_access) permits it.
pub struct ForwardTool {
    browser: Arc<BrowserSession>,
    policy: UrlPolicy,
}

impl ForwardTool {
    pub fn new(browser: Arc<BrowserSession>) -> Self {
        Self { browser, policy: UrlPolicy::default() }
    }

    /// Permit or refuse landing on a private network address. Refused by default.
    ///
    /// See [`NavigateTool::with_private_network_access`].
    #[must_use]
    pub fn with_private_network_access(mut self, enabled: bool) -> Self {
        self.policy.allow_private_network = enabled;
        self
    }

    /// Permit or refuse landing on a host name that does not resolve on the agent host.
    /// Refused by default.
    ///
    /// See [`NavigateTool::with_unresolved_hosts`].
    #[must_use]
    pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
        self.policy.allow_unresolved_hosts = enabled;
        self
    }
}

#[async_trait]
impl Tool for ForwardTool {
    fn name(&self) -> &str {
        "browser_forward"
    }

    fn description(&self) -> &str {
        "Go forward to the next page in browser history."
    }

    fn parameters_schema(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {}
        }))
    }

    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
        self.browser.forward().await?;

        let url = self.policy.check_landing(&self.browser).await?;
        let title = self.browser.title().await.unwrap_or_default();

        // Include page context like interaction tools do
        match self.browser.page_context().await {
            Ok(page) => Ok(json!({
                "success": true,
                "url": url,
                "title": title,
                "page": page
            })),
            Err(e) => Ok(json!({
                "success": true,
                "url": url,
                "title": title,
                "page_context_error": e.to_string()
            })),
        }
    }
}

/// Tool for refreshing the current page.
///
/// The page the browser lands on is checked like a navigation: one that points at a
/// private network address fails the call and is replaced with `about:blank`, unless
/// [`with_private_network_access`](Self::with_private_network_access) permits it.
pub struct RefreshTool {
    browser: Arc<BrowserSession>,
    policy: UrlPolicy,
}

impl RefreshTool {
    pub fn new(browser: Arc<BrowserSession>) -> Self {
        Self { browser, policy: UrlPolicy::default() }
    }

    /// Permit or refuse landing on a private network address. Refused by default.
    ///
    /// See [`NavigateTool::with_private_network_access`].
    #[must_use]
    pub fn with_private_network_access(mut self, enabled: bool) -> Self {
        self.policy.allow_private_network = enabled;
        self
    }

    /// Permit or refuse landing on a host name that does not resolve on the agent host.
    /// Refused by default.
    ///
    /// See [`NavigateTool::with_unresolved_hosts`].
    #[must_use]
    pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
        self.policy.allow_unresolved_hosts = enabled;
        self
    }
}

#[async_trait]
impl Tool for RefreshTool {
    fn name(&self) -> &str {
        "browser_refresh"
    }

    fn description(&self) -> &str {
        "Refresh the current page."
    }

    fn parameters_schema(&self) -> Option<Value> {
        Some(json!({
            "type": "object",
            "properties": {}
        }))
    }

    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
        self.browser.refresh().await?;

        let url = self.policy.check_landing(&self.browser).await?;
        let title = self.browser.title().await.unwrap_or_default();

        // Include page context like interaction tools do
        match self.browser.page_context().await {
            Ok(page) => Ok(json!({
                "success": true,
                "url": url,
                "title": title,
                "page": page
            })),
            Err(e) => Ok(json!({
                "success": true,
                "url": url,
                "title": title,
                "page_context_error": e.to_string()
            })),
        }
    }
}