oxi-agent 0.23.0

Agent runtime with tool-calling loop for AI coding assistants
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
//! Interactive browser session tool — persistent tab across tool calls.
//!
//! Manages a single browser tab that persists between `execute()` calls,
//! enabling multi-step workflows where the agent can reason between actions.
//! Uses `TabGuard` for RAII cleanup on drop.

use super::config::BrowseConfig;
use super::engine::{BrowserEngine, BrowserError};
use super::helpers;
use super::tab_guard::TabGuard;
use crate::tools::{AgentTool, AgentToolResult, ToolContext, ToolError};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::{oneshot, Mutex};

/// Interactive browser session with a persistent tab across calls.
///
/// Open a session, perform multiple operations (goto, click, fill, etc.),
/// read page content between steps, then close when done. The tab retains
/// cookies, localStorage, and DOM state between actions.
pub struct BrowseSessionTool {
    engine: Arc<dyn BrowserEngine>,
    tab: Arc<Mutex<Option<TabGuard>>>,
    config: BrowseConfig,
    last_action: Arc<Mutex<Option<Instant>>>,
}

impl BrowseSessionTool {
    /// Create with the given engine and default config.
    pub fn new(engine: Arc<dyn BrowserEngine>) -> Self {
        Self {
            engine,
            tab: Arc::new(Mutex::new(None)),
            config: BrowseConfig::default(),
            last_action: Arc::new(Mutex::new(None)),
        }
    }

    /// Create with custom configuration.
    pub fn with_config(engine: Arc<dyn BrowserEngine>, config: BrowseConfig) -> Self {
        Self {
            engine,
            tab: Arc::new(Mutex::new(None)),
            config,
            last_action: Arc::new(Mutex::new(None)),
        }
    }

    /// Update the last-action timestamp to now.
    async fn touch(&self) {
        *self.last_action.lock().await = Some(Instant::now());
    }

    /// Check idle timeout. Returns Ok if session is still valid or
    /// if idle timeout is disabled (0). Auto-closes stale sessions.
    async fn check_idle_timeout(&self) -> Result<(), ToolError> {
        if self.config.session_idle_timeout_secs == 0 {
            return Ok(());
        }
        let elapsed = {
            let last = self.last_action.lock().await;
            match *last {
                Some(instant) => instant.elapsed().as_secs(),
                None => return Ok(()), // No action yet, session is fresh
            }
        };
        if elapsed >= self.config.session_idle_timeout_secs {
            // Auto-close stale session
            let mut slot = self.tab.lock().await;
            if let Some(guard) = slot.take() {
                tracing::warn!(
                    elapsed_secs = elapsed,
                    timeout_secs = self.config.session_idle_timeout_secs,
                    "browse_session: auto-closing stale session"
                );
                guard.close().await;
            }
            return Err(format!(
                "Session timed out after {}s of inactivity",
                elapsed
            ));
        }
        Ok(())
    }
}

#[async_trait]
impl AgentTool for BrowseSessionTool {
    fn name(&self) -> &str {
        "browse_session"
    }

    fn label(&self) -> &str {
        "Browser Session"
    }

