File size: 45,422 Bytes
1269259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPF Smart Gateway - Mesh Network Transport (Layer 3)
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// P2P QUIC mesh via iroh. Ed25519 identity = iroh EndpointId.
// Inbound: peer connects → JSON-RPC over QUIC stream → dispatch::call(Source::Mesh)
// Outbound: spf_mesh_call tool → QUIC stream → peer's /spf/mesh/1 ALPN
//
// Rev 2: Persistent bidirectional streams with framing protocol.
//        Legacy detection: first byte '{' = old JSON-RPC, 0x01-0x08 = new framed.
//        call_peer() UNCHANGED for backward compat.
//        NEW: call_peer_stream() for persistent framed connections.
//        NEW: stream_router() dispatches by StreamType.
//
// Discovery: mDNS (LAN), Pkarr DHT (internet), groups/*.keys (explicit trust)
// Trust: Only peers in groups/*.keys are accepted. Default-deny.
//
// Depends on: dispatch.rs (Layer 0), identity.rs, config.rs (MeshConfig, AgentRole), framing.rs

use crate::config::{AgentRole, MeshConfig};
use crate::framing::{self, Frame, StreamType, FRAME_HEADER_SIZE};
use crate::http::ServerState;
use ed25519_dalek::SigningKey;
use iroh::{Endpoint, EndpointAddr, PublicKey, SecretKey};
use iroh::address_lookup::MdnsAddressLookup;
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};

/// ALPN bytes for SPF mesh protocol
fn spf_alpn(config: &MeshConfig) -> Vec<u8> {
    config.alpn.as_bytes().to_vec()
}

/// Convert Ed25519 SigningKey to iroh SecretKey.
/// Both are Curve25519 — direct byte mapping.
fn to_iroh_key(signing_key: &SigningKey) -> SecretKey {
    SecretKey::from_bytes(&signing_key.to_bytes())
}

/// Check if a connecting peer is in our trusted keys.
fn is_trusted(peer_id: &PublicKey, trusted_keys: &HashSet<String>) -> bool {
    let peer_hex = hex::encode(peer_id.as_bytes());
    trusted_keys.contains(&peer_hex)
}

/// Build a configured iroh endpoint builder from mesh config.
/// Single source of truth — used by both preferred-port and fallback paths.
fn build_mesh_builder(signing_key: &SigningKey, config: &MeshConfig, alpn: &[u8]) -> iroh::endpoint::Builder {
    let builder = Endpoint::builder()
        .secret_key(to_iroh_key(signing_key))
        .alpns(vec![alpn.to_vec()]);
    match config.discovery.as_str() {
        "auto" => builder,
        "local" => builder.clear_address_lookup()
            .address_lookup(MdnsAddressLookup::builder()),
        "manual" | _ => builder.clear_address_lookup(),
    }
}

/// Scan for an available UDP port starting at preferred.
/// Tries preferred..=preferred+1000. Returns first port that binds.
/// Mirrors HTTP's find_available_port() but for QUIC (UDP).
fn find_available_udp_port(bind: &str, preferred: u16) -> u16 {
    let range_end = preferred.saturating_add(1000);
    for port in preferred..=range_end {
        let addr = format!("{}:{}", bind, port);
        match std::net::UdpSocket::bind(&addr) {
            Ok(socket) => {
                drop(socket);
                if port != preferred {
                    eprintln!(
                        "[SPF-MESH] Port {} in use — auto-selected port {}",
                        preferred, port
                    );
                }
                return port;
            }
            Err(_) => continue,
        }
    }
    eprintln!(
        "[SPF-MESH] WARNING: No UDP port available in {}..={}, falling back to {}",
        preferred, range_end, preferred
    );
    preferred
}

// ============================================================================
// SYNC/ASYNC BRIDGE — channel for outbound mesh calls
// ============================================================================

/// Request sent from sync MCP world to async mesh world.
#[derive(Clone)]
pub struct MeshRequest {
    pub peer_key: String,
    pub addrs: Vec<String>,
    pub tool: String,
    pub args: Value,
    pub reply: std::sync::mpsc::Sender<Result<Value, String>>,
}

/// Create the sync channel for mesh request bridging.
/// Returns (sender for ServerState, receiver for mesh thread).
pub fn create_mesh_channel() -> (
    std::sync::mpsc::Sender<MeshRequest>,
    std::sync::mpsc::Receiver<MeshRequest>,
) {
    std::sync::mpsc::channel()
}

// ============================================================================
// P2: HANDSHAKE HELPERS — read/write role exchange on persistent streams
// ============================================================================

/// Read a handshake frame from a RecvStream. Returns the peer's role, or None
/// if the stream closes before we get a valid handshake.
async fn read_handshake_from_stream(
    recv: &mut iroh::endpoint::RecvStream,
) -> Result<Option<AgentRole>, String> {
    let mut buf = Vec::with_capacity(4096);
    let mut attempts = 0;
    while attempts < 10 {
        // Try parse from buffer first
        if let Ok(Some((frame, consumed))) = framing::parse_frame(&buf) {
            if frame.stream_type == StreamType::Control {
                if let Ok(text) = frame.payload_str() {
                    if let Some(role_str) = framing::control::parse_role(text) {
                        return Ok(parse_agent_role(&role_str));
                    }
                }
            }
            buf.drain(..consumed);
            continue;
        }

        let mut chunk = [0u8; 4096];
        match tokio::time::timeout(
            std::time::Duration::from_secs(5),
            recv.read(&mut chunk),
        ).await {
            Ok(Ok(Some(n))) => buf.extend_from_slice(&chunk[..n]),
            Ok(Ok(None)) => return Ok(None),  // Stream closed
            Ok(Err(e)) => return Err(format!("Read error: {}", e)),
            Err(_) => break,  // Timeout
        }
        attempts += 1;
    }
    Ok(None)
}

