merry-tools 0.1.3

Workspace file, search, patch, web fetch, and document tools for the Merry agent runtime.
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
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
//! Native CDP browser automation and inspection tools (`browser_tab` & `browser_network`).

mod cdp;
mod launcher;
mod network_tool;
mod session;
mod tab_tool;
mod ws;

pub use launcher::{
    BrowserLaunchSpec, BrowserLauncherFuture, BrowserProcessHandle, BrowserProcessLauncher,
    ProcessRunnerBrowserLauncher, child_browser_process_handle,
};
pub use network_tool::{BROWSER_NETWORK_TOOL, BrowserNetworkTool};
pub use session::{BrowserConfig, BrowserSessionManager};
pub use tab_tool::{BROWSER_TAB_TOOL, BrowserTabTool};

#[cfg(test)]
mod tests {
    use super::cdp::CdpSession;
    use super::ws::handshake_ws;
    use super::*;
    use base64::{Engine as _, engine::general_purpose::STANDARD};
    use merry_core::{
        PendingToolCall, ToolCallArguments, ToolCallId, ToolCallResultStatus, ToolName,
    };
    use merry_runtime::{ToolExecutionContext, ToolExecutor};
    use serde_json::{Value, json};
    use std::{io::Cursor, sync::Arc};
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio_util::sync::CancellationToken;

    fn call(tool: &str, args: Value) -> PendingToolCall {
        PendingToolCall::new(
            ToolCallId::new("call-browser").expect("valid id"),
            ToolName::new(tool).expect("valid tool"),
            ToolCallArguments::try_from(args).expect("object args"),
        )
    }

    async fn write_server_text_frame<W: AsyncWriteExt + Unpin>(writer: &mut W, text: &str) {
        let bytes = text.as_bytes();
        let mut frame = Vec::with_capacity(10 + bytes.len());
        frame.push(0x81);
        if bytes.len() < 126 {
            frame.push(bytes.len() as u8);
        } else if let Ok(len16) = u16::try_from(bytes.len()) {
            frame.push(126);
            frame.extend_from_slice(&len16.to_be_bytes());
        } else {
            frame.push(127);
            frame.extend_from_slice(&(bytes.len() as u64).to_be_bytes());
        }
        frame.extend_from_slice(bytes);
        writer.write_all(&frame).await.expect("write ws text frame");
        writer.flush().await.expect("flush ws text frame");
    }

    async fn read_masked_client_text<R: AsyncReadExt + Unpin>(reader: &mut R) -> Option<String> {
        let mut header = [0u8; 2];
        if reader.read_exact(&mut header).await.is_err() {
            return None;
        }
        let opcode = header[0] & 0x0F;
        if opcode == 0x8 {
            return None;
        }
        let masked = (header[1] & 0x80) != 0;
        let len_code = header[1] & 0x7F;
        let len = match len_code {
            0..=125 => usize::from(len_code),
            126 => {
                let mut b = [0u8; 2];
                reader.read_exact(&mut b).await.ok()?;
                usize::from(u16::from_be_bytes(b))
            }
            127 => {
                let mut b = [0u8; 8];
                reader.read_exact(&mut b).await.ok()?;
                usize::try_from(u64::from_be_bytes(b)).ok()?
            }
            _ => unreachable!(),
        };
        let mask = if masked {
            let mut m = [0u8; 4];
            reader.read_exact(&mut m).await.ok()?;
            Some(m)
        } else {
            None
        };
        let mut payload = vec![0u8; len];
        reader.read_exact(&mut payload).await.ok()?;
        if let Some(m) = mask {
            for (i, byte) in payload.iter_mut().enumerate() {
                *byte ^= m[i % 4];
            }
        }
        String::from_utf8(payload).ok()
    }

