| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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}; |
|
|
| |
| fn spf_alpn(config: &MeshConfig) -> Vec<u8> { |
| config.alpn.as_bytes().to_vec() |
| } |
|
|
| |
| |
| fn to_iroh_key(signing_key: &SigningKey) -> SecretKey { |
| SecretKey::from_bytes(&signing_key.to_bytes()) |
| } |
|
|
| |
| 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) |
| } |
|
|
| |
| |
| 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(), |
| } |
| } |
|
|
| |
| |
| |
| 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 |
| } |
|
|
| |
| |
| |
|
|
| |
| #[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>>, |
| } |
|
|
| |
| |
| pub fn create_mesh_channel() -> ( |
| std::sync::mpsc::Sender<MeshRequest>, |
| std::sync::mpsc::Receiver<MeshRequest>, |
| ) { |
| std::sync::mpsc::channel() |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| 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 { |
| |
| 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), |
| Ok(Err(e)) => return Err(format!("Read error: {}", e)), |
| Err(_) => break, |
| } |
| attempts += 1; |
| } |
| Ok(None) |
| } |
|
|
| |
| 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, |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| 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, |
| } |
|
|
| |
| |
| |
|
|
| |
| pub struct PeerChannelManager { |
| channels: HashMap<String, PeerChannel>, |
| endpoint: Endpoint, |
| alpn: Vec<u8>, |
| peer_addrs: HashMap<String, Vec<String>>, |
| } |
|
|
| impl PeerChannelManager { |
| |
| pub fn new(endpoint: Endpoint, alpn: Vec<u8>) -> Self { |
| Self { |
| channels: HashMap::new(), |
| endpoint, |
| alpn, |
| peer_addrs: HashMap::new(), |
| } |
| } |
|
|
| |
| pub fn register_peer_addrs(&mut self, peer_key: &str, addrs: Vec<String>) { |
| self.peer_addrs.insert(peer_key.to_string(), addrs); |
| } |
|
|
| |
| 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_iroh |
| .write_all(&handshake_frame.to_bytes()) |
| .await |
| .map_err(|e| format!("Write failed: {}", e))?; |
|
|
| |
| 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(()) |
| } |
|
|
| |
| 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]); |
| } |
| } |
|
|
| |
| 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(()) |
| } |
|
|
| |
| |
| 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])); |
| } |
|
|
| |
| 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)), |
| } |
| } |
| } |
|
|
| |
| pub fn get_channel(&mut self, peer_key: &str) -> Option<&mut PeerChannel> { |
| self.channels.get_mut(peer_key) |
| } |
|
|
| |
| pub fn active_peers(&self) -> Vec<String> { |
| self.channels |
| .iter() |
| .filter(|(_, ch)| ch.active) |
| .map(|(k, _)| k.clone()) |
| .collect() |
| } |
|
|
| |
| pub fn peer_role(&self, peer_key: &str) -> Option<AgentRole> { |
| self.channels.get(peer_key).map(|ch| ch.role) |
| } |
|
|
| |
| 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 |
| } |
|
|
| |
| 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 |
| } |
|
|
| |
| pub fn has_channel(&self, peer_key: &str) -> bool { |
| self.channels.contains_key(peer_key) |
| } |
|
|
| |
| pub fn channel_count(&self) -> usize { |
| self.channels.len() |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| pub async fn run( |
| state: Arc<ServerState>, |
| signing_key: SigningKey, |
| config: MeshConfig, |
| mesh_rx: std::sync::mpsc::Receiver<MeshRequest>, |
| ) { |
| let alpn = spf_alpn(&config); |
|
|
| |
| 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; |
| } |
| } |
| }; |
|
|
| |
| endpoint.online().await; |
|
|
| |
| 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); |
|
|
| |
| { |
| 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"); |
|
|
| |
| |
| let nc_endpoint = endpoint.clone(); |
| tokio::spawn(async move { |
| loop { |
| nc_endpoint.network_change().await; |
| } |
| }); |
|
|
| |
| let self_role = config.role; |
| let self_key = hex::encode(state.signing_key.verifying_key().to_bytes()); |
|
|
| |
| 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]); |
| } |
|
|
| |
| let boot_hs = Frame::control(&framing::control::build_handshake( |
| &self_role.to_string(), |
| &config.name, |
| env!("CARGO_PKG_VERSION"), |
| )); |
|
|
| |
| 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()); |
|
|
| |
| for (key, info) in &outbound_peers { |
| if outbound_trusted.contains(key.as_str()) { |
| mgr.register_peer_addrs(key, info.addr.clone()); |
| } |
| } |
|
|
| |
| |
| 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 { |
| |
| |
| if outbound_role == AgentRole::Orchestrator { |
| eprintln!("[SPF-MESH] Boot-connect (orchestrator): {}", &pk[..16]); |
| let _ = m.connect(pk, addrs, AgentRole::Orchestrator, &outbound_hs).await; |
| } else { |
| |
| eprintln!("[SPF-MESH] Boot-connect ({} mode): {}", outbound_role, &pk[..16]); |
| |
| let _ = m.connect(pk, addrs, AgentRole::Orchestrator, &outbound_hs).await; |
| } |
| } |
| m |
| }); |
| |
| |
| let mut mgr = boot_mgr; |
|
|
| |
| 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, |
| }, |
| ); |
| } |
| |
| 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); |
|
|
| while let Ok(request) = mesh_rx.recv() { |
| let ep = outbound_ep.clone(); |
| let a = outbound_alpn.clone(); |
|
|
| |
| let result = if mgr.has_channel(&request.peer_key) { |
| let ch_active = mgr.peer_role(&request.peer_key).is_some(); |
| if ch_active { |
| |
| let req = request.clone(); |
| rt_handle.block_on(async { |
| handle_framed_outbound(&mut mgr, &req).await |
| }) |
| } else { |
| |
| 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 { |
| |
| 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(); |
| } |
| }); |
|
|
| |
| 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(); |
|
|
| |
| 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_peer(connection, &state, &peer_hex).await; |
| }); |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| async fn handle_peer( |
| connection: iroh::endpoint::Connection, |
| state: &Arc<ServerState>, |
| peer_key: &str, |
| ) { |
| loop { |
| |
| let (mut send, mut recv) = match connection.accept_bi().await { |
| Ok(streams) => streams, |
| Err(_) => break, |
| }; |
|
|
| |
| 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, |
| Ok(Some(_)) => first_byte[0], |
| Err(_) => break, |
| }; |
|
|
| let protocol = framing::detect_protocol(first); |
|
|
| match protocol { |
| framing::Protocol::LegacyJsonRpc => { |
| |
| |
| 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) => { |
| |
| |
| let mut header_rest = [0u8; 4]; |
| 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; |
| } |
|
|
| |
| 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); |
|
|
| |
| 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(); |
| } |
| } |
| } |
| } |
|
|
| |
| 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!({})); |
|
|
| |
| 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)} |
| }) |
| } |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| async fn handle_framed_stream( |
| mut send: iroh::endpoint::SendStream, |
| mut recv: iroh::endpoint::RecvStream, |
| first_frame: Frame, |
| state: &Arc<ServerState>, |
| peer_key: &str, |
| ) { |
| |
| |
| |
| 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); |
| |
| 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; |
| } |
| } |
| } |
|
|
| |
| 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; |
| } |
| } |
| } |
|
|
| |
| let mut buf = Vec::new(); |
| loop { |
| |
| let mut chunk = vec![0u8; 8192]; |
| match recv.read(&mut chunk).await { |
| Ok(Some(n)) => { |
| buf.extend_from_slice(&chunk[..n]); |
| } |
| Ok(None) => break, |
| Err(_) => break, |
| } |
|
|
| |
| loop { |
| match framing::parse_frame(&buf) { |
| Ok(Some((frame, consumed))) => { |
| buf.drain(..consumed); |
|
|
| |
| if frame.stream_type == StreamType::Control { |
| if let Ok(text) = 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] Mid-stream handshake: {} | role={} name={}", &peer_key[..16], their_role, their_name); |
| |
| 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; |
| continue; |
| } |
| if text.contains("stream_close") { |
| |
| let ack = Frame::control(framing::control::STREAM_CLOSE); |
| send.write_all(&ack.to_bytes()).await.ok(); |
| return; |
| } |
| } |
| } |
|
|
| |
| 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, |
| Err(e) => { |
| eprintln!("[SPF-MESH] Frame parse error from {}: {}", &peer_key[..16], e); |
| return; |
| } |
| } |
| } |
| } |
| } |
|
|
| |
| |
| 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 => { |
| |
| 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 => { |
| |
| let payload = frame.payload_str().unwrap_or("{}"); |
| if payload.contains("heartbeat") { |
| |
| 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 |
| } |
| } |
|
|
| |
|
|
| StreamType::ChatText => { |
| crate::chat::handle_mesh_chat(frame, peer_key, &state.transformer) |
| } |
|
|
| StreamType::VoiceAudio => { |
| crate::voice::handle_mesh_voice(frame, peer_key) |
| } |
|
|
| StreamType::PipelineTask => { |
| |
| crate::pipeline::handle_pipeline_task(frame, state, peer_key) |
| } |
|
|
| StreamType::PipelineResult => { |
| |
| 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) |
| } |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| async fn handle_framed_outbound( |
| mgr: &mut PeerChannelManager, |
| request: &MeshRequest, |
| ) -> Result<Value, String> { |
| |
| 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); |
|
|
| |
| mgr.send_frame(&request.peer_key, &frame).await?; |
|
|
| |
| 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()), |
| }; |
|
|
| |
| 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) |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| #[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> { |
| |
| 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 (mut send, mut recv) = connection.open_bi().await |
| .map_err(|e| format!("Stream failed: {}", e))?; |
|
|
| |
| 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))?; |
|
|
| |
| 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)) |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| 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> { |
| |
| 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)) |
| } |
|
|