/// Parse a role string into AgentRole with fallback.
fn parse_agent_role(s: &str) -> Option<AgentRole> {
    match s.to_lowercase().as_str() {
        "orchestrator" | "coordinator" | "agent" | "director" => Some(AgentRole::Orchestrator),
        "thinker" | "problem-solver" => Some(AgentRole::Thinker),
        "worker" | "executor" => Some(AgentRole::Worker),
        _ => None,
    }
}

// ============================================================================
// P0-1: PEER CHANNEL — Persistent Duplex Stream
// ============================================================================

/// One persistent QUIC bi-stream per peer.
/// Stays open from boot to shutdown. Reconnects on drop.
pub struct PeerChannel {
    pub peer_key: String,
    pub role: AgentRole,
    pub send: iroh::endpoint::SendStream,
    pub recv: iroh::endpoint::RecvStream,
    _conn: iroh::endpoint::Connection,
    pub last_active: Instant,
    pub active: bool,
}

// ============================================================================
// P0-2: PEER CHANNEL MANAGER
// ============================================================================

/// Manages all persistent duplex channels to mesh peers.
pub struct PeerChannelManager {
    channels: HashMap<String, PeerChannel>,
    endpoint: Endpoint,
    alpn: Vec<u8>,
    peer_addrs: HashMap<String, Vec<String>>,
}

impl PeerChannelManager {
    /// Create a new empty channel manager.
    pub fn new(endpoint: Endpoint, alpn: Vec<u8>) -> Self {
        Self {
            channels: HashMap::new(),
            endpoint,
            alpn,
            peer_addrs: HashMap::new(),
        }
    }

    /// Register peer addresses for reconnect.
    pub fn register_peer_addrs(&mut self, peer_key: &str, addrs: Vec<String>) {
        self.peer_addrs.insert(peer_key.to_string(), addrs);
    }

    /// Connect to a peer — opens persistent duplex bi-stream, exchanges handshake.
    pub async fn connect(
        &mut self,
        peer_key: &str,
        addrs: &[String],
        _our_role: AgentRole,
        handshake_frame: &Frame,
    ) -> Result<(), String> {
        self.disconnect(peer_key);

        let (mut send_iroh, mut recv_iroh, conn_iroh) =
            call_peer_stream(&self.endpoint, peer_key, addrs, &self.alpn).await?;

        // Send our handshake
        send_iroh
            .write_all(&handshake_frame.to_bytes())
            .await
            .map_err(|e| format!("Write failed: {}", e))?;

        // Read their handshake reply
        let their_role = match read_handshake_from_stream(&mut recv_iroh).await {
            Ok(Some(role)) => {
                eprintln!("[SPF-MESH] Handshake: {} | role={}", &peer_key[..16], role);
                role
            }
            Ok(None) => {
                eprintln!("[SPF-MESH] No handshake from {} — assuming orchestrator", &peer_key[..16]);
                AgentRole::Orchestrator
            }
            Err(e) => {
                eprintln!("[SPF-MESH] Handshake read error for {}: {}", &peer_key[..16], e);
                AgentRole::Orchestrator
            }
        };

        self.channels.insert(
            peer_key.to_string(),
            PeerChannel {
                peer_key: peer_key.to_string(),
                role: their_role,
                send: send_iroh,
                recv: recv_iroh,
                _conn: conn_iroh,
                last_active: Instant::now(),
                active: true,
            },
        );
        Ok(())
    }

    /// Close and remove a peer channel.
    pub fn disconnect(&mut self, peer_key: &str) {
        if let Some(_ch) = self.channels.remove(peer_key) {
            eprintln!("[SPF-MESH] Channel closed for {}", &peer_key[..16]);
        }
    }

    /// Send a frame to a peer via its persistent channel.
    pub async fn send_frame(&mut self, peer_key: &str, frame: &Frame) -> Result<(), String> {
        let ch = self
            .channels
            .get_mut(peer_key)
            .ok_or_else(|| format!("No channel for peer {}", &peer_key[..16]))?;

        if !ch.active {
            return Err(format!("Channel inactive for {}", &peer_key[..16]));
        }

        ch.send
            .write_all(&frame.to_bytes())
            .await
            .map_err(|e| {
                ch.active = false;
                eprintln!("[SPF-MESH] Send failed for {}: {}", &peer_key[..16], e);
                format!("Send error: {}", e)
            })?;

        ch.last_active = Instant::now();
        Ok(())
    }

