aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / spark-discord-hub / src / gateway.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | use futures_util::{SinkExt, StreamExt}; |
| 17 | use serde_json::json; |
| 18 | use std::sync::atomic::{AtomicI64, Ordering}; |
| 19 | use std::sync::Arc; |
| 20 | use std::time::Duration; |
| 21 | use tokio::sync::mpsc; |
| 22 | use tokio::time::sleep; |
| 23 | use tokio_tungstenite::connect_async; |
| 24 | use tokio_tungstenite::tungstenite::Message as WsMessage; |
| 25 | use tracing::{error, info, warn}; |
| 26 | |
| 27 | use crate::atlas_bot::AtlasBot; |
| 28 | use crate::gideon_bot::GideonBot; |
| 29 | use crate::models::DiscordMessage; |
| 30 | |
| 31 | pub struct DiscordGatewayHub { |
| 32 | token: String, |
| 33 | atlas_bot: Arc<AtlasBot>, |
| 34 | gideon_bot: Arc<GideonBot>, |
| 35 | bot_user_id: Arc<tokio::sync::Mutex<Option<String>>>, |
| 36 | } |
| 37 | |
| 38 | impl DiscordGatewayHub { |
| 39 | pub fn new(token: String) -> Self { |
| 40 | Self { |
| 41 | atlas_bot: Arc::new(AtlasBot::new(token.clone())), |
| 42 | gideon_bot: Arc::new(GideonBot::new(token.clone())), |
| 43 | token, |
| 44 | bot_user_id: Arc::new(tokio::sync::Mutex::new(None)), |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | pub async fn run(&self) -> Result<(), Box<dyn std::error::Error>> { |
| 49 | let gateway_url = "wss://gateway.discord.gg/?v=10&encoding=json"; |
| 50 | info!( |
| 51 | "[GatewayHub] Connecting to Discord Gateway at {}...", |
| 52 | gateway_url |
| 53 | ); |
| 54 | |
| 55 | let mut backoff_secs = 5; |
| 56 | |
| 57 | loop { |
| 58 | match connect_async(gateway_url).await { |
| 59 | Ok((ws_stream, _)) => { |
| 60 | info!("[GatewayHub] Connected to Discord Gateway WebSocket."); |
| 61 | backoff_secs = 5; |
| 62 | |
| 63 | let (mut write, mut read) = ws_stream.split(); |
| 64 | let (outbound_tx, mut outbound_rx) = mpsc::channel::<WsMessage>(64); |
| 65 | |
| 66 | // Writer task: forwards outbound messages to the WebSocket sink |
| 67 | let writer_handle = tokio::spawn(async move { |
| 68 | while let Some(msg) = outbound_rx.recv().await { |
| 69 | if let Err(e) = write.send(msg).await { |
| 70 | warn!("[GatewayHub] WebSocket send failed: {}", e); |
| 71 | break; |
| 72 | } |
| 73 | } |
| 74 | }); |
| 75 | |
| 76 | let last_seq = Arc::new(AtomicI64::new(-1)); |
| 77 | let mut heartbeat_handle: Option<tokio::task::JoinHandle<()>> = None; |
| 78 | |
| 79 | while let Some(msg_result) = read.next().await { |
| 80 | match msg_result { |
| 81 | Ok(WsMessage::Text(text)) => { |
| 82 | if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) { |
| 83 | let op = v.get("op").and_then(|o| o.as_i64()).unwrap_or(-1); |
| 84 | |
| 85 | // Track sequence number |
| 86 | if let Some(s) = v.get("s").and_then(|s| s.as_i64()) { |
| 87 | last_seq.store(s, Ordering::Relaxed); |
| 88 | } |
| 89 | |
| 90 | // Opcode 10: Hello |
| 91 | if op == 10 { |
| 92 | if let Some(hb_ms) = v |
| 93 | .pointer("/d/heartbeat_interval") |
| 94 | .and_then(|h| h.as_u64()) |
| 95 | { |
| 96 | info!("[GatewayHub] Received Hello. Heartbeat interval: {}ms", hb_ms); |
| 97 | |
| 98 | // 1. Identify immediately (Intents: Guilds 1 + Guild Messages 512 + Message Content 32768 = 33281) |
| 99 | let identify = json!({ |
| 100 | "op": 2, |
| 101 | "d": { |
| 102 | "token": self.token, |
| 103 | "intents": 33281, |
| 104 | "properties": { |
| 105 | "os": "linux", |
| 106 | "browser": "spark-discord-hub", |
| 107 | "device": "spark-gb10" |
| 108 | } |
| 109 | } |
| 110 | }); |
| 111 | let _ = outbound_tx |
| 112 | .send(WsMessage::Text(identify.to_string())) |
| 113 | .await; |
| 114 | |
| 115 | // 2. Spawn periodic heartbeat task |
| 116 | if let Some(h) = heartbeat_handle.take() { |
| 117 | h.abort(); |
| 118 | } |
| 119 | let hb_tx = outbound_tx.clone(); |
| 120 | let seq_ref = last_seq.clone(); |
| 121 | heartbeat_handle = Some(tokio::spawn(async move { |
| 122 | let mut interval = tokio::time::interval( |
| 123 | Duration::from_millis(hb_ms), |
| 124 | ); |
| 125 | interval.tick().await; // first tick finishes immediately |
| 126 | loop { |
| 127 | interval.tick().await; |
| 128 | let s = seq_ref.load(Ordering::Relaxed); |
| 129 | let hb_payload = if s >= 0 { |
| 130 | json!({"op": 1, "d": s}) |
| 131 | } else { |
| 132 | json!({"op": 1, "d": null}) |
| 133 | }; |
| 134 | if hb_tx |
| 135 | .send(WsMessage::Text( |
| 136 | hb_payload.to_string(), |
| 137 | )) |
| 138 | .await |
| 139 | .is_err() |
| 140 | { |
| 141 | break; |
| 142 | } |
| 143 | } |
| 144 | })); |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | // Opcode 1: Heartbeat requested by Discord server |
| 149 | if op == 1 { |
| 150 | let s = last_seq.load(Ordering::Relaxed); |
| 151 | let hb_reply = if s >= 0 { |
| 152 | json!({"op": 1, "d": s}) |
| 153 | } else { |
| 154 | json!({"op": 1, "d": null}) |
| 155 | }; |
| 156 | let _ = outbound_tx |
| 157 | .send(WsMessage::Text(hb_reply.to_string())) |
| 158 | .await; |
| 159 | } |
| 160 | |
| 161 | // Opcode 7: Reconnect request from server |
| 162 | if op == 7 { |
| 163 | warn!( |
| 164 | "[GatewayHub] Discord requested reconnect (Opcode 7)." |
| 165 | ); |
| 166 | break; |
| 167 | } |
| 168 | |
| 169 | // Opcode 9: Invalid session |
| 170 | if op == 9 { |
| 171 | warn!("[GatewayHub] Discord invalid session (Opcode 9)."); |
| 172 | break; |
| 173 | } |
| 174 | |
| 175 | // Opcode 0: Dispatch event |
| 176 | if op == 0 { |
| 177 | let event_name = |
| 178 | v.get("t").and_then(|t| t.as_str()).unwrap_or(""); |
| 179 | if event_name == "READY" { |
| 180 | if let Some(id) = |
| 181 | v.pointer("/d/user/id").and_then(|i| i.as_str()) |
| 182 | { |
| 183 | *self.bot_user_id.lock().await = |
| 184 | Some(id.to_string()); |
| 185 | info!("[GatewayHub] Gateway Ready. Authenticated as bot ID: {}", id); |
| 186 | } |
| 187 | } else if event_name == "MESSAGE_CREATE" { |
| 188 | if let Some(d) = v.get("d") { |
| 189 | if let Ok(msg) = |
| 190 | serde_json::from_value::<DiscordMessage>( |
| 191 | d.clone(), |
| 192 | ) |
| 193 | { |
| 194 | self.route_message(msg).await; |
| 195 | } |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | } |
| 201 | Ok(WsMessage::Close(frame)) => { |
| 202 | warn!("[GatewayHub] WebSocket closed by Discord: {:?}", frame); |
| 203 | break; |
| 204 | } |
| 205 | Err(e) => { |
| 206 | error!("[GatewayHub] WebSocket read error: {}", e); |
| 207 | break; |
| 208 | } |
| 209 | _ => {} |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | if let Some(h) = heartbeat_handle { |
| 214 | h.abort(); |
| 215 | } |
| 216 | writer_handle.abort(); |
| 217 | } |
| 218 | Err(e) => { |
| 219 | error!( |
| 220 | "[GatewayHub] Failed to connect: {}. Retrying in {}s...", |
| 221 | e, backoff_secs |
| 222 | ); |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | sleep(Duration::from_secs(backoff_secs)).await; |
| 227 | backoff_secs = (backoff_secs * 2).min(60); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | async fn route_message(&self, msg: DiscordMessage) { |
| 232 | if msg.author.bot.unwrap_or(false) { |
| 233 | return; |
| 234 | } |
| 235 | |
| 236 | let my_id = self.bot_user_id.lock().await.clone().unwrap_or_default(); |
| 237 | let content = msg.content.trim(); |
| 238 | |
| 239 | // 1. Gideon bot commands |
| 240 | if content.starts_with("!gideon") |
| 241 | || content.starts_with("!verify") |
| 242 | || content.starts_with("!link") |
| 243 | { |
| 244 | let g = self.gideon_bot.clone(); |
| 245 | let c_id = msg.channel_id.clone(); |
| 246 | let m_id = msg.id.clone(); |
| 247 | let text = content.to_string(); |
| 248 | let author = msg.author.username.clone(); |
| 249 | tokio::spawn(async move { |
| 250 | g.handle_command(&c_id, &m_id, &text, &author).await; |
| 251 | }); |
| 252 | return; |
| 253 | } |
| 254 | |
| 255 | // 2. Atlas bot inquiries |
| 256 | let is_atlas_mention = !my_id.is_empty() && content.contains(&format!("<@{}>", my_id)); |
| 257 | let is_atlas_command = content.starts_with("!atlas") || content.starts_with("!ask"); |
| 258 | |
| 259 | if is_atlas_mention || is_atlas_command { |
| 260 | let clean_prompt = if is_atlas_command { |
| 261 | content |
| 262 | .trim_start_matches("!atlas") |
| 263 | .trim_start_matches("!ask") |
| 264 | .trim() |
| 265 | .to_string() |
| 266 | } else { |
| 267 | content |
| 268 | .replace(&format!("<@{}>", my_id), "") |
| 269 | .trim() |
| 270 | .to_string() |
| 271 | }; |
| 272 | |
| 273 | if clean_prompt.is_empty() { |
| 274 | return; |
| 275 | } |
| 276 | |
| 277 | let a = self.atlas_bot.clone(); |
| 278 | let c_id = msg.channel_id.clone(); |
| 279 | let m_id = msg.id.clone(); |
| 280 | let prompt = clean_prompt.to_string(); |
| 281 | let author = msg.author.username.clone(); |
| 282 | tokio::spawn(async move { |
| 283 | a.handle_message(&c_id, &m_id, &prompt, &author).await; |
| 284 | }); |
| 285 | } |
| 286 | } |
| 287 | } |