    #[tokio::test]
    async fn browser_tab_and_network_work_with_cdp_events_screenshots_and_ssrf() {
        let (client_stream, server_stream) = tokio::io::duplex(16 * 1024);

        let mut png_bytes = Vec::new();
        let img = image::RgbaImage::from_pixel(3, 2, image::Rgba([0, 128, 255, 255]));
        image::DynamicImage::ImageRgba8(img)
            .write_to(&mut Cursor::new(&mut png_bytes), image::ImageFormat::Png)
            .expect("png encodes");
        let screenshot_b64 = STANDARD.encode(&png_bytes);

        let server_task = tokio::spawn(async move {
            let (mut s_read, mut s_write) = tokio::io::split(server_stream);
            let mut buf = [0u8; 1024];
            let _ = s_read.read(&mut buf).await.expect("upgrade");
            s_write
                .write_all(
                    b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n",
                )
                .await
                .expect("101");

            // Emit a console error and a numeric CDP requestId network event proactively!
            write_server_text_frame(
                &mut s_write,
                &json!({
                    "method": "Runtime.consoleAPICalled",
                    "params": {
                        "type": "error",
                        "args": [{ "value": "Uncaught TypeError: boom" }]
                    }
                })
                .to_string(),
            )
            .await;
            write_server_text_frame(
                &mut s_write,
                &json!({
                    "method": "Network.requestWillBeSent",
                    "params": {
                        "requestId": 62576.34,
                        "type": "Fetch",
                        "request": { "method": "GET", "url": "http://127.0.0.1:3000/api/health" }
                    }
                })
                .to_string(),
            )
            .await;
            write_server_text_frame(
                &mut s_write,
                &json!({
                    "method": "Network.responseReceived",
                    "params": {
                        "requestId": "62576.34",
                        "type": "Fetch",
                        "response": { "status": 500, "statusText": "Internal Server Error", "mimeType": "application/json" }
                    }
                })
                .to_string(),
            )
            .await;

            while let Some(raw) = read_masked_client_text(&mut s_read).await {
                let req: Value = serde_json::from_str(&raw).expect("valid rpc json");
                let id = req["id"].as_u64().expect("id");
                let method = req["method"].as_str().expect("method");
                let result = match method {
                    "Page.navigate" => json!({ "frameId": "main" }),
                    "Runtime.evaluate" => {
                        let expr = req["params"]["expression"].as_str().unwrap_or("");
                        if expr == "document.readyState" {
                            json!({ "result": { "value": "complete" } })
                        } else if expr.contains("interactive_elements") {
                            json!({
                                "result": {
                                    "value": {
                                        "url": "http://127.0.0.1:3000/",
                                        "title": "App Preview",
                                        "text": "Welcome",
                                        "interactive_elements": [{ "index": 0, "tag": "button", "selector": "#save", "label": "Save" }]
                                    }
                                }
                            })
                        } else if expr.contains("click()") {
                            json!({ "result": { "value": { "found": true, "tag": "button", "text": "Save" } } })
                        } else {
                            json!({ "result": { "value": { "url": "http://127.0.0.1:3000/", "title": "App Preview" } } })
                        }
                    }
                    "Page.captureScreenshot" => json!({ "data": screenshot_b64 }),
                    "Network.getResponseBody" => {
                        json!({ "body": r#"{"error":"boom"}"#, "base64Encoded": false })
                    }
                    _ => json!({}),
                };
                write_server_text_frame(
                    &mut s_write,
                    &json!({ "id": id, "result": result }).to_string(),
                )
                .await;
            }
        });

        let (ws_r, ws_w) = handshake_ws(client_stream, "127.0.0.1:9222", "/devtools/page/1")
            .await
            .expect("handshake");
        let cdp = CdpSession::from_ws(ws_r, ws_w);
        let manager = Arc::new(BrowserSessionManager::with_test_cdp(
            BrowserConfig::default(),
            cdp,
        ));
        let tab_tool = BrowserTabTool::new(Arc::clone(&manager));
        let net_tool = BrowserNetworkTool::new(Arc::clone(&manager));

        // 1. SSRF blocks metadata IP before any CDP call runs.
        let ssrf_blocked = tab_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "open", "url": "http://169.254.169.254/latest/meta-data" }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("returns outcome");
        assert_eq!(ssrf_blocked.status(), ToolCallResultStatus::Failed);
        assert_eq!(
            ssrf_blocked.diagnostic().expect("diag").code(),
            "browser_tab_ssrf_blocked"
        );

        let data_opened = tab_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({
                        "action": "open",
                        "url": "data:text/html;charset=utf-8,<html><body><h1>Merry Browser Test</h1><button id=\"btn\">Verify Button</button></body></html>"
                    }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("data document open returns");
        assert_eq!(data_opened.status(), ToolCallResultStatus::Succeeded);

        let data_script = tab_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "open", "url": "data:text/javascript,alert(1)" }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("script data URL returns");
        assert_eq!(data_script.status(), ToolCallResultStatus::Failed);
        assert_eq!(
            data_script.diagnostic().expect("diag").code(),
            "browser_tab_invalid_url"
        );

        // 2. Navigate to loopback works.
        let opened = tab_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "open", "url": "http://127.0.0.1:3000/" }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("open succeeds");
        assert_eq!(opened.status(), ToolCallResultStatus::Succeeded);

        // 3. Click element works.
        let clicked = tab_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "click", "selector": "#save" }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("click succeeds");
        assert_eq!(clicked.status(), ToolCallResultStatus::Succeeded);