    /// Read the next frame from a peer's persistent channel.
    /// Returns None if stream closed by peer.
    pub async fn read_frame(
        &mut self,
        peer_key: &str,
    ) -> Result<Option<Frame>, String> {
        let ch = self
            .channels
            .get_mut(peer_key)
            .ok_or_else(|| format!("No channel for peer {}", &peer_key[..16]))?;

        if !ch.active {
            return Err(format!("Channel inactive for {}", &peer_key[..16]));
        }

        // Read into buffer until we have a complete frame
        let mut buf = Vec::with_capacity(8192);
        loop {
            let mut chunk = vec![0u8; 8192];
            match ch.recv.read(&mut chunk).await {
                Ok(Some(n)) => {
                    buf.extend_from_slice(&chunk[..n]);
                }
                Ok(None) => {
                    ch.active = false;
                    eprintln!("[SPF-MESH] Stream closed by peer {}", &peer_key[..16]);
                    return Ok(None);
                }
                Err(e) => {
                    ch.active = false;
                    return Err(format!("Read error: {}", e));
                }
            }

            match framing::parse_frame(&buf) {
                Ok(Some((frame, consumed))) => {
                    buf.drain(..consumed);
                    ch.last_active = Instant::now();
                    return Ok(Some(frame));
                }
                Ok(None) => continue,
                Err(e) => return Err(format!("Parse error: {}", e)),
            }
        }
    }

    /// Get a mutable reference to a peer channel for manual stream operations.
    pub fn get_channel(&mut self, peer_key: &str) -> Option<&mut PeerChannel> {
        self.channels.get_mut(peer_key)
    }

    /// Get all active peer keys.
    pub fn active_peers(&self) -> Vec<String> {
        self.channels
            .iter()
            .filter(|(_, ch)| ch.active)
            .map(|(k, _)| k.clone())
            .collect()
    }

    /// Get the role of a connected peer.
    pub fn peer_role(&self, peer_key: &str) -> Option<AgentRole> {
        self.channels.get(peer_key).map(|ch| ch.role)
    }

    /// Send heartbeat to all active peers. Returns list of peers that failed.
    pub async fn heartbeat_all(&mut self) -> Vec<String> {
        let mut failed = Vec::new();
        let peers: Vec<String> = self.active_peers();

        for peer_key in &peers {
            let hb = Frame::control(framing::control::HEARTBEAT);
            if let Err(e) = self.send_frame(peer_key, &hb).await {
                eprintln!("[SPF-MESH] Heartbeat failed for {}: {}", &peer_key[..16], e);
                failed.push(peer_key.clone());
            }
        }
        failed
    }

    /// Reap inactive/dead channels. Returns list of removed peer keys.
    pub fn reap_dead(&mut self, idle_timeout: Duration) -> Vec<String> {
        let mut removed = Vec::new();
        let to_remove: Vec<String> = self
            .channels
            .iter()
            .filter(|(_, ch)| !ch.active
                || (ch.active && ch.last_active.elapsed() > idle_timeout))
            .map(|(k, _)| k.clone())
            .collect();

        for key in &to_remove {
            self.channels.remove(key);
            removed.push(key.clone());
            eprintln!("[SPF-MESH] Reaped channel for {}", &key[..16]);
        }
        removed
    }

    /// Check if a specific peer has a channel.
    pub fn has_channel(&self, peer_key: &str) -> bool {
        self.channels.contains_key(peer_key)
    }

    /// Get count of all channels (active + inactive).
    pub fn channel_count(&self) -> usize {
        self.channels.len()
    }
}

// ============================================================================
// MESH STARTUP + INBOUND HANDLER
// ============================================================================

