Skip to main content

adk_browser/tools/
actions.rs

1//! Advanced action tools (drag-drop, context-click, focus, etc.)
2
3use crate::session::BrowserSession;
4use adk_core::{AdkError, Result, Tool, ToolContext};
5use async_trait::async_trait;
6use serde_json::{Value, json};
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9
10/// Tool for drag and drop operations.
11pub struct DragAndDropTool {
12    browser: Arc<BrowserSession>,
13}
14
15impl DragAndDropTool {
16    pub fn new(browser: Arc<BrowserSession>) -> Self {
17        Self { browser }
18    }
19}
20
21#[async_trait]
22impl Tool for DragAndDropTool {
23    fn name(&self) -> &str {
24        "browser_drag_and_drop"
25    }
26
27    fn description(&self) -> &str {
28        "Drag an element and drop it onto another element."
29    }
30
31    fn parameters_schema(&self) -> Option<Value> {
32        Some(json!({
33            "type": "object",
34            "properties": {
35                "source_selector": {
36                    "type": "string",
37                    "description": "CSS selector for the element to drag"
38                },
39                "target_selector": {
40                    "type": "string",
41                    "description": "CSS selector for the drop target"
42                }
43            },
44            "required": ["source_selector", "target_selector"]
45        }))
46    }
47
48    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
49        let source = args
50            .get("source_selector")
51            .and_then(|v| v.as_str())
52            .ok_or_else(|| AdkError::tool("Missing 'source_selector' parameter"))?;
53
54        let target = args
55            .get("target_selector")
56            .and_then(|v| v.as_str())
57            .ok_or_else(|| AdkError::tool("Missing 'target_selector' parameter"))?;
58
59        self.browser.drag_and_drop(source, target).await?;
60
61        Ok(json!({
62            "success": true,
63            "dragged_from": source,
64            "dropped_on": target
65        }))
66    }
67}
68
69/// Tool for right-click (context click).
70pub struct RightClickTool {
71    browser: Arc<BrowserSession>,
72}
73
74impl RightClickTool {
75    pub fn new(browser: Arc<BrowserSession>) -> Self {
76        Self { browser }
77    }
78}
79
80#[async_trait]
81impl Tool for RightClickTool {
82    fn name(&self) -> &str {
83        "browser_right_click"
84    }
85
86    fn description(&self) -> &str {
87        "Right-click (context click) on an element to open context menu."
88    }
89
90    fn parameters_schema(&self) -> Option<Value> {
91        Some(json!({
92            "type": "object",
93            "properties": {
94                "selector": {
95                    "type": "string",
96                    "description": "CSS selector for the element to right-click"
97                }
98            },
99            "required": ["selector"]
100        }))
101    }
102
103    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
104        let selector = args
105            .get("selector")
106            .and_then(|v| v.as_str())
107            .ok_or_else(|| AdkError::tool("Missing 'selector' parameter"))?;
108
109        self.browser.right_click(selector).await?;
110
111        Ok(json!({
112            "success": true,
113            "right_clicked": selector
114        }))
115    }
116}
117
118/// Tool for focusing an element.
119pub struct FocusTool {
120    browser: Arc<BrowserSession>,
121}
122
123impl FocusTool {
124    pub fn new(browser: Arc<BrowserSession>) -> Self {
125        Self { browser }
126    }
127}
128
129#[async_trait]
130impl Tool for FocusTool {
131    fn name(&self) -> &str {
132        "browser_focus"
133    }
134
135    fn description(&self) -> &str {
136        "Focus on an element (useful for inputs before typing)."
137    }
138
139    fn parameters_schema(&self) -> Option<Value> {
140        Some(json!({
141            "type": "object",
142            "properties": {
143                "selector": {
144                    "type": "string",
145                    "description": "CSS selector for the element to focus"
146                }
147            },
148            "required": ["selector"]
149        }))
150    }
151
152    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
153        let selector = args
154            .get("selector")
155            .and_then(|v| v.as_str())
156            .ok_or_else(|| AdkError::tool("Missing 'selector' parameter"))?;
157
158        self.browser.focus_element(selector).await?;
159
160        Ok(json!({
161            "success": true,
162            "focused": selector
163        }))
164    }
165}
166
167/// Tool for checking element state (visible, enabled, selected).
168pub struct ElementStateTool {
169    browser: Arc<BrowserSession>,
170}
171
172impl ElementStateTool {
173    pub fn new(browser: Arc<BrowserSession>) -> Self {
174        Self { browser }
175    }
176}
177
178#[async_trait]
179impl Tool for ElementStateTool {
180    fn name(&self) -> &str {
181        "browser_element_state"
182    }
183
184    fn description(&self) -> &str {
185        "Check the state of an element (displayed, enabled, selected, clickable)."
186    }
187
188    fn parameters_schema(&self) -> Option<Value> {
189        Some(json!({
190            "type": "object",
191            "properties": {
192                "selector": {
193                    "type": "string",
194                    "description": "CSS selector for the element"
195                }
196            },
197            "required": ["selector"]
198        }))
199    }
200
201    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
202        let selector = args
203            .get("selector")
204            .and_then(|v| v.as_str())
205            .ok_or_else(|| AdkError::tool("Missing 'selector' parameter"))?;
206
207        let state = self.browser.get_element_state(selector).await?;
208
209        Ok(json!({
210            "success": true,
211            "selector": selector,
212            "is_displayed": state.is_displayed,
213            "is_enabled": state.is_enabled,
214            "is_selected": state.is_selected,
215            "is_clickable": state.is_clickable
216        }))
217    }
218}
219
220/// Tool for pressing keyboard keys.
221pub struct PressKeyTool {
222    browser: Arc<BrowserSession>,
223}
224
225impl PressKeyTool {
226    pub fn new(browser: Arc<BrowserSession>) -> Self {
227        Self { browser }
228    }
229}
230
231#[async_trait]
232impl Tool for PressKeyTool {
233    fn name(&self) -> &str {
234        "browser_press_key"
235    }
236
237    fn description(&self) -> &str {
238        "Press a keyboard key (Enter, Escape, Tab, etc.) optionally on a specific element."
239    }
240
241    fn parameters_schema(&self) -> Option<Value> {
242        Some(json!({
243            "type": "object",
244            "properties": {
245                "key": {
246                    "type": "string",
247                    "description": "Key to press: Enter, Escape, Tab, Backspace, Delete, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, etc."
248                },
249                "selector": {
250                    "type": "string",
251                    "description": "Optional CSS selector for the target element"
252                },
253                "modifiers": {
254                    "type": "array",
255                    "items": { "type": "string" },
256                    "description": "Optional modifier keys: Ctrl, Alt, Shift, Meta"
257                }
258            },
259            "required": ["key"]
260        }))
261    }
262
263    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
264        let key = args
265            .get("key")
266            .and_then(|v| v.as_str())
267            .ok_or_else(|| AdkError::tool("Missing 'key' parameter"))?;
268
269        let selector = args.get("selector").and_then(|v| v.as_str());
270        let modifiers: Vec<&str> = args
271            .get("modifiers")
272            .and_then(|v| v.as_array())
273            .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
274            .unwrap_or_default();
275
276        self.browser.press_key(key, selector, &modifiers).await?;
277
278        Ok(json!({
279            "success": true,
280            "key_pressed": key,
281            "modifiers": modifiers,
282            "target": selector
283        }))
284    }
285}
286
287/// Tool for uploading files.
288///
289/// Uploads only files inside the roots set with
290/// [`with_allowed_roots`](Self::with_allowed_roots); with none set, every upload is refused. A
291/// model-chosen path is resolved — symlinks and `..` included — and must name an existing file
292/// under a resolved root, so the model cannot hand a page `~/.ssh/id_rsa` or a symlink to it.
293pub struct FileUploadTool {
294    browser: Arc<BrowserSession>,
295    allowed_roots: Vec<PathBuf>,
296}
297
298impl FileUploadTool {
299    /// Create an upload tool that refuses every upload until roots are allowed.
300    pub fn new(browser: Arc<BrowserSession>) -> Self {
301        Self { browser, allowed_roots: Vec::new() }
302    }
303
304    /// Replace the directories files may be uploaded from.
305    ///
306    /// # Example
307    ///
308    /// ```rust,ignore
309    /// use adk_browser::{BrowserSession, FileUploadTool};
310    /// use std::sync::Arc;
311    ///
312    /// let browser = Arc::new(BrowserSession::with_defaults());
313    /// let tool = FileUploadTool::new(browser).with_allowed_roots(["/srv/agent/uploads"]);
314    /// ```
315    #[must_use]
316    pub fn with_allowed_roots<I, P>(mut self, roots: I) -> Self
317    where
318        I: IntoIterator<Item = P>,
319        P: Into<PathBuf>,
320    {
321        self.allowed_roots = roots.into_iter().map(Into::into).collect();
322        self
323    }
324
325    /// Resolves `requested` and returns it when it is an existing file inside an allowed root.
326    fn resolve_upload(&self, requested: &str) -> Result<String> {
327        resolve_upload(&self.allowed_roots, requested)
328    }
329}
330
331/// Resolves `requested` and returns it when it is an existing file inside one of `roots`,
332/// following symlinks and `..` segments.
333pub(crate) fn resolve_upload(roots: &[PathBuf], requested: &str) -> Result<String> {
334    if roots.is_empty() {
335        return Err(AdkError::tool(
336            "File upload is disabled: no upload roots are configured. Enable it with \
337             BrowserToolset::with_file_upload or FileUploadTool::with_allowed_roots.",
338        ));
339    }
340    let refused = || {
341        AdkError::tool(format!(
342            "File '{requested}' is not an existing file inside an allowed upload root"
343        ))
344    };
345    // WebDriver reads a newline as a separator between several files.
346    if requested.contains(['\n', '\r']) {
347        return Err(refused());
348    }
349    let resolved = std::fs::canonicalize(Path::new(requested)).map_err(|_| refused())?;
350    let inside = roots
351        .iter()
352        .filter_map(|root| std::fs::canonicalize(root).ok())
353        .any(|root| resolved.starts_with(root));
354    if !inside || !resolved.is_file() {
355        return Err(refused());
356    }
357    resolved.into_os_string().into_string().map_err(|_| refused())
358}
359
360#[async_trait]
361impl Tool for FileUploadTool {
362    fn name(&self) -> &str {
363        "browser_file_upload"
364    }
365
366    fn description(&self) -> &str {
367        "Upload a file to a file input element."
368    }
369
370    fn parameters_schema(&self) -> Option<Value> {
371        Some(json!({
372            "type": "object",
373            "properties": {
374                "selector": {
375                    "type": "string",
376                    "description": "CSS selector for the file input element"
377                },
378                "file_path": {
379                    "type": "string",
380                    "description": "Path to the file to upload, inside an allowed upload directory"
381                }
382            },
383            "required": ["selector", "file_path"]
384        }))
385    }
386
387    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
388        let selector = args
389            .get("selector")
390            .and_then(|v| v.as_str())
391            .ok_or_else(|| AdkError::tool("Missing 'selector' parameter"))?;
392
393        let file_path = args
394            .get("file_path")
395            .and_then(|v| v.as_str())
396            .ok_or_else(|| AdkError::tool("Missing 'file_path' parameter"))?;
397        let resolved = self.resolve_upload(file_path)?;
398
399        self.browser.upload_file(selector, &resolved).await?;
400
401        Ok(json!({
402            "success": true,
403            "uploaded_file": file_path,
404            "to_element": selector
405        }))
406    }
407}
408
409/// Tool for printing page to PDF.
410pub struct PrintToPdfTool {
411    browser: Arc<BrowserSession>,
412}
413
414impl PrintToPdfTool {
415    pub fn new(browser: Arc<BrowserSession>) -> Self {
416        Self { browser }
417    }
418}
419
420#[async_trait]
421impl Tool for PrintToPdfTool {
422    fn name(&self) -> &str {
423        "browser_print_to_pdf"
424    }
425
426    fn description(&self) -> &str {
427        "Print the current page to PDF and return as base64."
428    }
429
430    fn parameters_schema(&self) -> Option<Value> {
431        Some(json!({
432            "type": "object",
433            "properties": {
434                "landscape": {
435                    "type": "boolean",
436                    "description": "Print in landscape orientation (default: false)"
437                },
438                "scale": {
439                    "type": "number",
440                    "description": "Scale factor (default: 1.0)"
441                }
442            }
443        }))
444    }
445
446    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
447        let landscape = args.get("landscape").and_then(|v| v.as_bool()).unwrap_or(false);
448        let scale = args.get("scale").and_then(|v| v.as_f64()).unwrap_or(1.0);
449
450        let pdf_base64 = self.browser.print_to_pdf(landscape, scale).await?;
451
452        Ok(json!({
453            "success": true,
454            "pdf_base64": pdf_base64
455        }))
456    }
457}