        // 4. Snapshot captures DOM + attached normalized PNG screenshot!
        let snapshot = tab_tool
            .execute(
                call(BROWSER_TAB_TOOL, json!({ "action": "snapshot" })),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("snapshot succeeds");
        assert_eq!(snapshot.status(), ToolCallResultStatus::Succeeded);
        assert_eq!(snapshot.images().len(), 1);
        assert_eq!(snapshot.images()[0].label(), "browser-snapshot.png");
        assert_eq!(snapshot.images()[0].width(), 3);
        assert_eq!(snapshot.images()[0].height(), 2);

        // 5. Network list & details handle lenient CDP requestId seamlessly!
        let listed = net_tool
            .execute(
                call(
                    BROWSER_NETWORK_TOOL,
                    json!({ "action": "list", "failed_only": true }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("network list succeeds");
        assert_eq!(listed.status(), ToolCallResultStatus::Succeeded);
        let listed_json: Value = serde_json::from_str(listed.content().as_str()).expect("json");
        assert_eq!(listed_json["count"], 1);
        assert_eq!(listed_json["requests"][0]["request_id"], "62576.34");

        let details = net_tool
            .execute(
                call(
                    BROWSER_NETWORK_TOOL,
                    json!({ "action": "details", "request_id": 62576.34 }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("network details succeeds");
        assert_eq!(details.status(), ToolCallResultStatus::Succeeded);
        let details_json: Value = serde_json::from_str(details.content().as_str()).expect("json");
        assert_eq!(details_json["body"], r#"{"error":"boom"}"#);

        // 6. Close shuts down cleanly.
        let closed = tab_tool
            .execute(
                call(BROWSER_TAB_TOOL, json!({ "action": "close" })),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("close succeeds");
        assert_eq!(closed.status(), ToolCallResultStatus::Succeeded);
        server_task.abort();
    }

    #[tokio::test]
    async fn browser_tab_enforces_domain_admission_local_flag_and_cdp_redirect_checks() {
        use merry_core::CapabilityPolicy;
        use merry_runtime::{
            LivePolicyHandle, NetworkAccessPolicy, PermissionedAction, RequestedCapability,
            ToolExecutionError,
        };

        // 1. network = "deny" hard-denies external URLs before launching or prompting.
        let deny_policy =
            LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Deny, true));
        let deny_manager = Arc::new(BrowserSessionManager::new(
            BrowserConfig::default().with_live_network_policy(deny_policy),
        ));
        let deny_tool = BrowserTabTool::new(deny_manager);
        let denied = deny_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "open", "url": "https://docs.rs/" }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("deny returns failed outcome");
        assert_eq!(denied.status(), ToolCallResultStatus::Failed);
        assert_eq!(
            denied.diagnostic().expect("diag").code(),
            "browser_tab_network_denied"
        );

        // 2. browser.allow_local = false denies data:text/html and loopback.
        let no_local_policy =
            LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Allow, false));
        let no_local_manager = Arc::new(BrowserSessionManager::new(
            BrowserConfig::default().with_live_network_policy(no_local_policy),
        ));
        let no_local_tool = BrowserTabTool::new(no_local_manager);
        let data_denied = no_local_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "open", "url": "data:text/html,<h1>Hi</h1>" }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("data URL denied");
        assert_eq!(data_denied.status(), ToolCallResultStatus::Failed);
        assert_eq!(
            data_denied.diagnostic().expect("diag").code(),
            "browser_tab_network_denied"
        );
        let loopback_denied = no_local_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "open", "url": "http://127.0.0.1:3000/" }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("loopback denied");
        assert_eq!(loopback_denied.status(), ToolCallResultStatus::Failed);
        assert_eq!(
            loopback_denied.diagnostic().expect("diag").code(),
            "browser_tab_ssrf_blocked"
        );

        // 3. CDP Fetch interception + post-navigation redirect domain consistency check.
        let ask_policy =
            LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Ask, true));
        let mut current_nav_url = String::new();
        let (manager, seen_methods, server_task) = spawn_mock_cdp_session(
            ask_policy,
            Vec::new(),
            move |method, params| match method {
                "Page.navigate" => {
                    let url = params["url"].as_str().unwrap_or("").to_owned();
                    current_nav_url = url.clone();
                    let events = if url.contains("fetch-redirect") {
                        vec![
                            json!({
                                "method": "Fetch.requestPaused",
                                "params": {
                                    "requestId": "req-ssrf-1",
                                    "resourceType": "Fetch",
                                    "request": { "method": "GET", "url": "http://169.254.169.254/latest/meta-data" }
                                }
                            }),
                            json!({
                                "method": "Fetch.requestPaused",
                                "params": {
                                    "requestId": "req-nav-2",
                                    "resourceType": "Document",
                                    "request": { "method": "GET", "url": "https://evil.example.com/landing" }
                                }
                            }),
                        ]
                    } else {
                        Vec::new()
                    };
                    (events, json!({ "frameId": "main" }))
                }
                "Runtime.evaluate" => {
                    let expr = params["expression"].as_str().unwrap_or("");
                    let result = if expr == "document.readyState" {
                        json!({ "result": { "value": "complete" } })
                    } else if current_nav_url.contains("client-redirect") {
                        json!({
                            "result": {
                                "value": {
                                    "url": "https://redirected.example.com/secret",
                                    "title": "Redirected"
                                }
                            }
                        })
                    } else {
                        json!({
                            "result": {
                                "value": {
                                    "url": current_nav_url,
                                    "title": "Local"
                                }
                            }
                        })
                    };
                    (Vec::new(), result)
                }
                _ => (Vec::new(), json!({})),
            },
        )
        .await;
        let tab_tool = BrowserTabTool::new(Arc::clone(&manager));