/// Main mesh loop — runs in dedicated thread with tokio runtime.
/// Accepts inbound QUIC connections from trusted peers.
/// Routes JSON-RPC requests through dispatch::call(Source::Mesh).
pub async fn run(
    state: Arc<ServerState>,
    signing_key: SigningKey,
    config: MeshConfig,
    mesh_rx: std::sync::mpsc::Receiver<MeshRequest>,
) {
    let alpn = spf_alpn(&config);

    // Bind iroh endpoint — pre-scan preferred port, fallback to random on BindError
    let endpoint = if config.port > 0 {
        let port = find_available_udp_port("0.0.0.0", config.port);
        let builder = build_mesh_builder(&signing_key, &config, &alpn);
        let preferred = match builder.clear_ip_transports().bind_addr(format!("0.0.0.0:{}", port)) {
            Ok(b) => b.bind().await,
            Err(e) => {
                eprintln!("[SPF-MESH] Invalid bind address for port {}: {}", port, e);
                return;
            }
        };
        match preferred {
            Ok(ep) => ep,
            Err(e) => {
                eprintln!("[SPF-MESH] Preferred port {} failed ({}), falling back to random", port, e);
                let fallback = build_mesh_builder(&signing_key, &config, &alpn);
                match fallback.bind().await {
                    Ok(ep) => ep,
                    Err(e2) => {
                        eprintln!("[SPF-MESH] Fallback bind also failed: {}", e2);
                        return;
                    }
                }
            }
        }
    } else {
        let builder = build_mesh_builder(&signing_key, &config, &alpn);
        match builder.bind().await {
            Ok(ep) => ep,
            Err(e) => {
                eprintln!("[SPF-MESH] Failed to bind iroh endpoint: {}", e);
                return;
            }
        }
    };

    // Wait until endpoint has relay/public connectivity before accepting
    endpoint.online().await;

    // Source of truth — query what iroh actually bound
    let bound = endpoint.bound_sockets();
    let endpoint_id = endpoint.id();
    let port_info = if bound.is_empty() {
        "no sockets".to_string()
    } else {
        bound.iter().map(|s| s.to_string()).collect::<Vec<_>>().join(", ")
    };
    eprintln!("[SPF-MESH] Online | EndpointID: {} | QUIC: {}",
             hex::encode(endpoint_id.as_bytes()), port_info);
    eprintln!("[SPF-MESH] Role: {} | Team: {} | Discovery: {}",
             config.role, config.team, config.discovery);

    // DS-2: Store endpoint in ServerState for direct MCP duplex access
    {
        let mut ep_slot = state.endpoint.lock().unwrap();
        *ep_slot = Some(endpoint.clone());
    }
    {
        let mut rt_slot = state.tokio_handle.lock().unwrap();
        *rt_slot = Some(tokio::runtime::Handle::current());
    }
    eprintln!("[SPF-MESH] Endpoint stored in ServerState for duplex stream access");

    // Android: notify iroh on EVERY network interface change (WiFi ↔ cellular)
    // network_change() returns after ONE event — must loop to catch all switches
    let nc_endpoint = endpoint.clone();
    tokio::spawn(async move {
        loop {
            nc_endpoint.network_change().await;
        }
    });

    // ── P4: Role-based bootstrap paths ──
    let self_role = config.role;
    let self_key = hex::encode(state.signing_key.verifying_key().to_bytes());

    // P4-2: Orchestrator path — build OrchestratorState, store in ServerState
    if self_role == AgentRole::Orchestrator {
        let orch = crate::orchestrator::OrchestratorState::new(self_role, self_key.clone());
        *state.orchestrator_state.lock().unwrap() =
            Some(Arc::new(std::sync::Mutex::new(orch)));
        eprintln!("[SPF-MESH] OrchestratorState initialised — projects={} my_pub={}",
            0, &self_key[..16]);
    }

    // Build handshake frame for bootstrapped channels
    let boot_hs = Frame::control(&framing::control::build_handshake(
        &self_role.to_string(),
        &config.name,
        env!("CARGO_PKG_VERSION"),
    ));

    // Spawn outbound request handler (sync channel → persistent duplex channels)
    let outbound_ep = endpoint.clone();
    let outbound_alpn = alpn.clone();
    let outbound_peers = state.peers.clone();
    let outbound_trusted = state.trusted_keys.clone();
    let outbound_role = self_role;
    let outbound_hs = boot_hs.clone();
    let outbound_state = state.clone();
    let rt_handle = tokio::runtime::Handle::current();
    std::thread::spawn(move || {
        let mut mgr = PeerChannelManager::new(outbound_ep.clone(), outbound_alpn.clone());

        // Register all known peer addresses from trusted groups
        for (key, info) in &outbound_peers {
            if outbound_trusted.contains(key.as_str()) {
                mgr.register_peer_addrs(key, info.addr.clone());
            }
        }

        // ── P4: Bootstrap persistent channels to trusted peers ──
        // Orchestrator connects to all. Worker/thinker connects to orchestrator first.
        let _ep = outbound_ep.clone();
        let peer_addrs_for_boot: Vec<(String, Vec<String>)> = outbound_peers
            .iter()
            .filter(|(k, _)| outbound_trusted.contains(k.as_str()))
            .map(|(k, v)| (k.clone(), v.addr.clone()))
            .collect();

        let boot_mgr = rt_handle.block_on(async {
            let mut m = mgr;
            for (pk, addrs) in &peer_addrs_for_boot {
                // For non-orchestrator modes, only boot-connect to peers known as orchestrators
                // For orchestrator, connect to all (classify by handshake response later)
                if outbound_role == AgentRole::Orchestrator {
                    eprintln!("[SPF-MESH] Boot-connect (orchestrator): {}", &pk[..16]);
                    let _ = m.connect(pk, addrs, AgentRole::Orchestrator, &outbound_hs).await;
                } else {
                    // Worker/thinker: try connecting, role comes from remote handshake
                    eprintln!("[SPF-MESH] Boot-connect ({} mode): {}", outbound_role, &pk[..16]);
                    // Default role will be updated from handshake response
                    let _ = m.connect(pk, addrs, AgentRole::Orchestrator, &outbound_hs).await;
                }
            }
            m
        });
        // Move the manager back — need to rebind since block_on took ownership
        // Re-read peers after the above to get role info
        let mut mgr = boot_mgr;

        // Update ServerState tracked_peers with boot-connected peers
        for (pk, ch) in mgr.channels.iter() {
            outbound_state.tracked_peers.lock().unwrap().insert(
                pk.clone(),
                crate::http::MeshPeerStatus {
                    role: ch.role,
                    name: "".to_string(),
                    last_seen: ch.last_active,
                },
            );
        }
        // Update orchestrator state workers/thinkers maps
        if outbound_role == AgentRole::Orchestrator {
            if let Some(ref orch_arc) = *outbound_state.orchestrator_state.lock().unwrap() {
                let mut orch = orch_arc.lock().unwrap();
                for (pk, ch) in mgr.channels.iter() {
                    match ch.role {
                        AgentRole::Worker => orch.assign_worker(pk, "boot"),
                        AgentRole::Thinker => orch.assign_thinker(pk, "boot"),
                        _ => {}
                    }
                }
            }
        }

        drop(boot_hs); // consumed

        while let Ok(request) = mesh_rx.recv() {
            let ep = outbound_ep.clone();
            let a = outbound_alpn.clone();

            // Try persistent channel first
            let result = if mgr.has_channel(&request.peer_key) {
                let ch_active = mgr.peer_role(&request.peer_key).is_some();
                if ch_active {
                    // Use persistent channel
                    let req = request.clone();
                    rt_handle.block_on(async {
                        handle_framed_outbound(&mut mgr, &req).await
                    })
                } else {
                    // Channel dropped, reconnect
                    mgr.disconnect(&request.peer_key);
                    let req = request.clone();
                    #[allow(deprecated)]
                    rt_handle.block_on(async {
                        call_peer(&ep, &req.peer_key, &req.addrs, &a, &req.tool, &req.args).await
                    })
                }
            } else {
                // No channel yet — use call_peer (will migrate later after bootstrap)
                let req = request.clone();
                #[allow(deprecated)]
                rt_handle.block_on(async {
                    call_peer(&ep, &req.peer_key, &req.addrs, &a, &req.tool, &req.args).await
                })
            };
            request.reply.send(result).ok();
        }
    });

    // Accept inbound connections
    while let Some(incoming) = endpoint.accept().await {
        let state = Arc::clone(&state);

        tokio::spawn(async move {
            let connection = match incoming.await {
                Ok(conn) => conn,
                Err(e) => {
                    eprintln!("[SPF-MESH] Connection failed: {}", e);
                    return;
                }
            };

            let peer_id = connection.remote_id();

            // DEFAULT-DENY: reject untrusted peers
            if !is_trusted(&peer_id, &state.trusted_keys) {
                eprintln!("[SPF-MESH] REJECTED untrusted peer: {}",
                         hex::encode(peer_id.as_bytes()));
                connection.close(1u32.into(), b"untrusted");
                return;
            }

            let peer_hex = hex::encode(peer_id.as_bytes());
            eprintln!("[SPF-MESH] Accepted peer: {}", &peer_hex[..16]);

            // Handle streams from this peer
            handle_peer(connection, &state, &peer_hex).await;
        });
    }
}

