1use std::sync::{Arc, Mutex};
19use std::time::Duration;
20
21use futures_util::{SinkExt, StreamExt};
22use serde_json::Value;
23use tokio::sync::mpsc;
24use tokio_tungstenite::tungstenite::Message;
25
26use crate::backend::reactive::types::InjectionRequest;
27use crate::messaging::{BridgeHealth, BridgeStatus, OutboundMsg};
28
29use super::rest;
30use super::types::{
31 opcode, GatewayPayload, HeartbeatPayload, IdentifyData, IdentifyPayload, IdentifyProperties,
32 MessageCreate, ReadyEvent, ResumeData, ResumePayload, INTENTS,
33};
34
35const GATEWAY_URL: &str = "wss://gateway.discord.gg/?v=10&encoding=json";
36const RECONNECT_DELAY_SECS: u64 = 5;
37const MAX_RECONNECT_DELAY_SECS: u64 = 60;
38
39#[derive(Clone)]
40struct Session {
41 session_id: String,
42 resume_url: String,
43 last_seq: u64,
44}
45
46pub async fn run_gateway_loop(
47 token: String,
48 channel_id: String,
49 target_agent: Option<String>,
50 http: reqwest::Client,
51 mut outbound_rx: mpsc::UnboundedReceiver<OutboundMsg>,
52 health: Arc<Mutex<BridgeHealth>>,
53) {
54 let mut delay_secs = RECONNECT_DELAY_SECS;
55 let mut session: Option<Session> = None;
56
57 loop {
58 {
59 let mut h = health.lock().unwrap();
60 h.status = BridgeStatus::Connecting;
61 }
62
63 let connect_url = session
64 .as_ref()
65 .map(|s| {
66 if s.resume_url.contains("?v=") {
68 s.resume_url.clone()
69 } else {
70 format!("{}?v=10&encoding=json", s.resume_url)
71 }
72 })
73 .unwrap_or_else(|| GATEWAY_URL.to_string());
74
75 tracing::info!("discord_bridge: connecting to {}", connect_url);
76 let session_start = std::time::Instant::now();
77
78 match run_session(
79 &token,
80 &channel_id,
81 &target_agent,
82 &connect_url,
83 &http,
84 &mut outbound_rx,
85 &health,
86 session.take(),
87 )
88 .await
89 {
90 Ok(new_session) => {
91 session = new_session;
92 if session_start.elapsed().as_secs() > 30 {
93 delay_secs = RECONNECT_DELAY_SECS;
94 }
95 tracing::info!("discord_bridge: session ended cleanly");
96 }
97 Err(e) => {
98 session = None;
99 if session_start.elapsed().as_secs() > 30 {
100 delay_secs = RECONNECT_DELAY_SECS;
101 }
102 tracing::warn!("discord_bridge: session error: {e}");
103 {
104 let mut h = health.lock().unwrap();
105 h.status = BridgeStatus::Error;
106 h.error = Some(e);
107 h.reconnect_count += 1;
108 }
109 }
110 }
111
112 {
113 let mut h = health.lock().unwrap();
114 if h.status != BridgeStatus::Error {
115 h.status = BridgeStatus::Disconnected;
116 }
117 }
118
119 tokio::time::sleep(Duration::from_secs(delay_secs)).await;
120 delay_secs = (delay_secs * 2).min(MAX_RECONNECT_DELAY_SECS);
121 }
122}
123
124enum Step {
126 Continue,
127 End(Result<Option<Session>, String>),
128}
129
130struct Ctx<'a> {
132 token: &'a str,
133 channel_id: &'a str,
134 target_agent: &'a Option<String>,
135 http: &'a reqwest::Client,
136 health: &'a Arc<Mutex<BridgeHealth>>,
137 resume_session: Option<Session>,
138}
139
140struct Heartbeat {
143 sleep: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>,
144 interval_ms: u64,
145 acked: bool,
146}
147
148struct State {
150 hb: Heartbeat,
151 session: Option<Session>,
152 identified: bool,
153}
154
155type WsError = tokio_tungstenite::tungstenite::Error;
156
157async fn run_session(
162 token: &str,
163 channel_id: &str,
164 target_agent: &Option<String>,
165 connect_url: &str,
166 http: &reqwest::Client,
167 outbound_rx: &mut mpsc::UnboundedReceiver<OutboundMsg>,
168 health: &Arc<Mutex<BridgeHealth>>,
169 resume_session: Option<Session>,
170) -> Result<Option<Session>, String> {
171 use tokio_tungstenite::tungstenite::client::IntoClientRequest;
172
173 let request = connect_url
175 .into_client_request()
176 .map_err(|e| format!("build ws request: {e}"))?;
177
178 let (ws_stream, _) = crate::muxbus::ws_connect::connect(request)
179 .await
180 .map_err(|e| format!("ws connect: {e}"))?;
181
182 let (mut write, mut read) = ws_stream.split();
183 let ctx = Ctx { token, channel_id, target_agent, http, health, resume_session };
184 let mut st = State {
185 hb: Heartbeat { sleep: Box::pin(std::future::pending()), interval_ms: 0, acked: true },
186 session: None,
187 identified: false,
188 };
189
190 loop {
191 let step = tokio::select! {
192 _ = &mut st.hb.sleep, if st.hb.interval_ms > 0 => on_heartbeat_tick(&mut write, &mut st).await,
193 msg = outbound_rx.recv() => on_outbound(msg, &ctx, &mut st).await,
194 frame = read.next() => on_frame(&mut write, &ctx, &mut st, frame).await,
195 };
196 if let Step::End(result) = step {
197 return result;
198 }
199 }
200}
201
202fn heartbeat_text(seq: Option<u64>) -> String {
203 serde_json::to_string(&HeartbeatPayload { op: opcode::HEARTBEAT, d: seq }).unwrap_or_default()
204}
205
206async fn on_heartbeat_tick<W>(write: &mut W, st: &mut State) -> Step
208where
209 W: futures_util::Sink<Message, Error = WsError> + Unpin,
210{
211 if !st.hb.acked {
212 tracing::warn!("discord_bridge: heartbeat zombie — reconnecting");
213 let _ = write.send(Message::Close(None)).await;
214 return Step::End(Ok(st.session.take()));
215 }
216 let payload = heartbeat_text(st.session.as_ref().map(|s| s.last_seq));
217 if let Err(e) = write.send(Message::Text(payload.into())).await {
218 return Step::End(Err(format!("heartbeat send: {e}")));
219 }
220 st.hb.acked = false;
221 st.hb.sleep = Box::pin(tokio::time::sleep(Duration::from_millis(st.hb.interval_ms)));
222 Step::Continue
223}
224
225async fn on_outbound(msg: Option<OutboundMsg>, ctx: &Ctx<'_>, st: &mut State) -> Step {
227 let Some(outbound) = msg else {
228 return Step::End(Ok(st.session.take()));
229 };
230 let channel = if outbound.channel_id.is_empty() {
231 ctx.channel_id
232 } else {
233 outbound.channel_id.as_str()
234 };
235 if let Err(e) = rest::send_message(ctx.http, ctx.token, channel, &outbound).await {
236 tracing::warn!("discord_bridge: send failed: {e}");
237 }
238 Step::Continue
239}
240
241async fn on_frame<W>(
243 write: &mut W,
244 ctx: &Ctx<'_>,
245 st: &mut State,
246 frame: Option<Result<Message, WsError>>,
247) -> Step
248where
249 W: futures_util::Sink<Message, Error = WsError> + Unpin,
250{
251 match frame {
252 None | Some(Ok(Message::Close(_))) => Step::End(Ok(st.session.take())),
253 Some(Err(e)) => Step::End(Err(format!("ws recv: {e}"))),
254 Some(Ok(Message::Text(text))) => {
255 let payload: GatewayPayload = match serde_json::from_str(&text) {
256 Ok(p) => p,
257 Err(e) => {
258 tracing::warn!("discord_bridge: parse error: {e}");
259 return Step::Continue;
260 }
261 };
262 if let (Some(seq), Some(sess)) = (payload.seq, st.session.as_mut()) {
264 if seq > sess.last_seq {
265 sess.last_seq = seq;
266 }
267 }
268 on_payload(write, ctx, st, payload).await
269 }
270 Some(Ok(Message::Ping(data))) => {
271 let _ = write.send(Message::Pong(data)).await;
272 Step::Continue
273 }
274 Some(Ok(_)) => Step::Continue,
275 }
276}
277
278async fn on_payload<W>(write: &mut W, ctx: &Ctx<'_>, st: &mut State, payload: GatewayPayload) -> Step
280where
281 W: futures_util::Sink<Message, Error = WsError> + Unpin,
282{
283 match payload.opcode {
284 opcode::HELLO => match on_hello(write, ctx, st, payload.data.as_ref()).await {
285 Ok(()) => Step::Continue,
286 Err(e) => Step::End(Err(e)),
287 },
288 opcode::HEARTBEAT_ACK => {
289 st.hb.acked = true;
290 let mut h = ctx.health.lock().unwrap();
291 h.status = BridgeStatus::Connected;
292 h.error = None;
293 h.last_event_at = Some(unix_secs());
294 Step::Continue
295 }
296 opcode::HEARTBEAT => {
297 let payload = heartbeat_text(st.session.as_ref().map(|s| s.last_seq));
299 let _ = write.send(Message::Text(payload.into())).await;
300 Step::Continue
301 }
302 opcode::RECONNECT => {
303 tracing::info!("discord_bridge: server requested reconnect (RESUME eligible)");
304 let _ = write.send(Message::Close(None)).await;
305 Step::End(Ok(st.session.take()))
306 }
307 opcode::INVALID_SESSION => {
308 let resumable = payload.data.as_ref().and_then(Value::as_bool).unwrap_or(false);
309 tracing::warn!("discord_bridge: invalid session (resumable={resumable})");
310 let _ = write.send(Message::Close(None)).await;
311 Step::End(Ok(if resumable { st.session.take() } else { None }))
312 }
313 opcode::DISPATCH => {
314 handle_dispatch(
315 payload.event_type.as_deref(),
316 payload.data,
317 ctx.channel_id,
318 ctx.target_agent,
319 &mut st.session,
320 ctx.health,
321 );
322 Step::Continue
323 }
324 op => {
325 tracing::debug!("discord_bridge: unhandled opcode {op}");
326 Step::Continue
327 }
328 }
329}
330
331async fn on_hello<W>(
333 write: &mut W,
334 ctx: &Ctx<'_>,
335 st: &mut State,
336 data: Option<&Value>,
337) -> Result<(), String>
338where
339 W: futures_util::Sink<Message, Error = WsError> + Unpin,
340{
341 st.hb.interval_ms = data
342 .and_then(|d| d.get("heartbeat_interval"))
343 .and_then(Value::as_u64)
344 .unwrap_or(41_250);
345 st.hb.sleep = Box::pin(tokio::time::sleep(Duration::from_millis(st.hb.interval_ms)));
347 st.hb.acked = true;
348
349 if let Some(prev) = ctx.resume_session.as_ref().filter(|_| !st.identified) {
350 write
351 .send(Message::Text(resume_text(ctx.token, prev).into()))
352 .await
353 .map_err(|e| format!("resume send: {e}"))?;
354 st.session = Some(prev.clone());
355 } else {
356 write
357 .send(Message::Text(identify_text(ctx.token).into()))
358 .await
359 .map_err(|e| format!("identify send: {e}"))?;
360 }
361 st.identified = true;
362 Ok(())
363}
364
365fn resume_text(token: &str, prev: &Session) -> String {
366 serde_json::to_string(&ResumePayload {
367 op: opcode::RESUME,
368 d: ResumeData {
369 token: token.to_string(),
370 session_id: prev.session_id.clone(),
371 seq: prev.last_seq,
372 },
373 })
374 .unwrap_or_default()
375}
376
377fn identify_text(token: &str) -> String {
378 serde_json::to_string(&IdentifyPayload {
379 op: opcode::IDENTIFY,
380 d: IdentifyData {
381 token: token.to_string(),
382 intents: INTENTS,
383 properties: IdentifyProperties {
384 os: std::env::consts::OS.to_string(),
385 browser: "agentmux".to_string(),
386 device: "agentmux".to_string(),
387 },
388 },
389 })
390 .unwrap_or_default()
391}
392
393fn handle_dispatch(
394 event_type: Option<&str>,
395 data: Option<Value>,
396 channel_id: &str,
397 target_agent: &Option<String>,
398 session: &mut Option<Session>,
399 health: &Arc<Mutex<BridgeHealth>>,
400) {
401 match event_type {
402 Some("READY") => {
403 if let Some(data) = data {
404 if let Ok(ready) = serde_json::from_value::<ReadyEvent>(data) {
405 let username = ready
406 .user
407 .as_ref()
408 .map(|u| u.username.as_str())
409 .unwrap_or("unknown");
410 tracing::info!(
411 "discord_bridge: READY as {}, session {}",
412 username,
413 ready.session_id
414 );
415 *session = Some(Session {
416 session_id: ready.session_id.clone(),
417 resume_url: ready.resume_gateway_url.clone(),
418 last_seq: 0,
419 });
420 let mut h = health.lock().unwrap();
421 h.status = BridgeStatus::Connected;
422 h.error = None;
423 }
424 }
425 }
426
427 Some("RESUMED") => {
428 tracing::info!("discord_bridge: session RESUMED");
429 let mut h = health.lock().unwrap();
430 h.status = BridgeStatus::Connected;
431 h.error = None;
432 }
433
434 Some("MESSAGE_CREATE") => {
435 let data = match data {
436 Some(d) => d,
437 None => return,
438 };
439 let msg: MessageCreate = match serde_json::from_value(data) {
440 Ok(m) => m,
441 Err(e) => {
442 tracing::warn!("discord_bridge: parse MESSAGE_CREATE: {e}");
443 return;
444 }
445 };
446
447 if msg.author.bot.unwrap_or(false) {
449 return;
450 }
451
452 if msg.channel_id != channel_id {
454 return;
455 }
456
457 {
458 let mut h = health.lock().unwrap();
459 h.last_event_at = Some(unix_secs());
460 }
461
462 let Some(target) = target_agent else {
463 tracing::debug!(
464 "discord_bridge: message from {} (no target agent configured)",
465 msg.author.username
466 );
467 return;
468 };
469
470 let envelope = format!("[Discord @{}]: {}", msg.author.username, msg.content);
471 let req = InjectionRequest {
472 target_agent: target.clone(),
473 message: envelope,
474 source_agent: Some("discord".to_string()),
475 request_id: Some(msg.id.clone()),
476 priority: None,
477 jekt_tier: None,
478 delivery_tier: Some("wan".to_string()),
479 forward_hops: 0,
480 ..Default::default()
481 };
482 let result = crate::server::jekt_entry::inject_from_bridge(req, &msg.content);
483 if result.success {
484 tracing::debug!(
485 "discord_bridge: injected msg from {} to agent {}",
486 msg.author.username,
487 target
488 );
489 } else {
490 tracing::warn!(
491 "discord_bridge: inject to agent {} failed: {:?}",
492 target,
493 result.error
494 );
495 }
496 }
497
498 Some(t) => {
499 tracing::debug!("discord_bridge: unhandled event {t}");
500 }
501 None => {}
502 }
503}
504
505fn unix_secs() -> u64 {
506 agentmux_common::time::now_secs_u64()
507}
508
509#[cfg(test)]
510#[path = "gateway_tests.rs"]
511mod tests;