SPFsmartGATE / src /mesh.rs
JosephStoneCellAI's picture
Upload 45 files
1269259 verified
// 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))
}