// ============================================================================
// INBOUND STREAM HANDLER (Rev 2: protocol detection + persistent streams)
// ============================================================================

/// Handle requests from a connected mesh peer.
///
/// Protocol detection on each new stream:
/// - First byte '{' (0x7B): Legacy one-shot JSON-RPC (existing behavior, unchanged)
/// - First byte 0x01-0x08: New framed protocol (persistent bidirectional stream)
///
/// Legacy mode: read_to_end → process → write_all → finish (one request per stream)
/// Framed mode: loop { read_frame → route_by_type → write_frame } (many per stream)
async fn handle_peer(
    connection: iroh::endpoint::Connection,
    state: &Arc<ServerState>,
    peer_key: &str,
) {
    loop {
        // Accept bidirectional streams
        let (mut send, mut recv) = match connection.accept_bi().await {
            Ok(streams) => streams,
            Err(_) => break,
        };

        // Read first byte to detect protocol
        let mut first_byte = [0u8; 1];
        let first = match recv.read(&mut first_byte).await {
            Ok(Some(1)) => first_byte[0],
            Ok(Some(0)) | Ok(None) => continue, // Empty stream, skip
            Ok(Some(_)) => first_byte[0],
            Err(_) => break,
        };

        let protocol = framing::detect_protocol(first);

        match protocol {
            framing::Protocol::LegacyJsonRpc => {
                // === LEGACY MODE (unchanged behavior) ===
                // First byte was '{', read rest of JSON-RPC message
                let mut data = vec![first];
                match recv.read_to_end(10_485_760).await {
                    Ok(rest) => data.extend_from_slice(&rest),
                    Err(_) => break,
                };

                let response = handle_legacy_rpc(&data, state, peer_key);
                send.write_all(serde_json::to_string(&response).unwrap_or_default().as_bytes()).await.ok();
                send.finish().ok();
            }

            framing::Protocol::Framed(stream_type) => {
                // === FRAMED MODE (new persistent streams) ===
                // First byte was stream type. Read rest of first frame header.
                let mut header_rest = [0u8; 4]; // 4 bytes length
                if recv.read_exact(&mut header_rest).await.is_err() {
                    continue;
                }
                let first_len = u32::from_be_bytes(header_rest);
                if first_len > framing::MAX_FRAME_SIZE {
                    continue; // Oversized frame, skip
                }

                // Read first frame payload
                let mut first_payload = vec![0u8; first_len as usize];
                if first_len > 0 {
                    if recv.read_exact(&mut first_payload).await.is_err() {
                        continue;
                    }
                }

                let first_frame = Frame::new(stream_type, first_payload);

                // Spawn persistent stream handler
                let state = Arc::clone(state);
                let peer_key = peer_key.to_string();
                tokio::spawn(async move {
                    handle_framed_stream(send, recv, first_frame, &state, &peer_key).await;
                });
            }

            framing::Protocol::Unknown(byte) => {
                eprintln!("[SPF-MESH] Unknown protocol byte 0x{:02x} from {}", byte, &peer_key[..16]);
                send.finish().ok();
            }
        }
    }
}

