Skip to main content

adk_browser/tools/
windows.rs

1//! Window and tab management tools.
2
3use crate::session::BrowserSession;
4use crate::tools::navigate::UrlPolicy;
5use adk_core::{AdkError, Result, Tool, ToolContext};
6use async_trait::async_trait;
7use serde_json::{Value, json};
8use std::sync::Arc;
9
10/// Tool for listing all windows/tabs.
11pub struct ListWindowsTool {
12    browser: Arc<BrowserSession>,
13}
14
15impl ListWindowsTool {
16    pub fn new(browser: Arc<BrowserSession>) -> Self {
17        Self { browser }
18    }
19}
20
21#[async_trait]
22impl Tool for ListWindowsTool {
23    fn name(&self) -> &str {
24        "browser_list_windows"
25    }
26
27    fn description(&self) -> &str {
28        "List all open browser windows/tabs."
29    }
30
31    fn parameters_schema(&self) -> Option<Value> {
32        Some(json!({
33            "type": "object",
34            "properties": {}
35        }))
36    }
37
38    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
39        let (windows, current) = self.browser.list_windows().await?;
40
41        Ok(json!({
42            "success": true,
43            "windows": windows,
44            "current_window": current,
45            "count": windows.len()
46        }))
47    }
48}
49
50/// Tool for opening a new tab.
51///
52/// A `url` argument must use a scheme in the allowlist, which defaults to
53/// [`DEFAULT_ALLOWED_SCHEMES`](crate::tools::DEFAULT_ALLOWED_SCHEMES), and must not point at a
54/// private network address unless
55/// [`with_private_network_access`](Self::with_private_network_access) permits it. The page
56/// the new tab or window ends on is checked again, so a redirect to a refused address fails
57/// the call.
58pub struct NewTabTool {
59    browser: Arc<BrowserSession>,
60    policy: UrlPolicy,
61}
62
63impl NewTabTool {
64    pub fn new(browser: Arc<BrowserSession>) -> Self {
65        Self { browser, policy: UrlPolicy::default() }
66    }
67
68    /// Permit or refuse a `url` that points at a private network address. Refused by default.
69    ///
70    /// See [`NavigateTool::with_private_network_access`](crate::tools::NavigateTool::with_private_network_access).
71    #[must_use]
72    pub fn with_private_network_access(mut self, enabled: bool) -> Self {
73        self.policy.allow_private_network = enabled;
74        self
75    }
76
77    /// Permit or refuse a `url` whose host name does not resolve on the agent host. Refused
78    /// by default.
79    ///
80    /// See [`NavigateTool::with_unresolved_hosts`](crate::tools::NavigateTool::with_unresolved_hosts).
81    #[must_use]
82    pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
83        self.policy.allow_unresolved_hosts = enabled;
84        self
85    }
86
87    /// Replace the URL schemes accepted for the optional `url` argument.
88    ///
89    /// Schemes are compared case-insensitively. See
90    /// [`NavigateTool::with_allowed_schemes`](crate::tools::NavigateTool::with_allowed_schemes).
91    #[must_use]
92    pub fn with_allowed_schemes<I, S>(mut self, schemes: I) -> Self
93    where
94        I: IntoIterator<Item = S>,
95        S: Into<String>,
96    {
97        self.policy.allowed_schemes = schemes.into_iter().map(Into::into).collect();
98        self
99    }
100
101    /// Opens the optional `url` only when it already appeared in the conversation's
102    /// `sources`. Off by default.
103    ///
104    /// See [`NavigateTool::with_url_provenance`](crate::tools::NavigateTool::with_url_provenance).
105    #[must_use]
106    pub fn with_url_provenance(mut self, sources: Option<adk_core::egress::UrlSources>) -> Self {
107        self.policy.url_sources = sources;
108        self
109    }
110}
111
112#[async_trait]
113impl Tool for NewTabTool {
114    fn name(&self) -> &str {
115        "browser_new_tab"
116    }
117
118    fn description(&self) -> &str {
119        "Open a new browser tab and switch to it."
120    }
121
122    fn parameters_schema(&self) -> Option<Value> {
123        Some(json!({
124            "type": "object",
125            "properties": {
126                "url": {
127                    "type": "string",
128                    "description": "Optional URL to navigate to in the new tab"
129                }
130            }
131        }))
132    }
133
134    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
135        let url = args.get("url").and_then(|v| v.as_str());
136        if let Some(url) = url {
137            self.policy.check_in_context(url, ctx.as_ref())?;
138            self.policy.check(url).await?;
139        }
140
141        let handle = self.browser.new_tab().await?;
142
143        let current_url = match url {
144            Some(url) => {
145                self.browser.navigate(url).await?;
146                self.policy.check_landing(&self.browser).await?
147            }
148            None => self.browser.current_url().await.unwrap_or_default(),
149        };
150
151        Ok(json!({
152            "success": true,
153            "window_handle": handle,
154            "url": current_url
155        }))
156    }
157}
158
159/// Tool for opening a new window.
160///
161/// A `url` argument must use a scheme in the allowlist, which defaults to
162/// [`DEFAULT_ALLOWED_SCHEMES`](crate::tools::DEFAULT_ALLOWED_SCHEMES), and must not point at a
163/// private network address unless
164/// [`with_private_network_access`](Self::with_private_network_access) permits it. The page
165/// the new tab or window ends on is checked again, so a redirect to a refused address fails
166/// the call.
167pub struct NewWindowTool {
168    browser: Arc<BrowserSession>,
169    policy: UrlPolicy,
170}
171
172impl NewWindowTool {
173    pub fn new(browser: Arc<BrowserSession>) -> Self {
174        Self { browser, policy: UrlPolicy::default() }
175    }
176
177    /// Permit or refuse a `url` that points at a private network address. Refused by default.
178    ///
179    /// See [`NavigateTool::with_private_network_access`](crate::tools::NavigateTool::with_private_network_access).
180    #[must_use]
181    pub fn with_private_network_access(mut self, enabled: bool) -> Self {
182        self.policy.allow_private_network = enabled;
183        self
184    }
185
186    /// Permit or refuse a `url` whose host name does not resolve on the agent host. Refused
187    /// by default.
188    ///
189    /// See [`NavigateTool::with_unresolved_hosts`](crate::tools::NavigateTool::with_unresolved_hosts).
190    #[must_use]
191    pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
192        self.policy.allow_unresolved_hosts = enabled;
193        self
194    }
195
196    /// Replace the URL schemes accepted for the optional `url` argument.
197    ///
198    /// Schemes are compared case-insensitively. See
199    /// [`NavigateTool::with_allowed_schemes`](crate::tools::NavigateTool::with_allowed_schemes).
200    #[must_use]
201    pub fn with_allowed_schemes<I, S>(mut self, schemes: I) -> Self
202    where
203        I: IntoIterator<Item = S>,
204        S: Into<String>,
205    {
206        self.policy.allowed_schemes = schemes.into_iter().map(Into::into).collect();
207        self
208    }
209
210    /// Opens the optional `url` only when it already appeared in the conversation's
211    /// `sources`. Off by default.
212    ///
213    /// See [`NavigateTool::with_url_provenance`](crate::tools::NavigateTool::with_url_provenance).
214    #[must_use]
215    pub fn with_url_provenance(mut self, sources: Option<adk_core::egress::UrlSources>) -> Self {
216        self.policy.url_sources = sources;
217        self
218    }
219}
220
221#[async_trait]
222impl Tool for NewWindowTool {
223    fn name(&self) -> &str {
224        "browser_new_window"
225    }
226
227    fn description(&self) -> &str {
228        "Open a new browser window and switch to it."
229    }
230
231    fn parameters_schema(&self) -> Option<Value> {
232        Some(json!({
233            "type": "object",
234            "properties": {
235                "url": {
236                    "type": "string",
237                    "description": "Optional URL to navigate to in the new window"
238                }
239            }
240        }))
241    }
242
243    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
244        let url = args.get("url").and_then(|v| v.as_str());
245        if let Some(url) = url {
246            self.policy.check_in_context(url, ctx.as_ref())?;
247            self.policy.check(url).await?;
248        }
249
250        let handle = self.browser.new_window().await?;
251
252        let current_url = match url {
253            Some(url) => {
254                self.browser.navigate(url).await?;
255                self.policy.check_landing(&self.browser).await?
256            }
257            None => self.browser.current_url().await.unwrap_or_default(),
258        };
259
260        Ok(json!({
261            "success": true,
262            "window_handle": handle,
263            "url": current_url
264        }))
265    }
266}
267
268/// Tool for switching to a window/tab.
269pub struct SwitchWindowTool {
270    browser: Arc<BrowserSession>,
271}
272
273impl SwitchWindowTool {
274    pub fn new(browser: Arc<BrowserSession>) -> Self {
275        Self { browser }
276    }
277}
278
279#[async_trait]
280impl Tool for SwitchWindowTool {
281    fn name(&self) -> &str {
282        "browser_switch_window"
283    }
284
285    fn description(&self) -> &str {
286        "Switch to a different browser window/tab by its handle."
287    }
288
289    fn parameters_schema(&self) -> Option<Value> {
290        Some(json!({
291            "type": "object",
292            "properties": {
293                "handle": {
294                    "type": "string",
295                    "description": "The window handle to switch to"
296                }
297            },
298            "required": ["handle"]
299        }))
300    }
301
302    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
303        let handle = args
304            .get("handle")
305            .and_then(|v| v.as_str())
306            .ok_or_else(|| AdkError::tool("Missing 'handle' parameter"))?;
307
308        self.browser.switch_to_window(handle).await?;
309
310        let url = self.browser.current_url().await.unwrap_or_default();
311        let title = self.browser.title().await.unwrap_or_default();
312
313        Ok(json!({
314            "success": true,
315            "switched_to": handle,
316            "url": url,
317            "title": title
318        }))
319    }
320}
321
322/// Tool for closing the current window/tab.
323pub struct CloseWindowTool {
324    browser: Arc<BrowserSession>,
325}
326
327impl CloseWindowTool {
328    pub fn new(browser: Arc<BrowserSession>) -> Self {
329        Self { browser }
330    }
331}
332
333#[async_trait]
334impl Tool for CloseWindowTool {
335    fn name(&self) -> &str {
336        "browser_close_window"
337    }
338
339    fn description(&self) -> &str {
340        "Close the current browser window/tab."
341    }
342
343    fn parameters_schema(&self) -> Option<Value> {
344        Some(json!({
345            "type": "object",
346            "properties": {}
347        }))
348    }
349
350    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
351        self.browser.close_window().await?;
352
353        Ok(json!({
354            "success": true,
355            "message": "Window closed"
356        }))
357    }
358}
359
360/// Tool for maximizing the window.
361pub struct MaximizeWindowTool {
362    browser: Arc<BrowserSession>,
363}
364
365impl MaximizeWindowTool {
366    pub fn new(browser: Arc<BrowserSession>) -> Self {
367        Self { browser }
368    }
369}
370
371#[async_trait]
372impl Tool for MaximizeWindowTool {
373    fn name(&self) -> &str {
374        "browser_maximize_window"
375    }
376
377    fn description(&self) -> &str {
378        "Maximize the browser window."
379    }
380
381    fn parameters_schema(&self) -> Option<Value> {
382        Some(json!({
383            "type": "object",
384            "properties": {}
385        }))
386    }
387
388    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
389        self.browser.maximize_window().await?;
390
391        Ok(json!({
392            "success": true,
393            "message": "Window maximized"
394        }))
395    }
396}
397
398/// Tool for minimizing the window.
399pub struct MinimizeWindowTool {
400    browser: Arc<BrowserSession>,
401}
402
403impl MinimizeWindowTool {
404    pub fn new(browser: Arc<BrowserSession>) -> Self {
405        Self { browser }
406    }
407}
408
409#[async_trait]
410impl Tool for MinimizeWindowTool {
411    fn name(&self) -> &str {
412        "browser_minimize_window"
413    }
414
415    fn description(&self) -> &str {
416        "Minimize the browser window."
417    }
418
419    fn parameters_schema(&self) -> Option<Value> {
420        Some(json!({
421            "type": "object",
422            "properties": {}
423        }))
424    }
425
426    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
427        self.browser.minimize_window().await?;
428
429        Ok(json!({
430            "success": true,
431            "message": "Window minimized"
432        }))
433    }
434}
435
436/// Tool for setting window size.
437pub struct SetWindowSizeTool {
438    browser: Arc<BrowserSession>,
439}
440
441impl SetWindowSizeTool {
442    pub fn new(browser: Arc<BrowserSession>) -> Self {
443        Self { browser }
444    }
445}
446
447#[async_trait]
448impl Tool for SetWindowSizeTool {
449    fn name(&self) -> &str {
450        "browser_set_window_size"
451    }
452
453    fn description(&self) -> &str {
454        "Set the browser window size and position."
455    }
456
457    fn parameters_schema(&self) -> Option<Value> {
458        Some(json!({
459            "type": "object",
460            "properties": {
461                "width": {
462                    "type": "integer",
463                    "description": "Window width in pixels"
464                },
465                "height": {
466                    "type": "integer",
467                    "description": "Window height in pixels"
468                },
469                "x": {
470                    "type": "integer",
471                    "description": "Window X position (default: 0)"
472                },
473                "y": {
474                    "type": "integer",
475                    "description": "Window Y position (default: 0)"
476                }
477            },
478            "required": ["width", "height"]
479        }))
480    }
481
482    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
483        let width = args
484            .get("width")
485            .and_then(|v| v.as_u64())
486            .ok_or_else(|| AdkError::tool("Missing 'width' parameter"))? as u32;
487
488        let height =
489            args.get("height")
490                .and_then(|v| v.as_u64())
491                .ok_or_else(|| AdkError::tool("Missing 'height' parameter"))? as u32;
492
493        let x = args.get("x").and_then(|v| v.as_i64()).unwrap_or(0) as i32;
494        let y = args.get("y").and_then(|v| v.as_i64()).unwrap_or(0) as i32;
495
496        self.browser.set_window_rect(x, y, width, height).await?;
497
498        Ok(json!({
499            "success": true,
500            "width": width,
501            "height": height,
502            "x": x,
503            "y": y
504        }))
505    }
506}