        // Unapproved external domain triggers PermissionRequired before Page.navigate.
        let err = tab_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "open", "url": "https://docs.rs/tokio" }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect_err("external domain requires approval");
        match err {
            ToolExecutionError::PermissionRequired(requirement) => {
                assert_eq!(
                    requirement.action(),
                    &PermissionedAction::NetworkUrl {
                        tool: BROWSER_TAB_TOOL.to_owned(),
                        url: "https://docs.rs/tokio".to_owned(),
                        host: "docs.rs".to_owned(),
                    }
                );
                assert_eq!(
                    requirement.requested(),
                    &[RequestedCapability::NetworkDomain("docs.rs".to_owned())]
                );
            }
            other => panic!("expected PermissionRequired, got {other:?}"),
        }

        // Open loopback (auto-allowed by allow_local=true), then server emits
        // Fetch.requestPaused for SSRF + unapproved external document navigation!
        let fetch_err = tab_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "open", "url": "http://127.0.0.1:3000/fetch-redirect" }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect_err("CDP Fetch redirect to unapproved external domain must require approval");
        match fetch_err {
            ToolExecutionError::PermissionRequired(requirement) => {
                assert_eq!(
                    requirement.requested(),
                    &[RequestedCapability::NetworkDomain(
                        "evil.example.com".to_owned()
                    )]
                );
            }
            other => panic!("expected PermissionRequired for evil.example.com, got {other:?}"),
        }

        // Verify Fetch.failRequest was sent for both the SSRF request and the blocked navigation.
        let recorded = seen_methods.lock().expect("lock").clone();
        let failed_ids: Vec<&str> = recorded
            .iter()
            .filter(|(method, _)| method == "Fetch.failRequest")
            .filter_map(|(_, params)| params["requestId"].as_str())
            .collect();
        assert!(
            failed_ids.contains(&"req-ssrf-1"),
            "expected SSRF subresource to be failed via Fetch.failRequest; seen: {recorded:?}"
        );
        assert!(
            failed_ids.contains(&"req-nav-2"),
            "expected unapproved navigation to be failed via Fetch.failRequest; seen: {recorded:?}"
        );

        // Open loopback without Fetch events, but page lands on redirected.example.com:
        // post-navigation consistency check must clear to about:blank and request approval.
        let post_nav_err = tab_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "open", "url": "http://127.0.0.1:3000/client-redirect" }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect_err("post-navigation redirect to unapproved domain must require approval");
        match post_nav_err {
            ToolExecutionError::PermissionRequired(requirement) => {
                assert_eq!(
                    requirement.requested(),
                    &[RequestedCapability::NetworkDomain(
                        "redirected.example.com".to_owned()
                    )]
                );
            }
            other => {
                panic!("expected PermissionRequired for redirected.example.com, got {other:?}")
            }
        }
        let recorded_after = seen_methods.lock().expect("lock").clone();
        assert!(
            recorded_after.iter().any(|(method, params)| {
                method == "Page.navigate" && params["url"].as_str() == Some("about:blank")
            }),
            "post-navigation domain mismatch must clear the tab to about:blank"
        );

        server_task.abort();
    }

    async fn spawn_mock_cdp_session<F>(
        policy: merry_runtime::LivePolicyHandle,
        initial_events: Vec<Value>,
        mut on_rpc: F,
    ) -> (
        Arc<BrowserSessionManager>,
        Arc<std::sync::Mutex<Vec<(String, Value)>>>,
        tokio::task::JoinHandle<()>,
    )
    where
        F: FnMut(&str, &Value) -> (Vec<Value>, Value) + Send + 'static,
    {
        let (client_stream, server_stream) = tokio::io::duplex(32 * 1024);
        let seen_methods = Arc::new(std::sync::Mutex::new(Vec::<(String, Value)>::new()));
        let seen_methods_server = Arc::clone(&seen_methods);
        let server_task = tokio::spawn(async move {
            let (mut s_read, mut s_write) = tokio::io::split(server_stream);
            let mut buf = [0u8; 1024];
            let _ = s_read.read(&mut buf).await.expect("upgrade");
            s_write
                .write_all(
                    b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n",
                )
                .await
                .expect("101");

            for event in initial_events {
                write_server_text_frame(&mut s_write, &event.to_string()).await;
            }

            while let Some(raw) = read_masked_client_text(&mut s_read).await {
                let req: Value = serde_json::from_str(&raw).expect("valid rpc json");
                let id = req["id"].as_u64().expect("id");
                let method = req["method"].as_str().expect("method").to_owned();
                let params = req.get("params").cloned().unwrap_or(Value::Null);
                seen_methods_server
                    .lock()
                    .expect("lock")
                    .push((method.clone(), params.clone()));

                let (events, result) = on_rpc(&method, &params);
                for event in &events {
                    write_server_text_frame(&mut s_write, &event.to_string()).await;
                }
                for _ in 0..events.len() {
                    if let Some(reply_raw) = read_masked_client_text(&mut s_read).await {
                        let reply: Value = serde_json::from_str(&reply_raw).expect("valid rpc");
                        let reply_id = reply["id"].as_u64().expect("reply id");
                        let reply_method = reply["method"].as_str().expect("method").to_owned();
                        let reply_params = reply.get("params").cloned().unwrap_or(Value::Null);
                        seen_methods_server
                            .lock()
                            .expect("lock")
                            .push((reply_method, reply_params));
                        write_server_text_frame(
                            &mut s_write,
                            &json!({ "id": reply_id, "result": {} }).to_string(),
                        )
                        .await;
                    }
                }
                write_server_text_frame(
                    &mut s_write,
                    &json!({ "id": id, "result": result }).to_string(),
                )
                .await;
            }
        });

        let (ws_r, ws_w) = handshake_ws(client_stream, "127.0.0.1:9222", "/devtools/page/1")
            .await
            .expect("handshake");
        let manager = Arc::new(BrowserSessionManager::with_test_ws(
            BrowserConfig::default().with_live_network_policy(policy),
            ws_r,
            ws_w,
        ));
        (manager, seen_methods, server_task)
    }

    #[tokio::test]
    async fn browser_tab_snapshot_blocks_delayed_redirect_and_malformed_fetch_fails_closed() {
        use merry_core::CapabilityPolicy;
        use merry_runtime::{
            LivePolicyHandle, NetworkAccessPolicy, RequestedCapability, ToolExecutionError,
        };

        let ask_policy =
            LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Ask, true));
        // Push a malformed Fetch.requestPaused event (missing `request`) to verify
        // the reader fails it closed via Fetch.failRequest without stalling Chrome.
        let (manager, seen_methods, server_task) = spawn_mock_cdp_session(
            ask_policy,
            vec![json!({
                "method": "Fetch.requestPaused",
                "params": { "requestId": "req-malformed-1" }
            })],
            |method, params| {
                let result = match method {
                    "Runtime.evaluate"
                        if params["expression"]
                            .as_str()
                            .is_some_and(|e| e.contains("interactive_elements")) =>
                    {
                        json!({
                            "result": {
                                "value": {
                                    "url": "https://delayed.example.com/private",
                                    "title": "Delayed Redirect",
                                    "text": "Should not leak",
                                    "interactive_elements": []
                                }
                            }
                        })
                    }
                    "Runtime.evaluate" => json!({ "result": { "value": {} } }),
                    _ => json!({}),
                };
                (Vec::new(), result)
            },
        )
        .await;
        let tab_tool = BrowserTabTool::new(Arc::clone(&manager));

        let err = tab_tool
            .execute(
                call(BROWSER_TAB_TOOL, json!({ "action": "snapshot" })),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect_err("snapshot on unapproved redirected domain must require approval");
        match err {
            ToolExecutionError::PermissionRequired(requirement) => {
                assert_eq!(
                    requirement.requested(),
                    &[RequestedCapability::NetworkDomain(
                        "delayed.example.com".to_owned()
                    )]
                );
            }
            other => panic!("expected PermissionRequired, got {other:?}"),
        }

        let recorded = seen_methods.lock().expect("lock").clone();
        assert!(
            recorded.iter().any(|(method, params)| {
                method == "Fetch.failRequest"
                    && params["requestId"].as_str() == Some("req-malformed-1")
            }),
            "malformed Fetch.requestPaused must still fail closed via Fetch.failRequest; seen: {recorded:?}"
        );
        assert!(
            !recorded
                .iter()
                .any(|(method, _)| method == "Page.captureScreenshot"),
            "snapshot must block before capturing screenshot of an unapproved domain"
        );
        assert!(
            recorded.iter().any(|(method, params)| {
                method == "Page.navigate" && params["url"].as_str() == Some("about:blank")
            }),
            "snapshot domain mismatch must clear the tab to about:blank"
        );

        server_task.abort();
    }

    #[test]
    fn cdp_fetch_policy_respects_active_authorized_host_and_deny_floor() {
        use super::cdp::{BlockedNavigationReason, CdpNetworkGuard, evaluate_cdp_fetch_policy};
        use merry_core::CapabilityPolicy;
        use merry_runtime::{LivePolicyBaseline, LivePolicyHandle, NetworkAccessPolicy};
        use std::sync::Mutex as StdMutex;

        let policy =
            LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Ask, true));
        // Intentionally store unnormalized host to verify normalization at evaluation time.
        let active_host = Arc::new(StdMutex::new(Some("DOCS.EXAMPLE.COM.".to_owned())));
        let guard = CdpNetworkGuard {
            allow_local: true,
            live_network_policy: Some(policy.clone()),
            once_domains: Arc::new(StdMutex::new(Vec::new())),
            active_authorized_host: Arc::clone(&active_host),
        };

        assert_eq!(
            evaluate_cdp_fetch_policy("docs.example.com", true, &guard),
            None
        );
        assert_eq!(
            evaluate_cdp_fetch_policy("evil.example.com", true, &guard),
            Some(BlockedNavigationReason::RequireReview {
                host: "evil.example.com".to_owned(),
            })
        );
        policy.replace_baseline(LivePolicyBaseline::new(
            false,
            None,
            Vec::new(),
            NetworkAccessPolicy::new(CapabilityPolicy::Deny, true),
        ));
        assert!(matches!(
            evaluate_cdp_fetch_policy("docs.example.com", true, &guard),
            Some(BlockedNavigationReason::NetworkDenied(_))
        ));
        assert!(matches!(
            evaluate_cdp_fetch_policy("docs.example.com", false, &guard),
            Some(BlockedNavigationReason::NetworkDenied(_))
        ));
        policy.replace_baseline(LivePolicyBaseline::new(
            false,
            None,
            Vec::new(),
            NetworkAccessPolicy::new(CapabilityPolicy::Ask, true),
        ));
        *active_host.lock().expect("lock") = None;
        assert_eq!(
            evaluate_cdp_fetch_policy("docs.example.com", true, &guard),
            Some(BlockedNavigationReason::RequireReview {
                host: "docs.example.com".to_owned(),
            })
        );
    }

    #[tokio::test]
    async fn browser_tab_once_active_host_enforces_navigate_reset_and_deny() {
        use merry_core::CapabilityPolicy;
        use merry_runtime::{
            LivePolicyBaseline, LivePolicyHandle, NetworkAccessPolicy, RequestedCapability,
            ToolExecutionError,
        };

        let policy =
            LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Ask, true));
        let (manager, seen_methods, server_task) =
            spawn_mock_cdp_session(policy.clone(), Vec::new(), |method, params| match method {
                "Page.navigate"
                    if params["url"]
                        .as_str()
                        .is_some_and(|u| u.contains("redirect-back")) =>
                {
                    (
                        vec![json!({
                            "method": "Fetch.requestPaused",
                            "params": {
                                "requestId": "req-back-1",
                                "resourceType": "Document",
                                "request": { "method": "GET", "url": "https://docs.example.com/back" }
                            }
                        })],
                        json!({ "frameId": "main" }),
                    )
                }
                "Runtime.evaluate" => (
                    Vec::new(),
                    json!({
                        "result": {
                            "value": {
                                "url": "https://docs.example.com/guide",
                                "title": "Docs",
                                "text": "Hello docs",
                                "interactive_elements": []
                            }
                        }
                    }),
                ),
                _ => (Vec::new(), json!({})),
            })
            .await;
        manager.set_active_authorized_host(Some("DOCS.EXAMPLE.COM".to_owned()));
        let tab_tool = BrowserTabTool::new(Arc::clone(&manager));

        // 1. Snapshot on the active Once-authorized host succeeds without re-prompting.
        let snapshot = tab_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "snapshot", "include_screenshot": false }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("same-host snapshot on active authorized host must succeed");
        assert_eq!(snapshot.status(), ToolCallResultStatus::Succeeded);

        // 2. Explicit new navigate to the same host without a fresh Once grant requires review
        //    and leaves the current open tab's active_authorized_host intact on pre-flight rejection.
        let nav_err = tab_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "navigate", "url": "https://docs.example.com/other" }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect_err("explicit navigate must not bypass approval via active_authorized_host");
        match nav_err {
            ToolExecutionError::PermissionRequired(requirement) => {
                assert_eq!(
                    requirement.requested(),
                    &[RequestedCapability::NetworkDomain(
                        "docs.example.com".to_owned()
                    )]
                );
            }
            other => panic!("expected PermissionRequired, got {other:?}"),
        }
        assert_eq!(
            manager.active_authorized_host().as_deref(),
            Some("docs.example.com")
        );

        // 3. Starting a new explicit navigation clears active_authorized_host before Page.navigate,
        //    so a CDP Fetch redirect back to the previous host is blocked via Fetch.failRequest.
        let redirect_err = tab_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "open", "url": "http://127.0.0.1:3000/redirect-back" }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect_err(
                "redirect back to prior active host during new navigate must require review",
            );
        match redirect_err {
            ToolExecutionError::PermissionRequired(requirement) => {
                assert_eq!(
                    requirement.requested(),
                    &[RequestedCapability::NetworkDomain(
                        "docs.example.com".to_owned()
                    )]
                );
            }
            other => panic!("expected PermissionRequired, got {other:?}"),
        }
        assert!(
            seen_methods.lock().expect("lock").iter().any(|(m, p)| {
                m == "Fetch.failRequest" && p["requestId"].as_str() == Some("req-back-1")
            }),
            "stale active_authorized_host must not bypass CDP Fetch guard during new navigation"
        );

        // 4. Hot-switching policy to Deny overrides active_authorized_host and clears tab.
        manager.set_active_authorized_host(Some("docs.example.com".to_owned()));
        policy.replace_baseline(LivePolicyBaseline::new(
            false,
            None,
            Vec::new(),
            NetworkAccessPolicy::new(CapabilityPolicy::Deny, true),
        ));
        let denied = tab_tool
            .execute(
                call(
                    BROWSER_TAB_TOOL,
                    json!({ "action": "snapshot", "include_screenshot": false }),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("deny returns failed outcome");
        assert_eq!(denied.status(), ToolCallResultStatus::Failed);
        assert_eq!(manager.active_authorized_host(), None);
        assert!(
            seen_methods
                .lock()
                .expect("lock")
                .iter()
                .any(|(m, p)| { m == "Page.navigate" && p["url"].as_str() == Some("about:blank") }),
            "denied snapshot must clear tab to about:blank"
        );

        server_task.abort();
    }
}