/// Handle a legacy one-shot JSON-RPC message (unchanged from original)
fn handle_legacy_rpc(data: &[u8], state: &Arc<ServerState>, peer_key: &str) -> Value {
    let msg: Value = match serde_json::from_slice(data) {
        Ok(v) => v,
        Err(_) => {
            return json!({"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error"}});
        }
    };

    let method = msg["method"].as_str().unwrap_or("");
    let id = &msg["id"];
    let params = &msg["params"];

    match method {
        "tools/call" => {
            let name = params["name"].as_str().unwrap_or("");
            let args = params.get("arguments").cloned().unwrap_or(json!({}));

            // Route through Unified Dispatch — same gate as stdio/HTTP
            let resp = tokio::task::block_in_place(|| {
                crate::dispatch::call(
                    state,
                    crate::dispatch::Source::Mesh { peer_key: peer_key.to_string() },
                    name,
                    &args,
                )
            });

            json!({
                "jsonrpc": "2.0",
                "id": id,
                "result": { "content": [resp.result] }
            })
        }

        "mesh/info" => {
            let mesh_json = crate::paths::spf_root().join("LIVE/CONFIG/mesh.json");
            let mesh_cfg = crate::config::MeshConfig::load(&mesh_json).unwrap_or_default();
            json!({
                "jsonrpc": "2.0",
                "id": id,
                "result": {
                    "version": env!("CARGO_PKG_VERSION"),
                    "peer_id": state.pub_key_hex,
                    "role": mesh_cfg.role,
                    "team": mesh_cfg.team,
                    "name": mesh_cfg.name,
                }
            })
        }

        _ => {
            json!({
                "jsonrpc": "2.0",
                "id": id,
                "error": {"code": -32601, "message": format!("Unknown method: {}", method)}
            })
        }
    }
}

// ============================================================================
// FRAMED STREAM HANDLER (Block G + H: persistent bidirectional streams)
// ============================================================================

/// Handle a persistent framed stream. Routes frames by StreamType.
/// Stream stays open until peer closes or error occurs.
async fn handle_framed_stream(
    mut send: iroh::endpoint::SendStream,
    mut recv: iroh::endpoint::RecvStream,
    first_frame: Frame,
    state: &Arc<ServerState>,
    peer_key: &str,
) {
    // ── P2: Handshake exchange ──
    // If first frame is a Control handshake, respond with our handshake
    // and log the peer's role. Then continue normal routing.
    let mut handshake_done = false;
    if first_frame.stream_type == StreamType::Control {
        if let Ok(text) = first_frame.payload_str() {
            if let Some(their_role) = framing::control::parse_role(text) {
                let their_name = framing::control::parse_name(text).unwrap_or_else(|| "unknown".to_string());
                eprintln!("[SPF-MESH] Inbound handshake: {} | role={} name={}", &peer_key[..16], their_role, their_name);
                // Record in ServerState tracked_peers
                state.tracked_peers.lock().unwrap().insert(
                    peer_key.to_string(),
                    crate::http::MeshPeerStatus {
                        role: parse_agent_role(&their_role).unwrap_or(AgentRole::Orchestrator),
                        name: their_name,
                        last_seen: Instant::now(),
                    },
                );
                let our_cfg = crate::config::MeshConfig::load(
                    &crate::paths::spf_root().join("LIVE/CONFIG/mesh.json")
                ).unwrap_or_default();
                let hs = framing::control::build_handshake(
                    &our_cfg.role.to_string(),
                    &our_cfg.name,
                    env!("CARGO_PKG_VERSION"),
                );
                let resp = Frame::control(&hs);
                if send.write_all(&resp.to_bytes()).await.is_err() {
                    return;
                }
                handshake_done = true;
            }
        }
    }

    // Process first frame through normal router (skip if it was handshake — already responded)
    if !handshake_done {
        let response = stream_router(&first_frame, state, peer_key);
        if let Some(resp_frame) = response {
            let bytes = resp_frame.to_bytes();
            if send.write_all(&bytes).await.is_err() {
                return;
            }
        }
    }

    // Continue reading frames until stream closes
    let mut buf = Vec::new();
    loop {
        // Read into buffer
        let mut chunk = vec![0u8; 8192];
        match recv.read(&mut chunk).await {
            Ok(Some(n)) => {
                buf.extend_from_slice(&chunk[..n]);
            }
            Ok(None) => break,  // Stream closed by peer
            Err(_) => break,
        }

        // Parse complete frames from buffer
        loop {
            match framing::parse_frame(&buf) {
                Ok(Some((frame, consumed))) => {
                    buf.drain(..consumed);

                    // Check for graceful close
                    if frame.stream_type == StreamType::Control {
                        if let Ok(text) = frame.payload_str() {
                            // ── P2: Handshake mid-stream (reconnect scenario) ──
                            if let Some(their_role) = framing::control::parse_role(text) {
                                let their_name = framing::control::parse_name(text).unwrap_or_else(|| "unknown".to_string());
                                eprintln!("[SPF-MESH] Mid-stream handshake: {} | role={} name={}", &peer_key[..16], their_role, their_name);
                                // Update tracked_peers
                                state.tracked_peers.lock().unwrap().insert(
                                    peer_key.to_string(),
                                    crate::http::MeshPeerStatus {
                                        role: parse_agent_role(&their_role).unwrap_or(AgentRole::Orchestrator),
                                        name: their_name,
                                        last_seen: Instant::now(),
                                    },
                                );
                                let our_cfg = crate::config::MeshConfig::load(
                                    &crate::paths::spf_root().join("LIVE/CONFIG/mesh.json")
                                ).unwrap_or_default();
                                let hs = framing::control::build_handshake(
                                    &our_cfg.role.to_string(),
                                    &our_cfg.name,
                                    env!("CARGO_PKG_VERSION"),
                                );
                                let resp = Frame::control(&hs);
                                if send.write_all(&resp.to_bytes()).await.is_err() {
                                    return;
                                }
                                let _ = handshake_done; // mark as read (used in first-frame check above)
                                continue;
                            }
                            if text.contains("stream_close") {
                                // Acknowledge and close
                                let ack = Frame::control(framing::control::STREAM_CLOSE);
                                send.write_all(&ack.to_bytes()).await.ok();
                                return;
                            }
                        }
                    }

                    // Route and respond
                    let response = stream_router(&frame, state, peer_key);
                    if let Some(resp_frame) = response {
                        let bytes = resp_frame.to_bytes();
                        if send.write_all(&bytes).await.is_err() {
                            return;
                        }
                    }
                }
                Ok(None) => break,   // Need more data
                Err(e) => {
                    eprintln!("[SPF-MESH] Frame parse error from {}: {}", &peer_key[..16], e);
                    return;
                }
            }
        }
    }
}