    fn description(&self) -> &str {
        "Interactive browser session with a persistent tab across calls. \
         Open a session, perform multiple operations, then close when done. \
         The tab retains cookies, localStorage, and DOM state between actions. \
         Use for multi-step interactions like form filling, login flows, and \
         SPA exploration where reasoning is needed between steps."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": [
                        "open",
                        "goto",
                        "back",
                        "forward",
                        "reload",
                        "click",
                        "fill",
                        "type",
                        "clear",
                        "press",
                        "select",
                        "check",
                        "uncheck",
                        "scroll",
                        "scroll_into_view",
                        "hover",
                        "double_click",
                        "right_click",
                        "drag",
                        "upload_file",
                        "wait_for",
                        "content",
                        "query_all",
                        "extract_links",
                        "evaluate",
                        "evaluate_await",
                        "get_value",
                        "screenshot",
                        "close"
                    ],
                    "description": "Session action to perform"
                },
                "url": {
                    "type": "string",
                    "description": "URL to navigate to (goto action)"
                },
                "selector": {
                    "type": "string",
                    "description": "CSS selector (click, fill, type, clear, select, check, uncheck, wait_for, query_all, extract_links)"
                },
                "value": {
                    "type": "string",
                    "description": "Value to fill/type/select (fill, type, select actions)"
                },
                "combo": {
                    "type": "string",
                    "description": "Key combo (press action, e.g. 'Enter', 'Control+a')"
                },
                "pixels": {
                    "type": "integer",
                    "description": "Scroll distance in pixels (scroll action, positive = down)"
                },
                "javascript": {
                    "type": "string",
                    "description": "JS expression to evaluate (evaluate, evaluate_await actions)"
                },
                "format": {
                    "type": "string",
                    "enum": ["markdown", "html", "text", "links"],
                    "default": "markdown",
                    "description": "Output format for content action"
                },
                "timeout_ms": {
                    "type": "integer",
                    "default": 10000,
                    "description": "Timeout in ms (wait_for action)"
                },
                "from_selector": {
                    "type": "string",
                    "description": "Source CSS selector (drag action)"
                },
                "to_selector": {
                    "type": "string",
                    "description": "Target CSS selector (drag action)"
                },
                "file_path": {
                    "type": "string",
                    "description": "Local file path to upload (upload_file action)"
                },
                "width": {
                    "type": "integer",
                    "default": 800,
                    "description": "Viewport width for screenshot (default: 800)"
                }
            },
            "required": ["action"]
        })
    }

    #[allow(clippy::too_many_lines)]
    async fn execute(
        &self,
        _tool_call_id: &str,
        params: Value,
        _signal: Option<oneshot::Receiver<()>>,
        _ctx: &ToolContext,
    ) -> Result<AgentToolResult, ToolError> {
        let action = params["action"]
            .as_str()
            .ok_or_else(|| "Missing required parameter: action".to_string())?;

        let url = params["url"].as_str();
        let selector = params["selector"].as_str();
        let value = params["value"].as_str();
        let combo = params["combo"].as_str();
        let pixels = params["pixels"].as_u64().unwrap_or(300);
        let javascript = params["javascript"].as_str();
        let format = params["format"].as_str().unwrap_or("markdown");
        let timeout_ms = params["timeout_ms"]
            .as_u64()
            .unwrap_or(self.config.default_wait_timeout_ms);
        let width = params["width"]
            .as_u64()
            .unwrap_or(self.config.screenshot_width as u64) as u32;
        let from_selector = params["from_selector"].as_str();
        let to_selector = params["to_selector"].as_str();
        let file_path = params["file_path"].as_str();

        tracing::info!(action = %action, "browse_session action");

        self.touch().await;

        match action {
            // ── Lifecycle ────────────────────────────────────────────
            "open" => {
                let mut slot = self.tab.lock().await;
                // If a session is already open, close it first
                if let Some(old_guard) = slot.take() {
                    tracing::warn!("browse_session: closing previous session on re-open");
                    old_guard.close().await;
                }
                let raw_tab = self
                    .engine
                    .new_tab()
                    .await
                    .map_err(|e| format!("Failed to open browser tab: {}", e))?;
                let guard = TabGuard::new(raw_tab);
                *slot = Some(guard);
                Ok(json_ok())
            }

            "close" => {
                let mut slot = self.tab.lock().await;
                match slot.take() {
                    Some(guard) => {
                        guard.close().await;
                        Ok(json_ok())
                    }
                    None => Ok(json_error("no active session to close")),
                }
            }

            // ── Navigation ──────────────────────────────────────────
            "goto" => {
                self.check_idle_timeout().await?;
                let url = url.ok_or_else(|| "Missing required parameter: url".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                let page = tab.goto(url).await.map_err(browser_err)?;
                Ok(AgentToolResult::success(json_str(&json!({
                    "status": "ok",
                    "url": page.url,
                    "title": page.title,
                    "status_code": page.status,
                }))))
            }

            "back" => {
                self.check_idle_timeout().await?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                let _ = tab.evaluate("history.back()").await;
                let page = tab.content().await.map_err(browser_err)?;
                Ok(AgentToolResult::success(json_str(&json!({
                    "status": "ok",
                    "url": page.url,
                    "title": page.title,
                }))))
            }

            "forward" => {
                self.check_idle_timeout().await?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                let _ = tab.evaluate("history.forward()").await;
                let page = tab.content().await.map_err(browser_err)?;
                Ok(AgentToolResult::success(json_str(&json!({
                    "status": "ok",
                    "url": page.url,
                    "title": page.title,
                }))))
            }

            "reload" => {
                self.check_idle_timeout().await?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                let _ = tab.evaluate("location.reload()").await;
                let page = tab.content().await.map_err(browser_err)?;
                Ok(AgentToolResult::success(json_str(&json!({
                    "status": "ok",
                    "url": page.url,
                    "title": page.title,
                }))))
            }

            // ── DOM interaction ─────────────────────────────────────
            "click" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.click(sel).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "fill" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let val = value.ok_or_else(|| "Missing required parameter: value".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.fill(sel, val).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "type" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let val = value.ok_or_else(|| "Missing required parameter: value".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.type_(sel, val).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "clear" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.clear(sel).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "press" => {
                self.check_idle_timeout().await?;
                let c = combo.ok_or_else(|| "Missing required parameter: combo".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.press(c).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "select" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let val = value.ok_or_else(|| "Missing required parameter: value".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.select_option(sel, val).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "check" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.check(sel).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "uncheck" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.uncheck(sel).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "scroll" => {
                self.check_idle_timeout().await?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.scroll(0.0, pixels as f64).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            // ── Wait ────────────────────────────────────────────────
            "wait_for" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.wait_for(sel, timeout_ms).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            // ── Read ────────────────────────────────────────────────
            "content" => {
                self.check_idle_timeout().await?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                let page = tab.content().await.map_err(browser_err)?;

                let content = match format {
                    "html" => {
                        if let Some(sel) = selector {
                            tab.query_all(sel).await.map_err(browser_err)?.join("\n\n")
                        } else {
                            page.html.clone()
                        }
                    }
                    "links" => {
                        let links = if let Some(sel) = selector {
                            let js = helpers::js_links_within(sel);
                            let value = tab.evaluate(&js).await.map_err(browser_err)?;
                            helpers::parse_link_values(value)
                        } else {
                            helpers::extract_links(tab)
                                .await
                                .map_err(|e: ToolError| e)?
                        };
                        helpers::format_links(&links)
                    }
                    "text" => {
                        if let Some(sel) = selector {
                            tab.query_all(sel).await.map_err(browser_err)?.join("\n")
                        } else {
                            page.markdown.clone()
                        }
                    }
                    _ => {
                        // "markdown" (default)
                        if let Some(sel) = selector {
                            tab.query_all(sel).await.map_err(browser_err)?.join("\n\n")
                        } else {
                            page.markdown.clone()
                        }
                    }
                };

                Ok(AgentToolResult::success(json_str(&json!({
                    "status": "ok",
                    "url": page.url,
                    "title": page.title,
                    "content": content,
                }))))
            }

            "query_all" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                let results = tab.query_all(sel).await.map_err(browser_err)?;
                Ok(AgentToolResult::success(json_str(&json!({
                    "status": "ok",
                    "results": results,
                }))))
            }

            "extract_links" => {
                self.check_idle_timeout().await?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;

                let links = if let Some(sel) = selector {
                    let js = helpers::js_links_within(sel);
                    let value = tab.evaluate(&js).await.map_err(browser_err)?;
                    helpers::parse_link_values(value)
                } else {
                    helpers::extract_links(tab)
                        .await
                        .map_err(|e: ToolError| e)?
                };

                let json_links: Vec<Value> = links
                    .iter()
                    .map(|(text, href)| json!({ "text": text, "href": href }))
                    .collect();

                Ok(AgentToolResult::success(json_str(&json!({
                    "status": "ok",
                    "links": json_links,
                }))))
            }

            // ── Evaluate ────────────────────────────────────────────
            "evaluate" => {
                self.check_idle_timeout().await?;
                let js = javascript
                    .ok_or_else(|| "Missing required parameter: javascript".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                let result_val = tab.evaluate(js).await.map_err(browser_err)?;
                Ok(AgentToolResult::success(json_str(&json!({
                    "status": "ok",
                    "result": result_val,
                }))))
            }

            "evaluate_await" => {
                self.check_idle_timeout().await?;
                let js = javascript
                    .ok_or_else(|| "Missing required parameter: javascript".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                let result_val = tab.evaluate_await(js).await.map_err(browser_err)?;
                Ok(AgentToolResult::success(json_str(&json!({
                    "status": "ok",
                    "result": result_val,
                }))))
            }

            // ── Screenshot ──────────────────────────────────────────
            "screenshot" => {
                self.check_idle_timeout().await?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                let png = tab.screenshot(width).await.map_err(browser_err)?;
                let size_bytes = png.len();
                let b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &png);
                let img = oxi_ai::ContentBlock::Image(oxi_ai::ImageContent::new(b64, "image/png"));

                Ok(AgentToolResult::success(json_str(&json!({
                    "status": "ok",
                    "size_bytes": size_bytes,
                })))
                .with_content_blocks(vec![img]))
            }

            // ── Extended DOM actions ──────────────────────────────
            "scroll_into_view" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.scroll_into_view(sel).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "hover" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.hover(sel).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "double_click" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.double_click(sel).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "right_click" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.right_click(sel).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "drag" => {
                self.check_idle_timeout().await?;
                let from = from_selector
                    .ok_or_else(|| "Missing required parameter: from_selector".to_string())?;
                let to = to_selector
                    .ok_or_else(|| "Missing required parameter: to_selector".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.drag(from, to).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "upload_file" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let path =
                    file_path.ok_or_else(|| "Missing required parameter: file_path".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                tab.upload_file(sel, path).await.map_err(browser_err)?;
                Ok(json_ok())
            }

            "get_value" => {
                self.check_idle_timeout().await?;
                let sel =
                    selector.ok_or_else(|| "Missing required parameter: selector".to_string())?;
                let slot = self.tab.lock().await;
                let tab = require_tab(&slot)?;
                let result_val = tab.get_value(sel).await.map_err(browser_err)?;
                Ok(AgentToolResult::success(json_str(&json!({
                    "status": "ok",
                    "value": result_val,
                }))))
            }

            _ => Err(format!(
                "Unknown action: '{}'. Valid actions: open, goto, back, forward, reload, \
                 click, fill, type, clear, press, select, check, uncheck, scroll, \
                 scroll_into_view, hover, double_click, right_click, drag, upload_file, \
                 wait_for, content, query_all, extract_links, evaluate, evaluate_await, \
                 get_value, screenshot, close",
                action
            )),
        }
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

/// Get a reference to the tab from the locked slot, or return an error.
fn require_tab(slot: &Option<TabGuard>) -> Result<&dyn super::engine::BrowserTab, ToolError> {
    match slot {
        Some(guard) => Ok(guard.tab()),
        None => Err(BrowserError::NoActiveSession.into()),
    }
}

/// Serialize a JSON value to a pretty string.
fn json_str(v: &Value) -> String {
    serde_json::to_string_pretty(v).unwrap_or_default()
}

/// Create a JSON success result.
fn json_ok() -> AgentToolResult {
    AgentToolResult::success(json_str(&json!({ "status": "ok" })))
}

/// Create a JSON error result (still `success: true` — error is in the payload).
fn json_error(msg: &str) -> AgentToolResult {
    AgentToolResult::success(json_str(&json!({
        "status": "error",
        "error": msg,
    })))
}

/// Convert a `BrowserError` into a `ToolError`.
fn browser_err(e: BrowserError) -> ToolError {
    e.to_string()
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::browse::engine::{BrowserError, PageContent};
    use async_trait::async_trait;
    use std::sync::atomic::{AtomicBool, Ordering};

    // ── Mock tab for unit tests ─────────────────────────────────

    struct MockTab {
        closed: Arc<AtomicBool>,
    }

    impl MockTab {
        fn new() -> (Self, Arc<AtomicBool>) {
            let closed = Arc::new(AtomicBool::new(false));
            (
                Self {
                    closed: closed.clone(),
                },
                closed,
            )
        }
    }

    #[async_trait]
    impl super::super::engine::BrowserTab for MockTab {
        async fn goto(&self, _url: &str) -> Result<PageContent, BrowserError> {
            Ok(PageContent {
                url: "https://example.com".into(),
                title: "Example".into(),
                status: 200,
                markdown: "# Example\nHello".into(),
                html: "<h1>Example</h1>".into(),
            })
        }
        async fn click(&self, _selector: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn type_(&self, _selector: &str, _text: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn fill(&self, _selector: &str, _value: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn press(&self, _combo: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn wait_for(&self, _selector: &str, _timeout_ms: u64) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn content(&self) -> Result<PageContent, BrowserError> {
            Ok(PageContent {
                url: "https://example.com".into(),
                title: "Example".into(),
                status: 200,
                markdown: "# Example\nHello".into(),
                html: "<h1>Example</h1>".into(),
            })
        }
        async fn query_all(&self, _selector: &str) -> Result<Vec<String>, BrowserError> {
            Ok(vec!["item1".into(), "item2".into()])
        }
        async fn evaluate(&self, _js: &str) -> Result<Value, BrowserError> {
            Ok(Value::String("ok".into()))
        }
        async fn screenshot(&self, _width: u32) -> Result<Vec<u8>, BrowserError> {
            Ok(vec![0x89, 0x50, 0x4E, 0x47]) // PNG magic bytes
        }
        async fn close(&self) -> Result<(), BrowserError> {
            self.closed.store(true, Ordering::SeqCst);
            Ok(())
        }
        async fn select_option(&self, _selector: &str, _value: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn check(&self, _selector: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn uncheck(&self, _selector: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn hover(&self, _selector: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn double_click(&self, _selector: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn right_click(&self, _selector: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn scroll_into_view(&self, _selector: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn drag(&self, _from_selector: &str, _to_selector: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn upload_file(&self, _selector: &str, _path: &str) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn get_value(&self, _selector: &str) -> Result<String, BrowserError> {
            Ok("mock_value".into())
        }
        async fn evaluate_await(&self, _js: &str) -> Result<Value, BrowserError> {
            Ok(Value::String("ok".into()))
        }
    }

    // ── Mock engine ─────────────────────────────────────────────

    struct MockEngine;

    #[async_trait]
    impl super::super::engine::BrowserEngine for MockEngine {
        async fn new_tab(&self) -> Result<Box<dyn super::super::engine::BrowserTab>, BrowserError> {
            let (tab, _) = MockTab::new();
            Ok(Box::new(tab))
        }
        async fn close(&self) -> Result<(), BrowserError> {
            Ok(())
        }
        async fn is_alive(&self) -> bool {
            true
        }
    }

    /// Create a tool with a mock engine for testing.
    fn make_tool() -> BrowseSessionTool {
        let engine: Arc<dyn BrowserEngine> = Arc::new(MockEngine);
        BrowseSessionTool::new(engine)
    }

    // ── Tests ──────────────────────────────────────────────────

    #[tokio::test]
    async fn test_open_close_lifecycle() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        let result = tool
            .execute("c1", json!({"action": "open"}), None, &ctx)
            .await
            .unwrap();
        assert!(result.success);
        assert!(result.output.contains("ok"));

        let result = tool
            .execute("c2", json!({"action": "close"}), None, &ctx)
            .await
            .unwrap();
        assert!(result.success);
    }

    #[tokio::test]
    async fn test_goto_requires_open_session() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        let result = tool
            .execute(
                "c1",
                json!({"action": "goto", "url": "https://example.com"}),
                None,
                &ctx,
            )
            .await;
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("no active session"));
    }

    #[tokio::test]
    async fn test_open_goto_close() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        tool.execute("c1", json!({"action": "open"}), None, &ctx)
            .await
            .unwrap();

        let result = tool
            .execute(
                "c2",
                json!({"action": "goto", "url": "https://example.com"}),
                None,
                &ctx,
            )
            .await
            .unwrap();
        assert!(result.success);
        assert!(result.output.contains("example.com"));
        assert!(result.output.contains("200"));

        let result = tool
            .execute("c3", json!({"action": "close"}), None, &ctx)
            .await
            .unwrap();
        assert!(result.success);
    }

    #[tokio::test]
    async fn test_content_action() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        tool.execute("c1", json!({"action": "open"}), None, &ctx)
            .await
            .unwrap();
        tool.execute(
            "c2",
            json!({"action": "goto", "url": "https://example.com"}),
            None,
            &ctx,
        )
        .await
        .unwrap();

        let result = tool
            .execute(
                "c3",
                json!({"action": "content", "format": "markdown"}),
                None,
                &ctx,
            )
            .await
            .unwrap();
        assert!(result.success);
        assert!(result.output.contains("Example"));
        assert!(result.output.contains("Hello"));

        tool.execute("c4", json!({"action": "close"}), None, &ctx)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_query_all_action() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        tool.execute("c1", json!({"action": "open"}), None, &ctx)
            .await
            .unwrap();

        let result = tool
            .execute(
                "c2",
                json!({"action": "query_all", "selector": ".item"}),
                None,
                &ctx,
            )
            .await
            .unwrap();
        assert!(result.success);
        assert!(result.output.contains("item1"));
        assert!(result.output.contains("item2"));

        tool.execute("c3", json!({"action": "close"}), None, &ctx)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_evaluate_action() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        tool.execute("c1", json!({"action": "open"}), None, &ctx)
            .await
            .unwrap();

        let result = tool
            .execute(
                "c2",
                json!({"action": "evaluate", "javascript": "document.title"}),
                None,
                &ctx,
            )
            .await
            .unwrap();
        assert!(result.success);
        assert!(result.output.contains("ok"));

        tool.execute("c3", json!({"action": "close"}), None, &ctx)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_screenshot_action() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        tool.execute("c1", json!({"action": "open"}), None, &ctx)
            .await
            .unwrap();

        let result = tool
            .execute("c2", json!({"action": "screenshot"}), None, &ctx)
            .await
            .unwrap();
        assert!(result.success);
        assert!(result.output.contains("size_bytes"));
        assert!(result.content_blocks.is_some());

        tool.execute("c3", json!({"action": "close"}), None, &ctx)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_dom_actions() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        tool.execute("c1", json!({"action": "open"}), None, &ctx)
            .await
            .unwrap();

        let actions: Vec<(&str, Value)> = vec![
            ("click", json!({"action": "click", "selector": "#btn"})),
            (
                "fill",
                json!({"action": "fill", "selector": "#input", "value": "hello"}),
            ),
            (
                "type",
                json!({"action": "type", "selector": "#input", "value": "world"}),
            ),
            ("clear", json!({"action": "clear", "selector": "#input"})),
            ("press", json!({"action": "press", "combo": "Enter"})),
            ("check", json!({"action": "check", "selector": "#agree"})),
            (
                "uncheck",
                json!({"action": "uncheck", "selector": "#newsletter"}),
            ),
            ("scroll", json!({"action": "scroll", "pixels": 500})),
            (
                "wait_for",
                json!({"action": "wait_for", "selector": ".loaded"}),
            ),
            (
                "scroll_into_view",
                json!({"action": "scroll_into_view", "selector": "#section"}),
            ),
            ("hover", json!({"action": "hover", "selector": "#menu"})),
            (
                "double_click",
                json!({"action": "double_click", "selector": "#item"}),
            ),
            (
                "right_click",
                json!({"action": "right_click", "selector": "#item"}),
            ),
            (
                "get_value",
                json!({"action": "get_value", "selector": "#input"}),
            ),
        ];

        for (name, params) in &actions {
            let result = tool.execute("cx", params.clone(), None, &ctx).await;
            assert!(result.is_ok(), "Action '{}' failed: {:?}", name, result);
        }

        tool.execute("c99", json!({"action": "close"}), None, &ctx)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_navigation_actions() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        tool.execute("c1", json!({"action": "open"}), None, &ctx)
            .await
            .unwrap();

        for nav_action in &["back", "forward", "reload"] {
            let result = tool
                .execute("cx", json!({"action": *nav_action}), None, &ctx)
                .await;
            assert!(result.is_ok(), "Navigation action '{}' failed", nav_action);
        }

        tool.execute("c99", json!({"action": "close"}), None, &ctx)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_unknown_action() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        let result = tool
            .execute("c1", json!({"action": "nonexistent"}), None, &ctx)
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Unknown action"));
    }

    #[tokio::test]
    async fn test_close_without_open() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        let result = tool
            .execute("c1", json!({"action": "close"}), None, &ctx)
            .await
            .unwrap();
        assert!(result.success);
        assert!(result.output.contains("error"));
    }

    #[tokio::test]
    async fn test_re_open_closes_previous() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        tool.execute("c1", json!({"action": "open"}), None, &ctx)
            .await
            .unwrap();

        let result = tool
            .execute("c2", json!({"action": "open"}), None, &ctx)
            .await
            .unwrap();
        assert!(result.success);

        let result = tool
            .execute(
                "c3",
                json!({"action": "goto", "url": "https://example.com"}),
                None,
                &ctx,
            )
            .await
            .unwrap();
        assert!(result.success);
    }

    #[tokio::test]
    async fn test_missing_required_params() {
        let tool = make_tool();
        let ctx = ToolContext::default();

        tool.execute("c1", json!({"action": "open"}), None, &ctx)
            .await
            .unwrap();

        // goto without url
        assert!(tool
            .execute("c2", json!({"action": "goto"}), None, &ctx)
            .await
            .is_err());

        // click without selector
        assert!(tool
            .execute("c3", json!({"action": "click"}), None, &ctx)
            .await
            .is_err());

        // fill without value
        assert!(tool
            .execute(
                "c4",
                json!({"action": "fill", "selector": "#x"}),
                None,
                &ctx
            )
            .await
            .is_err());

        // press without combo
        assert!(tool
            .execute("c5", json!({"action": "press"}), None, &ctx)
            .await
            .is_err());

        // evaluate without javascript
        assert!(tool
            .execute("c6", json!({"action": "evaluate"}), None, &ctx)
            .await
            .is_err());

        tool.execute("c7", json!({"action": "close"}), None, &ctx)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_name_label_description() {
        let tool = make_tool();
        assert_eq!(tool.name(), "browse_session");
        assert_eq!(tool.label(), "Browser Session");
        assert!(!tool.description().is_empty());
    }

    #[tokio::test]
    async fn test_schema_has_all_actions() {
        let tool = make_tool();
        let schema = tool.parameters_schema();
        let actions = schema["properties"]["action"]["enum"].as_array().unwrap();
        assert_eq!(actions.len(), 29);
    }
}