/// Route a frame to the appropriate handler based on StreamType.
/// Returns an optional response frame.
fn stream_router(
    frame: &Frame,
    state: &Arc<ServerState>,
    peer_key: &str,
) -> Option<Frame> {
    eprintln!("[SPF-MESH] Frame: {:?} {} payload + {} header bytes",
        frame.stream_type, frame.payload.len(), FRAME_HEADER_SIZE);
    match frame.stream_type {
        StreamType::ToolRpc => {
            // Parse JSON-RPC from frame payload, dispatch via existing path
            let payload = match frame.payload_str() {
                Ok(s) => s,
                Err(_) => return Some(Frame::tool_rpc(
                    r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Invalid UTF-8"}}"#
                )),
            };

            let _msg: Value = match serde_json::from_str(payload) {
                Ok(v) => v,
                Err(_) => return Some(Frame::tool_rpc(
                    r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error"}}"#
                )),
            };

            let response = handle_legacy_rpc(payload.as_bytes(), state, peer_key);
            let resp_json = serde_json::to_string(&response).unwrap_or_default();
            Some(Frame::tool_rpc(&resp_json))
        }

        StreamType::Control => {
            // Handle control messages
            let payload = frame.payload_str().unwrap_or("{}");
            if payload.contains("heartbeat") {
                // Echo heartbeat back
                Some(Frame::control(framing::control::HEARTBEAT))
            } else if payload.contains("status_request") {
                let status = json!({
                    "type": "status_response",
                    "peer_id": state.pub_key_hex,
                    "tools": crate::mcp::tool_count(),
                    "uptime": "active",
                });
                Some(Frame::control(&serde_json::to_string(&status).unwrap_or_default()))
            } else {
                None // Unknown control message — no response needed
            }
        }

        // === Stream handlers — wired to real modules ===

        StreamType::ChatText => {
            crate::chat::handle_mesh_chat(frame, peer_key, &state.transformer)
        }

        StreamType::VoiceAudio => {
            crate::voice::handle_mesh_voice(frame, peer_key)
        }

        StreamType::PipelineTask => {
            // Route to pipeline handler — executes via dispatch::call() → gate → same 55+ tools
            crate::pipeline::handle_pipeline_task(frame, state, peer_key)
        }

        StreamType::PipelineResult => {
            // Inbound results from remote worker — route to pipeline state
            crate::pipeline::handle_pipeline_result(frame, &state.pipeline)
        }

        StreamType::BrainSync => {
            crate::learning::handle_brain_sync(frame, peer_key, &state.transformer)
        }

        StreamType::WeightSync => {
            crate::checkpoint::handle_weight_sync(frame, peer_key, &state.transformer)
        }
    }
}

// ============================================================================
// P0-4: FRAMED OUTBOUND — Send request via persistent channel, read response
// ============================================================================

/// Send a tool call frame through a persistent channel and read the response frame.
/// Returns the parsed JSON-RPC response as Value.
async fn handle_framed_outbound(
    mgr: &mut PeerChannelManager,
    request: &MeshRequest,
) -> Result<Value, String> {
    // Build JSON-RPC request
    let rpc = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": request.tool,
            "arguments": request.args,
        }
    });
    let rpc_json = serde_json::to_string(&rpc).map_err(|e| format!("Serialize error: {}", e))?;
    let frame = Frame::tool_rpc(&rpc_json);

    // Send frame through persistent channel
    mgr.send_frame(&request.peer_key, &frame).await?;

    // Read response frame with timeout
    let resp_frame = match tokio::time::timeout(
        std::time::Duration::from_secs(30),
        mgr.read_frame(&request.peer_key),
    ).await {
        Ok(Ok(Some(frame))) => frame,
        Ok(Ok(None)) => return Err("Stream closed by peer".to_string()),
        Ok(Err(e)) => return Err(format!("Read error: {}", e)),
        Err(_) => return Err("Response timed out (30s)".to_string()),
    };

    // Parse JSON-RPC response
    let response_text = resp_frame.payload_str().map_err(|e| format!("UTF-8 error: {}", e))?;
    let response: Value = serde_json::from_str(response_text)
        .map_err(|e| format!("Parse error: {}", e))?;

    Ok(response)
}

// ============================================================================
// OUTBOUND MESH CLIENT — LEGACY (unchanged)
// ============================================================================

/// Call a peer agent's tool via QUIC mesh.
/// Opens a bidirectional stream, sends JSON-RPC, reads response.
/// Accepts explicit addresses for direct connectivity without relay/mDNS/DHT.
///
/// THIS FUNCTION IS UNCHANGED — backward compatible with all existing callers.
/// For persistent streams, use call_peer_stream() instead.
#[deprecated(since = "3.1.0", note = "Use PeerChannelManager for persistent channels. Kept as fallback for backward compatibility.")]
pub async fn call_peer(
    endpoint: &Endpoint,
    peer_key: &str,
    addrs: &[String],
    alpn: &[u8],
    tool: &str,
    args: &Value,
) -> Result<Value, String> {
    // Parse peer PublicKey from hex pubkey
    let peer_bytes: [u8; 32] = hex::decode(peer_key)
        .map_err(|e| format!("Invalid peer key: {}", e))?
        .try_into()
        .map_err(|_| "Peer key must be 32 bytes".to_string())?;
    let peer_id = PublicKey::from_bytes(&peer_bytes)
        .map_err(|e| format!("Invalid peer key: {}", e))?;

    // Build EndpointAddr with explicit addresses if available
    let mut peer_addr = EndpointAddr::new(peer_id);
    for addr_str in addrs {
        if let Ok(sock_addr) = addr_str.parse::<std::net::SocketAddr>() {
            peer_addr = peer_addr.with_ip_addr(sock_addr);
        }
    }

    // Connect to peer with address hints
    let connection = endpoint.connect(peer_addr, alpn).await
        .map_err(|e| format!("Connection failed: {}", e))?;

    // Open bidirectional stream
    let (mut send, mut recv) = connection.open_bi().await
        .map_err(|e| format!("Stream failed: {}", e))?;

    // Send JSON-RPC request
    let request = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": tool,
            "arguments": args,
        }
    });
    send.write_all(serde_json::to_string(&request).unwrap().as_bytes()).await
        .map_err(|e| format!("Write failed: {}", e))?;
    send.finish().map_err(|e| format!("Finish failed: {}", e))?;

    // Read response
    let data = recv.read_to_end(10_485_760).await
        .map_err(|e| format!("Read failed: {}", e))?;

    serde_json::from_slice(&data)
        .map_err(|e| format!("Parse failed: {}", e))
}

// ============================================================================
// OUTBOUND MESH CLIENT — FRAMED PERSISTENT STREAMS (Block G new)
// ============================================================================

/// Open a persistent framed stream to a peer.
/// Returns (SendStream, RecvStream, Connection) for the caller to manage.
///
/// The caller sends frames via framing::encode_frame() + send.write_all(),
/// and reads frames by buffering recv.read() + framing::parse_frame().
///
/// The first frame sent determines the stream type for the remote router.
///
/// Example:
/// ```ignore
/// let (send, recv, conn) = call_peer_stream(&ep, key, addrs, alpn).await?;
/// // Send a tool RPC frame
/// let frame = Frame::tool_rpc(r#"{"method":"tools/call","params":{...}}"#);
/// send.write_all(&frame.to_bytes()).await?;
/// // Read response frame
/// // ... buffered read + parse_frame() ...
/// ```
pub async fn call_peer_stream(
    endpoint: &Endpoint,
    peer_key: &str,
    addrs: &[String],
    alpn: &[u8],
) -> Result<(iroh::endpoint::SendStream, iroh::endpoint::RecvStream, iroh::endpoint::Connection), String> {
    // Parse peer PublicKey from hex
    let peer_bytes: [u8; 32] = hex::decode(peer_key)
        .map_err(|e| format!("Invalid peer key: {}", e))?
        .try_into()
        .map_err(|_| "Peer key must be 32 bytes".to_string())?;
    let peer_id = PublicKey::from_bytes(&peer_bytes)
        .map_err(|e| format!("Invalid peer key: {}", e))?;

    let mut peer_addr = EndpointAddr::new(peer_id);
    for addr_str in addrs {
        if let Ok(sock_addr) = addr_str.parse::<std::net::SocketAddr>() {
            peer_addr = peer_addr.with_ip_addr(sock_addr);
        }
    }

    let connection = endpoint.connect(peer_addr, alpn).await
        .map_err(|e| format!("Connection failed: {}", e))?;

    let (send, recv) = connection.open_bi().await
        .map_err(|e| format!("Stream failed: {}", e))?;

    Ok((send, recv, connection))
}