Skip to main content

soothe_client/
client.rs

1//! Protocol-1 WebSocket transport client with mux and delivery_ack.
2
3use std::collections::{HashMap, VecDeque};
4use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
5use std::sync::Arc;
6use std::time::Duration;
7
8use futures_util::{SinkExt, StreamExt};
9use serde_json::{json, Map, Value};
10use tokio::sync::{mpsc, oneshot, Mutex, Notify};
11use tokio::time::{sleep, timeout};
12use tokio_tungstenite::{connect_async, tungstenite::Message};
13
14use crate::errors::{
15    ConnectionError, DaemonError, DisconnectCause, Error, Result, StaleLoopError, TimeoutError,
16};
17use crate::heartbeat::HeartbeatTracker;
18use crate::inbound_priority::{
19    inbound_frame_drop_priority, DEFAULT_INBOUND_MAX_SIZE, DROP_PRIORITY_NORMAL,
20};
21use crate::protocol::{
22    decode_message, expand_wire_messages, new_connection_init, new_notification, new_ping,
23    new_pong, new_request, new_subscribe, new_unsubscribe, Envelope,
24};
25use crate::stream_terminal::{
26    extract_loop_id_from_inbound, inbound_needs_delivery_ack, stale_pending_frame_label,
27};
28const DEFAULT_MAX_FRAME: usize = 10 * 1024 * 1024;
29
30/// Options for Client construction.
31#[derive(Debug, Clone)]
32pub struct ClientConfig {
33    /// WebSocket URL.
34    pub url: String,
35    /// Max inbound queue depth before priority drop.
36    pub max_inbound: usize,
37    /// Max frame size hint (informational).
38    pub max_frame_size: usize,
39}
40
41impl Default for ClientConfig {
42    fn default() -> Self {
43        Self {
44            url: "ws://127.0.0.1:8765".into(),
45            max_inbound: DEFAULT_INBOUND_MAX_SIZE,
46            max_frame_size: DEFAULT_MAX_FRAME,
47        }
48    }
49}
50
51/// Options for `send_input` / loop_input notification.
52#[derive(Debug, Clone, Default)]
53pub struct SendInputOptions {
54    /// Loop id (required for multi-loop).
55    pub loop_id: Option<String>,
56    /// Preferred subagent.
57    pub preferred_subagent: Option<String>,
58    /// Forced StrangeLoop intake scope (`trivial`|`simple`|`complex`).
59    pub intake_scope: Option<String>,
60    /// Model override.
61    pub model: Option<String>,
62    /// Model params.
63    pub model_params: Option<Value>,
64    /// Router profile.
65    pub router_profile: Option<String>,
66    /// Attachments array.
67    pub attachments: Option<Value>,
68    /// Intent hint.
69    pub intent_hint: Option<String>,
70    /// Response schema.
71    pub response_schema: Option<Value>,
72    /// Response schema name.
73    pub response_schema_name: Option<String>,
74    /// Strict schema.
75    pub response_schema_strict: Option<bool>,
76    /// Clarification mode.
77    pub clarification_mode: Option<String>,
78    /// Clarification answer flag.
79    pub clarification_answer: bool,
80    /// Clarification answers payload.
81    pub clarification_answers: Option<Value>,
82    /// Interaction mode (`agent`|`ask`|`plan`|`bypass`).
83    pub interaction_mode: Option<String>,
84    /// Autopilot rail id (pins the turn to a specific autopilot rail).
85    pub autopilot_rail_id: Option<String>,
86}
87
88type RpcWaiter = oneshot::Sender<std::result::Result<Value, DaemonError>>;
89type StreamDegradedCallback = Arc<dyn Fn(u64, String) + Send + Sync>;
90
91struct Shared {
92    url: String,
93    max_inbound: AtomicUsize,
94    write_tx: Mutex<Option<mpsc::UnboundedSender<Message>>>,
95    rpc_waiters: Mutex<HashMap<String, RpcWaiter>>,
96    inbound: Mutex<VecDeque<Value>>,
97    inbound_notify: Notify,
98    connected: AtomicBool,
99    reader_alive: AtomicBool,
100    handshake_complete: AtomicBool,
101    readiness_state: Mutex<String>,
102    disconnect_cause: Mutex<Option<DisconnectCause>>,
103    disconnect_notify: Notify,
104    inbound_dropped: AtomicU64,
105    delivery_seq: Mutex<HashMap<String, u64>>,
106    heartbeat_interval_ms: Mutex<Option<u64>>,
107    stream_degraded_cb: std::sync::Mutex<Option<StreamDegradedCallback>>,
108    degraded_notified: AtomicBool,
109    heartbeat_tracker: std::sync::Mutex<Option<Arc<HeartbeatTracker>>>,
110}
111
112/// Long-lived protocol-1 WebSocket client.
113#[derive(Clone)]
114pub struct Client {
115    shared: Arc<Shared>,
116}
117
118impl Client {
119    /// Create a client for `url`.
120    pub fn new(url: impl Into<String>) -> Self {
121        Self::with_config(ClientConfig {
122            url: url.into(),
123            ..Default::default()
124        })
125    }
126
127    /// Create with explicit config.
128    pub fn with_config(cfg: ClientConfig) -> Self {
129        Self {
130            shared: Arc::new(Shared {
131                url: cfg.url,
132                max_inbound: AtomicUsize::new(cfg.max_inbound),
133                write_tx: Mutex::new(None),
134                rpc_waiters: Mutex::new(HashMap::new()),
135                inbound: Mutex::new(VecDeque::new()),
136                inbound_notify: Notify::new(),
137                connected: AtomicBool::new(false),
138                reader_alive: AtomicBool::new(false),
139                handshake_complete: AtomicBool::new(false),
140                readiness_state: Mutex::new(String::new()),
141                disconnect_cause: Mutex::new(None),
142                disconnect_notify: Notify::new(),
143                inbound_dropped: AtomicU64::new(0),
144                delivery_seq: Mutex::new(HashMap::new()),
145                heartbeat_interval_ms: Mutex::new(None),
146                stream_degraded_cb: std::sync::Mutex::new(None),
147                degraded_notified: AtomicBool::new(false),
148                heartbeat_tracker: std::sync::Mutex::new(None),
149            }),
150        }
151    }
152
153    /// Daemon URL.
154    pub fn url(&self) -> &str {
155        &self.shared.url
156    }
157
158    /// Whether the socket is connected.
159    pub fn is_connected(&self) -> bool {
160        self.shared.connected.load(Ordering::SeqCst)
161    }
162
163    /// Whether the reader task is alive.
164    pub fn is_connection_alive(&self) -> bool {
165        self.shared.reader_alive.load(Ordering::SeqCst)
166            && self.shared.connected.load(Ordering::SeqCst)
167    }
168
169    /// Whether the protocol-1 handshake has completed.
170    pub fn is_handshake_complete(&self) -> bool {
171        self.shared.handshake_complete.load(Ordering::SeqCst)
172    }
173
174    /// Daemon `readiness_state` from the last `connection_ack` (empty before handshake).
175    pub async fn readiness_state(&self) -> String {
176        self.shared.readiness_state.lock().await.clone()
177    }
178
179    /// Count of dropped inbound frames under backpressure.
180    pub fn inbound_dropped(&self) -> u64 {
181        self.shared.inbound_dropped.load(Ordering::SeqCst)
182    }
183
184    /// Register a hook invoked on the first inbound overflow drop.
185    pub fn set_stream_degraded_callback(&self, cb: Option<Arc<dyn Fn(u64, String) + Send + Sync>>) {
186        *self
187            .shared
188            .stream_degraded_cb
189            .lock()
190            .expect("stream_degraded lock") = cb;
191        self.shared.degraded_notified.store(false, Ordering::SeqCst);
192    }
193
194    /// Enable heartbeat tracking with the default 15s alive threshold.
195    pub fn enable_heartbeat_tracking(&self) -> Arc<HeartbeatTracker> {
196        self.enable_heartbeat_tracking_with_threshold(Duration::from_secs(15))
197    }
198
199    /// Enable heartbeat tracking with a custom alive threshold.
200    pub fn enable_heartbeat_tracking_with_threshold(
201        &self,
202        threshold: Duration,
203    ) -> Arc<HeartbeatTracker> {
204        let tracker = Arc::new(HeartbeatTracker::with_threshold(threshold));
205        *self
206            .shared
207            .heartbeat_tracker
208            .lock()
209            .expect("heartbeat lock") = Some(tracker.clone());
210        tracker
211    }
212
213    /// Disable heartbeat tracking.
214    pub fn disable_heartbeat_tracking(&self) {
215        *self
216            .shared
217            .heartbeat_tracker
218            .lock()
219            .expect("heartbeat lock") = None;
220    }
221
222    /// Current heartbeat tracker, if enabled.
223    pub fn heartbeat_tracker(&self) -> Option<Arc<HeartbeatTracker>> {
224        self.shared
225            .heartbeat_tracker
226            .lock()
227            .expect("heartbeat lock")
228            .clone()
229    }
230
231    /// Whether the tracked daemon is considered alive (true if tracking disabled).
232    pub fn is_daemon_alive(&self) -> bool {
233        match self
234            .shared
235            .heartbeat_tracker
236            .lock()
237            .expect("heartbeat lock")
238            .as_ref()
239        {
240            Some(t) => t.get_health().is_alive,
241            None => true,
242        }
243    }
244
245    /// Disconnect cause if disconnected.
246    pub async fn disconnect_cause(&self) -> Option<DisconnectCause> {
247        *self.shared.disconnect_cause.lock().await
248    }
249
250    /// Wait until disconnected.
251    pub async fn wait_disconnected(&self) -> DisconnectCause {
252        loop {
253            if let Some(c) = *self.shared.disconnect_cause.lock().await {
254                return c;
255            }
256            self.shared.disconnect_notify.notified().await;
257        }
258    }
259
260    /// Dial + handshake (`connection_init` / `connection_ack` ready).
261    pub async fn connect(&self) -> Result<()> {
262        if self.is_connected() {
263            return Ok(());
264        }
265        let (ws, _) = connect_async(&self.shared.url).await.map_err(|e| {
266            ConnectionError::new(
267                &self.shared.url,
268                1,
269                Box::new(e) as Box<dyn std::error::Error + Send + Sync>,
270            )
271        })?;
272        let (mut write, mut read) = ws.split();
273        let (tx, mut rx) = mpsc::unbounded_channel::<Message>();
274        {
275            let mut slot = self.shared.write_tx.lock().await;
276            *slot = Some(tx);
277        }
278        self.shared.connected.store(true, Ordering::SeqCst);
279        self.shared.reader_alive.store(true, Ordering::SeqCst);
280        *self.shared.disconnect_cause.lock().await = None;
281
282        let shared_r2 = self.shared.clone();
283        let client_for_hb = self.clone();
284        tokio::spawn(async move {
285            while let Some(msg) = rx.recv().await {
286                if write.send(msg).await.is_err() {
287                    break;
288                }
289            }
290            let _ = write.close().await;
291        });
292
293        tokio::spawn(async move {
294            while let Some(item) = read.next().await {
295                match item {
296                    Ok(Message::Text(text)) => {
297                        if let Ok(raw) = decode_message(&text) {
298                            for msg in expand_wire_messages(raw) {
299                                shared_r2.route_inbound(msg).await;
300                            }
301                        }
302                    }
303                    Ok(Message::Ping(data)) => {
304                        let _ = shared_r2.send_raw(Message::Pong(data)).await;
305                    }
306                    Ok(Message::Close(_)) => break,
307                    Ok(_) => {}
308                    Err(_) => break,
309                }
310            }
311            shared_r2.mark_disconnected(DisconnectCause::Unclean).await;
312        });
313
314        // Handshake
315        self.send_envelope(new_connection_init()).await?;
316        let ack = self.wait_connection_ack(Duration::from_secs(15)).await?;
317        if let Some(interval) = ack
318            .get("result")
319            .and_then(|r| r.get("heartbeat_interval_ms"))
320            .and_then(|v| v.as_u64())
321        {
322            *self.shared.heartbeat_interval_ms.lock().await = Some(interval);
323            if interval > 0 {
324                let hb_client = client_for_hb;
325                tokio::spawn(async move {
326                    let period = Duration::from_millis(interval.max(5_000));
327                    while hb_client.is_connection_alive() {
328                        sleep(period).await;
329                        if !hb_client.is_connection_alive() {
330                            break;
331                        }
332                        let _ = hb_client.send_envelope(new_ping()).await;
333                    }
334                });
335            }
336        }
337        Ok(())
338    }
339
340    async fn wait_connection_ack(&self, overall: Duration) -> Result<Value> {
341        let deadline = tokio::time::Instant::now() + overall;
342        loop {
343            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
344            if remaining.is_zero() {
345                return Err(TimeoutError::new("connection_ack", format!("{overall:?}")).into());
346            }
347            let msg = self
348                .read_event_with_timeout(remaining.min(Duration::from_secs(2)))
349                .await?;
350            let Some(msg) = msg else {
351                continue;
352            };
353            let msg_type = msg.get("type").and_then(|v| v.as_str()).unwrap_or("");
354            if msg_type == "status" {
355                continue;
356            }
357            if msg_type == "error" {
358                let err = parse_daemon_error(&msg);
359                // Retryable readiness codes.
360                if matches!(err.code, -32003..=-32001) {
361                    sleep(Duration::from_millis(50)).await;
362                    self.send_envelope(new_connection_init()).await?;
363                    continue;
364                }
365                return Err(err.into());
366            }
367            if msg_type == "connection_ack" {
368                let state = msg
369                    .get("result")
370                    .and_then(|r| r.get("readiness_state"))
371                    .and_then(|v| v.as_str())
372                    .unwrap_or("");
373                if state == "starting" || state == "warming" {
374                    sleep(Duration::from_millis(50)).await;
375                    self.send_envelope(new_connection_init()).await?;
376                    continue;
377                }
378                if state == "ready" || state.is_empty() {
379                    *self.shared.readiness_state.lock().await = if state.is_empty() {
380                        "ready".into()
381                    } else {
382                        state.into()
383                    };
384                    self.shared.handshake_complete.store(true, Ordering::SeqCst);
385                    return Ok(msg);
386                }
387                return Err(Error::protocol(format!(
388                    "connection_ack readiness_state={state}"
389                )));
390            }
391        }
392    }
393
394    /// Close the connection.
395    pub async fn close(&self) -> Result<()> {
396        if self.is_connected() {
397            let _ = self.notify("disconnect", Map::new()).await;
398        }
399        {
400            let mut tx = self.shared.write_tx.lock().await;
401            *tx = None;
402        }
403        self.shared
404            .handshake_complete
405            .store(false, Ordering::SeqCst);
406        *self.shared.readiness_state.lock().await = String::new();
407        self.shared.mark_disconnected(DisconnectCause::Clean).await;
408        Ok(())
409    }
410
411    /// Re-dial and re-handshake after a connection drop.
412    ///
413    /// Does not re-establish loop subscriptions; follow with `reattach_and_probe`
414    /// to resume a loop session.
415    pub async fn reconnect(&self) -> Result<()> {
416        {
417            let mut tx = self.shared.write_tx.lock().await;
418            *tx = None;
419        }
420        self.shared.connected.store(false, Ordering::SeqCst);
421        self.shared.reader_alive.store(false, Ordering::SeqCst);
422        self.shared
423            .handshake_complete
424            .store(false, Ordering::SeqCst);
425        *self.shared.readiness_state.lock().await = String::new();
426        *self.shared.disconnect_cause.lock().await = None;
427        self.shared.rpc_waiters.lock().await.clear();
428        self.shared.inbound.lock().await.clear();
429        self.shared.degraded_notified.store(false, Ordering::SeqCst);
430        self.connect().await
431    }
432
433    /// Send a raw envelope.
434    pub async fn send_envelope(&self, env: Envelope) -> Result<()> {
435        let text = env.to_wire_json()?;
436        self.shared.send_raw(Message::Text(text.into())).await
437    }
438
439    /// Fire-and-forget notification.
440    pub async fn notify(&self, method: &str, params: Map<String, Value>) -> Result<()> {
441        self.send_envelope(new_notification(method, params)).await
442    }
443
444    /// RPC request correlated by id.
445    pub async fn request(
446        &self,
447        method: &str,
448        params: Map<String, Value>,
449        req_timeout: Duration,
450    ) -> Result<Map<String, Value>> {
451        let env = new_request(method, params);
452        let id = env.id.clone().unwrap_or_default();
453        let (tx, rx) = oneshot::channel();
454        self.shared.rpc_waiters.lock().await.insert(id.clone(), tx);
455        if let Err(e) = self.send_envelope(env).await {
456            self.shared.rpc_waiters.lock().await.remove(&id);
457            return Err(e);
458        }
459        match timeout(req_timeout, rx).await {
460            Ok(Ok(Ok(Value::Object(m)))) => Ok(m),
461            Ok(Ok(Ok(other))) => {
462                let mut m = Map::new();
463                m.insert("result".into(), other);
464                Ok(m)
465            }
466            Ok(Ok(Err(de))) => Err(de.into()),
467            Ok(Err(_)) => Err(Error::protocol("rpc waiter dropped")),
468            Err(_) => {
469                self.shared.rpc_waiters.lock().await.remove(&id);
470                Err(TimeoutError::new(method, format!("{req_timeout:?}")).into())
471            }
472        }
473    }
474
475    /// Request with a payload map whose `type` field names the method.
476    pub async fn request_response(
477        &self,
478        payload: Map<String, Value>,
479        fallback_method: &str,
480        req_timeout: Duration,
481    ) -> Result<Map<String, Value>> {
482        let method = payload
483            .get("type")
484            .and_then(|v| v.as_str())
485            .unwrap_or(fallback_method)
486            .to_string();
487        let mut params = Map::new();
488        for (k, v) in payload {
489            if k == "type" || k == "request_id" {
490                continue;
491            }
492            params.insert(k, v);
493        }
494        self.request(&method, params, req_timeout).await
495    }
496
497    /// Subscribe; returns subscription id.
498    pub async fn subscribe(
499        &self,
500        method: &str,
501        params: Map<String, Value>,
502        req_timeout: Duration,
503    ) -> Result<String> {
504        let env = new_subscribe(method, params);
505        let id = env.id.clone().unwrap_or_default();
506        // Subscribe confirmation may arrive as next/complete; we treat send success as ok
507        // and rely on subsequent events. Still register a short waiter for error.
508        let (tx, rx) = oneshot::channel();
509        self.shared.rpc_waiters.lock().await.insert(id.clone(), tx);
510        self.send_envelope(env).await?;
511        // Don't block long — many daemons only send `next` without a response.
512        match timeout(req_timeout.min(Duration::from_millis(500)), rx).await {
513            Ok(Ok(Err(de))) => return Err(de.into()),
514            Ok(Ok(Ok(_))) => {}
515            _ => {
516                self.shared.rpc_waiters.lock().await.remove(&id);
517            }
518        }
519        Ok(id)
520    }
521
522    /// Unsubscribe by id.
523    pub async fn unsubscribe(&self, id: &str) -> Result<()> {
524        self.send_envelope(new_unsubscribe(id)).await
525    }
526
527    /// Read next inbound app event (blocks).
528    pub async fn read_event(&self) -> Result<Option<Value>> {
529        loop {
530            {
531                let mut q = self.shared.inbound.lock().await;
532                if let Some(v) = q.pop_front() {
533                    return Ok(Some(v));
534                }
535            }
536            if !self.is_connection_alive() {
537                return Ok(None);
538            }
539            self.shared.inbound_notify.notified().await;
540        }
541    }
542
543    /// Read with timeout; `None` on timeout.
544    pub async fn read_event_with_timeout(&self, dur: Duration) -> Result<Option<Value>> {
545        match timeout(dur, self.read_event()).await {
546            Ok(r) => r,
547            Err(_) => Ok(None),
548        }
549    }
550
551    /// Clear pending inbound events.
552    pub async fn clear_pending_events(&self) {
553        self.shared.inbound.lock().await.clear();
554    }
555
556    /// Peel stale pending control frames at turn start.
557    pub async fn peel_stale_pending_control_events(&self) -> Vec<String> {
558        let mut labels = Vec::new();
559        let mut kept = VecDeque::new();
560        let mut q = self.shared.inbound.lock().await;
561        while let Some(ev) = q.pop_front() {
562            if let Some(label) = stale_pending_frame_label(&ev) {
563                labels.push(label);
564            } else {
565                kept.push_back(ev);
566            }
567        }
568        *q = kept;
569        labels
570    }
571
572    /// Re-queue an event ahead of subsequent `read_event` calls.
573    ///
574    /// Applies priority-aware drop when the pending buffer is full.
575    pub async fn push_pending_event(&self, ev: Value) {
576        if !ev.is_object() {
577            return;
578        }
579        let mut q = self.shared.inbound.lock().await;
580        self.shared.enqueue_pending_locked(&mut q, ev);
581        self.shared.inbound_notify.notify_one();
582    }
583
584    /// Override the pending-event cap at runtime.
585    pub fn set_inbound_max_size(&self, n: usize) {
586        if n > 0 {
587            self.shared.max_inbound.store(n, Ordering::SeqCst);
588        }
589    }
590
591    /// Background reader that streams inbound frames on a channel.
592    ///
593    /// The channel closes when the connection ends. Solicited frames (RPC
594    /// responses / subscription confirmations) stay on the internal mux and
595    /// are not forwarded; only unsolicited app events are forwarded.
596    pub fn receive_messages(&self, buffer: usize) -> mpsc::Receiver<Value> {
597        let (tx, rx) = mpsc::channel(if buffer == 0 { 100 } else { buffer });
598        let shared = self.shared.clone();
599        tokio::spawn(async move {
600            loop {
601                let ev = {
602                    let mut q = shared.inbound.lock().await;
603                    q.pop_front()
604                };
605                if let Some(ev) = ev {
606                    if tx.send(ev).await.is_err() {
607                        return;
608                    }
609                    continue;
610                }
611                if !shared.is_connection_alive() {
612                    return;
613                }
614                shared.inbound_notify.notified().await;
615            }
616        });
617        rx
618    }
619
620    /// Notify `loop_input`.
621    pub async fn send_input(&self, text: &str, opts: SendInputOptions) -> Result<()> {
622        let mut params = Map::new();
623        params.insert("content".into(), json!(text));
624        if let Some(lid) = opts.loop_id {
625            params.insert("loop_id".into(), json!(lid));
626        }
627        if let Some(v) = opts.preferred_subagent {
628            params.insert("preferred_subagent".into(), json!(v));
629        }
630        if let Some(v) = opts.intake_scope {
631            params.insert("intake_scope".into(), json!(v));
632        }
633        if let Some(v) = opts.model {
634            params.insert("model".into(), json!(v));
635        }
636        if let Some(v) = opts.model_params {
637            params.insert("model_params".into(), v);
638        }
639        if let Some(v) = opts.router_profile {
640            params.insert("router_profile".into(), json!(v));
641        }
642        if let Some(v) = opts.attachments {
643            params.insert("attachments".into(), v);
644        }
645        if let Some(v) = opts.intent_hint {
646            params.insert("intent_hint".into(), json!(v));
647        }
648        if let Some(v) = opts.response_schema {
649            params.insert("response_schema".into(), v);
650        }
651        if let Some(v) = opts.response_schema_name {
652            params.insert("response_schema_name".into(), json!(v));
653        }
654        if let Some(v) = opts.response_schema_strict {
655            params.insert("response_schema_strict".into(), json!(v));
656        }
657        if let Some(v) = opts.clarification_mode {
658            params.insert("clarification_mode".into(), json!(v));
659        }
660        if opts.clarification_answer {
661            params.insert("clarification_answer".into(), json!(true));
662        }
663        if let Some(v) = opts.clarification_answers {
664            params.insert("clarification_answers".into(), v);
665        }
666        if let Some(v) = opts.interaction_mode {
667            params.insert("interaction_mode".into(), json!(v));
668        }
669        if let Some(v) = opts.autopilot_rail_id {
670            params.insert("autopilot_rail_id".into(), json!(v));
671        }
672        self.notify("loop_input", params).await
673    }
674
675    /// `loop_new` RPC.
676    pub async fn loop_new(&self, params: Map<String, Value>) -> Result<Map<String, Value>> {
677        self.request("loop_new", params, Duration::from_secs(30))
678            .await
679    }
680
681    /// `loop_list`.
682    pub async fn loop_list(&self, limit: u32) -> Result<Map<String, Value>> {
683        let mut params = Map::new();
684        params.insert("limit".into(), json!(limit));
685        self.request("loop_list", params, Duration::from_secs(15))
686            .await
687    }
688
689    /// `loop_get`.
690    pub async fn loop_get(&self, loop_id: &str) -> Result<Map<String, Value>> {
691        let mut params = Map::new();
692        params.insert("loop_id".into(), json!(loop_id));
693        self.request("loop_get", params, Duration::from_secs(15))
694            .await
695    }
696
697    /// `loop_reattach`.
698    pub async fn loop_reattach(&self, loop_id: &str) -> Result<Map<String, Value>> {
699        let mut params = Map::new();
700        params.insert("loop_id".into(), json!(loop_id));
701        self.request("loop_reattach", params, Duration::from_secs(15))
702            .await
703    }
704
705    /// Subscribe to `loop_events`.
706    pub async fn loop_subscribe(&self, loop_id: &str, stream_delivery: &str) -> Result<String> {
707        let mut params = Map::new();
708        params.insert("loop_id".into(), json!(loop_id));
709        params.insert("stream_delivery".into(), json!(stream_delivery));
710        params.insert("wire_tier".into(), json!("full"));
711        self.subscribe("loop_events", params, Duration::from_secs(30))
712            .await
713    }
714
715    /// `loop_history_fetch`.
716    pub async fn loop_history_fetch(&self, loop_id: &str) -> Result<Map<String, Value>> {
717        let mut params = Map::new();
718        params.insert("loop_id".into(), json!(loop_id));
719        self.request("loop_history_fetch", params, Duration::from_secs(30))
720            .await
721    }
722
723    /// `loop_execution_state_fetch` — execution-progress snapshot
724    /// (plan, step_index, iteration, status) for the bound checkpoint thread.
725    pub async fn loop_execution_state_fetch(&self, loop_id: &str) -> Result<Map<String, Value>> {
726        let mut params = Map::new();
727        params.insert("loop_id".into(), json!(loop_id));
728        self.request(
729            "loop_execution_state_fetch",
730            params,
731            Duration::from_secs(30),
732        )
733        .await
734    }
735
736    /// `loop_messages`.
737    pub async fn loop_messages(
738        &self,
739        loop_id: &str,
740        limit: u32,
741        offset: u32,
742    ) -> Result<Map<String, Value>> {
743        let mut params = Map::new();
744        params.insert("loop_id".into(), json!(loop_id));
745        params.insert("limit".into(), json!(limit));
746        params.insert("offset".into(), json!(offset));
747        self.request("loop_messages", params, Duration::from_secs(10))
748            .await
749    }
750
751    /// `loop_state_get`.
752    pub async fn loop_state_get(&self, loop_id: &str) -> Result<Map<String, Value>> {
753        let mut params = Map::new();
754        params.insert("loop_id".into(), json!(loop_id));
755        self.request("loop_state_get", params, Duration::from_secs(30))
756            .await
757    }
758
759    /// `loop_state_update`.
760    pub async fn loop_state_update(
761        &self,
762        loop_id: &str,
763        state: Map<String, Value>,
764    ) -> Result<Map<String, Value>> {
765        let mut params = Map::new();
766        params.insert("loop_id".into(), json!(loop_id));
767        params.insert("state".into(), Value::Object(state));
768        self.request("loop_state_update", params, Duration::from_secs(30))
769            .await
770    }
771
772    /// `loop_delete`.
773    pub async fn loop_delete(&self, loop_id: &str) -> Result<Map<String, Value>> {
774        let mut params = Map::new();
775        params.insert("loop_id".into(), json!(loop_id));
776        self.request("loop_delete", params, Duration::from_secs(10))
777            .await
778    }
779
780    /// Detach from a loop by unsubscribing (`subscription_id` from `loop_subscribe`).
781    pub async fn loop_detach(&self, subscription_id: &str) -> Result<()> {
782        self.unsubscribe(subscription_id).await
783    }
784
785    /// Authenticate with access/secret keys.
786    pub async fn authenticate(
787        &self,
788        access_key: &str,
789        secret_key: &str,
790    ) -> Result<Map<String, Value>> {
791        let mut params = Map::new();
792        params.insert("access_key".into(), json!(access_key));
793        params.insert("secret_key".into(), json!(secret_key));
794        self.request("auth", params, Duration::from_secs(15)).await
795    }
796
797    /// Refresh auth token.
798    pub async fn refresh_auth_token(&self, refresh_token: &str) -> Result<Map<String, Value>> {
799        let mut params = Map::new();
800        params.insert("refresh_token".into(), json!(refresh_token));
801        self.request("auth_refresh", params, Duration::from_secs(15))
802            .await
803    }
804
805    /// `job_create` on this long-lived connection. `rail_id` is required
806    /// (loop-native submission path).
807    pub async fn job_create(
808        &self,
809        goal: &str,
810        rail_id: &str,
811        workspace: Option<&str>,
812    ) -> Result<Map<String, Value>> {
813        if goal.trim().is_empty() {
814            return Err(crate::errors::Error::msg("goal is required"));
815        }
816        if rail_id.trim().is_empty() {
817            return Err(crate::errors::Error::msg("rail_id is required"));
818        }
819        let mut params = Map::new();
820        params.insert("goal".into(), json!(goal));
821        params.insert("rail_id".into(), json!(rail_id));
822        if let Some(ws) = workspace {
823            params.insert("workspace".into(), json!(ws));
824        }
825        self.request("job_create", params, Duration::from_secs(30))
826            .await
827    }
828
829    /// `job_status`.
830    pub async fn job_status(&self, job_id: &str) -> Result<Map<String, Value>> {
831        let mut params = Map::new();
832        params.insert("job_id".into(), json!(job_id));
833        self.request("job_status", params, Duration::from_secs(15))
834            .await
835    }
836
837    /// `job_pause`.
838    pub async fn job_pause(&self, job_id: &str) -> Result<Map<String, Value>> {
839        let mut params = Map::new();
840        params.insert("job_id".into(), json!(job_id));
841        self.request("job_pause", params, Duration::from_secs(15))
842            .await
843    }
844
845    /// `job_resume`.
846    pub async fn job_resume(&self, job_id: &str) -> Result<Map<String, Value>> {
847        let mut params = Map::new();
848        params.insert("job_id".into(), json!(job_id));
849        self.request("job_resume", params, Duration::from_secs(15))
850            .await
851    }
852
853    /// `job_cancel`.
854    pub async fn job_cancel(&self, job_id: &str) -> Result<Map<String, Value>> {
855        let mut params = Map::new();
856        params.insert("job_id".into(), json!(job_id));
857        self.request("job_cancel", params, Duration::from_secs(15))
858            .await
859    }
860
861    /// `job_dag`.
862    pub async fn job_dag(&self, job_id: &str) -> Result<Map<String, Value>> {
863        let mut params = Map::new();
864        params.insert("job_id".into(), json!(job_id));
865        self.request("job_dag", params, Duration::from_secs(15))
866            .await
867    }
868
869    /// `job_guidance`.
870    pub async fn job_guidance(
871        &self,
872        job_id: &str,
873        content: &str,
874        goal_id: Option<&str>,
875    ) -> Result<Map<String, Value>> {
876        let mut params = Map::new();
877        params.insert("job_id".into(), json!(job_id));
878        params.insert("content".into(), json!(content));
879        if let Some(g) = goal_id {
880            params.insert("goal_id".into(), json!(g));
881        }
882        self.request("job_guidance", params, Duration::from_secs(30))
883            .await
884    }
885
886    /// `cron_add`.
887    pub async fn cron_add(&self, text: &str, priority: Option<i32>) -> Result<Map<String, Value>> {
888        let mut params = Map::new();
889        params.insert("text".into(), json!(text));
890        if let Some(p) = priority {
891            params.insert("priority".into(), json!(p));
892        }
893        self.request("cron_add", params, Duration::from_secs(15))
894            .await
895    }
896
897    /// `cron_list`.
898    pub async fn cron_list(&self, status: Option<&str>) -> Result<Map<String, Value>> {
899        let mut params = Map::new();
900        if let Some(s) = status {
901            params.insert("status".into(), json!(s));
902        }
903        self.request("cron_list", params, Duration::from_secs(15))
904            .await
905    }
906
907    /// `cron_show`.
908    pub async fn cron_show(&self, job_id: &str) -> Result<Map<String, Value>> {
909        let mut params = Map::new();
910        params.insert("job_id".into(), json!(job_id));
911        self.request("cron_show", params, Duration::from_secs(15))
912            .await
913    }
914
915    /// `cron_cancel`.
916    pub async fn cron_cancel(&self, job_id: &str) -> Result<Map<String, Value>> {
917        let mut params = Map::new();
918        params.insert("job_id".into(), json!(job_id));
919        self.request("cron_cancel", params, Duration::from_secs(15))
920            .await
921    }
922
923    /// `memory_stats`.
924    pub async fn memory_stats(&self, mode: &str) -> Result<Map<String, Value>> {
925        let mut params = Map::new();
926        params.insert("mode".into(), json!(mode));
927        self.request("memory_stats", params, Duration::from_secs(15))
928            .await
929    }
930
931    /// `skills_list`.
932    pub async fn list_skills(&self) -> Result<Map<String, Value>> {
933        self.request("skills_list", Map::new(), Duration::from_secs(15))
934            .await
935    }
936
937    /// `models_list`.
938    pub async fn list_models(&self) -> Result<Map<String, Value>> {
939        self.request("models_list", Map::new(), Duration::from_secs(15))
940            .await
941    }
942
943    /// `mcp_status`.
944    pub async fn mcp_status(&self) -> Result<Map<String, Value>> {
945        self.request("mcp_status", Map::new(), Duration::from_secs(15))
946            .await
947    }
948
949    /// `daemon_status`.
950    pub async fn fetch_daemon_status(&self) -> Result<Map<String, Value>> {
951        self.request("daemon_status", Map::new(), Duration::from_secs(10))
952            .await
953    }
954
955    /// `config_get` — fetch a daemon config section (empty `section` → all).
956    pub async fn config_get(&self, section: &str) -> Result<Map<String, Value>> {
957        let mut params = Map::new();
958        if !section.is_empty() {
959            params.insert("section".into(), json!(section));
960        }
961        self.request("config_get", params, Duration::from_secs(15))
962            .await
963    }
964
965    /// `config_reload` — ask the daemon to reload its configuration.
966    pub async fn config_reload(&self) -> Result<Map<String, Value>> {
967        self.request("config_reload", Map::new(), Duration::from_secs(5))
968            .await
969    }
970
971    /// `daemon_shutdown` — request graceful daemon shutdown.
972    ///
973    /// Returns `Ok(())` when the daemon acknowledges the shutdown request.
974    pub async fn daemon_shutdown(&self) -> Result<()> {
975        let resp = self
976            .request("daemon_shutdown", Map::new(), Duration::from_secs(10))
977            .await?;
978        let status = resp.get("status").and_then(|v| v.as_str()).unwrap_or("");
979        if status != "acknowledged" && !status.is_empty() {
980            return Err(Error::msg(format!("unexpected shutdown status: {status}")));
981        }
982        Ok(())
983    }
984
985    /// `invoke_skill` on this connection (stream socket for turn enqueue).
986    pub async fn invoke_skill(
987        &self,
988        skill: &str,
989        args: &str,
990        interaction_mode: Option<&str>,
991    ) -> Result<Map<String, Value>> {
992        let mut params = Map::new();
993        params.insert("skill".into(), json!(skill));
994        if !args.is_empty() {
995            params.insert("args".into(), json!(args));
996        }
997        if let Some(v) = interaction_mode {
998            params.insert("interaction_mode".into(), json!(v));
999        }
1000        self.request("invoke_skill", params, Duration::from_secs(120))
1001            .await
1002    }
1003
1004    /// Reattach + subscribe + `loop_get` probe.
1005    pub async fn reattach_and_probe(&self, loop_id: &str) -> Result<()> {
1006        self.loop_reattach(loop_id).await?;
1007        self.loop_subscribe(loop_id, "adaptive").await?;
1008        match self.loop_get(loop_id).await {
1009            Ok(_) => Ok(()),
1010            Err(Error::Daemon(de)) if de.code == -32200 => {
1011                Err(StaleLoopError::new(loop_id, Some(Box::new(de))).into())
1012            }
1013            Err(e) => Err(StaleLoopError::new(loop_id, Some(Box::new(e))).into()),
1014        }
1015    }
1016
1017    // ----- Structured command shorthands (Go `CommandRequest` parity) -----
1018
1019    /// `command_request` RPC (structured slash command).
1020    pub async fn command_request(
1021        &self,
1022        command: &str,
1023        loop_id: Option<&str>,
1024        params: Option<Map<String, Value>>,
1025    ) -> Result<Map<String, Value>> {
1026        let mut p = Map::new();
1027        p.insert("command".into(), json!(command));
1028        if let Some(lid) = loop_id {
1029            p.insert("loop_id".into(), json!(lid));
1030        }
1031        if let Some(extra) = params {
1032            p.insert("params".into(), Value::Object(extra));
1033        }
1034        self.request("command_request", p, Duration::from_secs(30))
1035            .await
1036    }
1037
1038    /// `/clear` — clear loop conversation history.
1039    pub async fn command_clear(&self, loop_id: &str) -> Result<Map<String, Value>> {
1040        self.command_request("clear", Some(loop_id), None).await
1041    }
1042
1043    /// `/exit` — stop the loop and mark for exit.
1044    pub async fn command_exit(&self, loop_id: &str) -> Result<Map<String, Value>> {
1045        self.command_request("exit", Some(loop_id), None).await
1046    }
1047
1048    /// `/quit` — alias for `/exit`.
1049    pub async fn command_quit(&self, loop_id: &str) -> Result<Map<String, Value>> {
1050        self.command_request("quit", Some(loop_id), None).await
1051    }
1052
1053    /// `/detach` — mark the loop as detached (continues running server-side).
1054    pub async fn command_detach(&self, loop_id: &str) -> Result<Map<String, Value>> {
1055        self.command_request("detach", Some(loop_id), None).await
1056    }
1057
1058    /// `/cancel` — cancel the running query.
1059    pub async fn command_cancel(&self, loop_id: &str) -> Result<Map<String, Value>> {
1060        self.command_request("cancel", Some(loop_id), None).await
1061    }
1062
1063    /// `/memory` — query memory stats.
1064    pub async fn command_memory(&self, loop_id: &str) -> Result<Map<String, Value>> {
1065        self.command_request("memory", Some(loop_id), None).await
1066    }
1067
1068    /// `/policy` — query the active policy profile.
1069    pub async fn command_policy(&self) -> Result<Map<String, Value>> {
1070        self.command_request("policy", None, None).await
1071    }
1072
1073    /// `/history` — query input history.
1074    pub async fn command_history(&self, loop_id: &str) -> Result<Map<String, Value>> {
1075        self.command_request("history", Some(loop_id), None).await
1076    }
1077
1078    /// `/config` — query daemon configuration.
1079    pub async fn command_config(&self) -> Result<Map<String, Value>> {
1080        self.command_request("config", None, None).await
1081    }
1082
1083    /// `/review` — query conversation review.
1084    pub async fn command_review(&self, loop_id: &str) -> Result<Map<String, Value>> {
1085        self.command_request("review", Some(loop_id), None).await
1086    }
1087
1088    /// `/plan` — query current plan.
1089    pub async fn command_plan(&self, loop_id: &str) -> Result<Map<String, Value>> {
1090        self.command_request("plan", Some(loop_id), None).await
1091    }
1092
1093    /// `/autopilot_dashboard` — show autopilot dashboard.
1094    pub async fn command_autopilot_dashboard(&self, loop_id: &str) -> Result<Map<String, Value>> {
1095        self.command_request("autopilot_dashboard", Some(loop_id), None)
1096            .await
1097    }
1098
1099    // ----- Daemon readiness -----
1100
1101    /// Wait for the `connection_ack` handshake to report `readiness_state == "ready"`.
1102    ///
1103    /// Returns immediately when the handshake already completed during
1104    /// `connect`; otherwise polls inbound frames for an out-of-band
1105    /// `connection_ack`.
1106    pub async fn wait_for_daemon_ready(&self, timeout: Duration) -> Result<Map<String, Value>> {
1107        let timeout = if timeout.is_zero() {
1108            Duration::from_secs(10)
1109        } else {
1110            timeout
1111        };
1112        // Handshake already completed during `connect` — do not drain inbound
1113        // looking for a second `connection_ack` (that stalls and drops events).
1114        if self.is_handshake_complete() {
1115            let state = self.readiness_state().await;
1116            if state.is_empty() || state == "ready" {
1117                let mut m = Map::new();
1118                m.insert("readiness_state".into(), json!("ready"));
1119                return Ok(m);
1120            }
1121            return Err(Error::protocol(format!(
1122                "daemon not ready: readiness_state={state}"
1123            )));
1124        }
1125        let deadline = tokio::time::Instant::now() + timeout;
1126        loop {
1127            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
1128            if remaining.is_zero() {
1129                return Err(TimeoutError::new("connection_ack", format!("{timeout:?}")).into());
1130            }
1131            let msg = self
1132                .read_event_with_timeout(remaining.min(Duration::from_secs(2)))
1133                .await?;
1134            let Some(msg) = msg else {
1135                continue;
1136            };
1137            let msg_type = msg.get("type").and_then(|v| v.as_str()).unwrap_or("");
1138            if msg_type != "connection_ack" {
1139                continue;
1140            }
1141            let state = msg
1142                .get("result")
1143                .and_then(|r| r.get("readiness_state"))
1144                .and_then(|v| v.as_str())
1145                .unwrap_or("");
1146            if state == "ready" {
1147                return Ok(map_from_value(msg));
1148            }
1149            return Err(Error::protocol(format!(
1150                "daemon not ready: readiness_state={state}"
1151            )));
1152        }
1153    }
1154}
1155
1156/// Convert a `Value` (expected Object) into a `Map<String, Value>`.
1157fn map_from_value(v: Value) -> Map<String, Value> {
1158    match v {
1159        Value::Object(m) => m,
1160        other => {
1161            let mut m = Map::new();
1162            m.insert("result".into(), other);
1163            m
1164        }
1165    }
1166}
1167
1168impl Shared {
1169    fn is_connection_alive(&self) -> bool {
1170        self.reader_alive.load(Ordering::SeqCst) && self.connected.load(Ordering::SeqCst)
1171    }
1172
1173    async fn send_raw(&self, msg: Message) -> Result<()> {
1174        let tx = self.write_tx.lock().await;
1175        let Some(tx) = tx.as_ref() else {
1176            return Err(Error::protocol("not connected"));
1177        };
1178        tx.send(msg)
1179            .map_err(|_| Error::protocol("write channel closed"))?;
1180        Ok(())
1181    }
1182
1183    async fn mark_disconnected(&self, cause: DisconnectCause) {
1184        self.connected.store(false, Ordering::SeqCst);
1185        self.reader_alive.store(false, Ordering::SeqCst);
1186        {
1187            let mut slot = self.write_tx.lock().await;
1188            *slot = None;
1189        }
1190        {
1191            let mut c = self.disconnect_cause.lock().await;
1192            if c.is_none() {
1193                *c = Some(cause);
1194            }
1195        }
1196        // Fail pending RPCs.
1197        let mut waiters = self.rpc_waiters.lock().await;
1198        for (_, tx) in waiters.drain() {
1199            let _ = tx.send(Err(DaemonError::new(-1, "disconnected")));
1200        }
1201        self.inbound_notify.notify_waiters();
1202        self.disconnect_notify.notify_waiters();
1203    }
1204
1205    async fn route_inbound(&self, msg: Value) {
1206        // Auto pong for app-level ping.
1207        if msg.get("type").and_then(|v| v.as_str()) == Some("ping") {
1208            let _ = self
1209                .send_raw(Message::Text(
1210                    new_pong().to_wire_json().unwrap_or_default().into(),
1211                ))
1212                .await;
1213            return;
1214        }
1215
1216        if msg.get("type").and_then(|v| v.as_str()) == Some("pong") {
1217            if let Some(tracker) = self.heartbeat_tracker.lock().expect("hb").as_ref() {
1218                tracker.note_pong();
1219            }
1220            return;
1221        }
1222
1223        // Daemon heartbeat custom events (namespace / type heuristics).
1224        let ns = msg
1225            .get("namespace")
1226            .or_else(|| msg.get("type"))
1227            .and_then(|v| v.as_str())
1228            .unwrap_or("");
1229        if ns.contains("heartbeat") {
1230            if let Some(tracker) = self.heartbeat_tracker.lock().expect("hb").as_ref() {
1231                tracker.update(msg.get("data"));
1232            }
1233        }
1234
1235        if inbound_needs_delivery_ack(&msg) {
1236            let loop_id = extract_loop_id_from_inbound(&msg);
1237            if !loop_id.is_empty() {
1238                let seq = {
1239                    let mut map = self.delivery_seq.lock().await;
1240                    let e = map.entry(loop_id.clone()).or_insert(0);
1241                    *e += 1;
1242                    *e
1243                };
1244                let mut params = Map::new();
1245                params.insert("loop_id".into(), json!(loop_id));
1246                params.insert("seq".into(), json!(seq));
1247                let _ = self
1248                    .send_raw(Message::Text(
1249                        new_notification("delivery_ack", params)
1250                            .to_wire_json()
1251                            .unwrap_or_default()
1252                            .into(),
1253                    ))
1254                    .await;
1255            }
1256        }
1257
1258        let msg_type = msg.get("type").and_then(|v| v.as_str()).unwrap_or("");
1259        let id = msg
1260            .get("id")
1261            .and_then(|v| v.as_str())
1262            .unwrap_or("")
1263            .to_string();
1264
1265        if matches!(msg_type, "response" | "error") && !id.is_empty() {
1266            if let Some(waiter) = self.rpc_waiters.lock().await.remove(&id) {
1267                let result = if msg_type == "error" {
1268                    Err(parse_daemon_error(&msg))
1269                } else {
1270                    Ok(msg
1271                        .get("result")
1272                        .cloned()
1273                        .unwrap_or(Value::Object(Map::new())))
1274                };
1275                let _ = waiter.send(result);
1276                return;
1277            }
1278        }
1279
1280        // Push to inbound queue with priority backpressure.
1281        {
1282            let mut q = self.inbound.lock().await;
1283            self.enqueue_pending_locked(&mut q, msg);
1284        }
1285        self.inbound_notify.notify_one();
1286    }
1287
1288    fn enqueue_pending_locked(&self, q: &mut VecDeque<Value>, ev: Value) {
1289        let max = self.max_inbound.load(Ordering::SeqCst);
1290        if q.len() < max {
1291            q.push_back(ev);
1292            return;
1293        }
1294        // Priority-aware drop: remove highest-priority-number (NORMAL) frame if possible.
1295        let mut drop_idx = None;
1296        let mut drop_pri = -1;
1297        for (i, item) in q.iter().enumerate() {
1298            let p = inbound_frame_drop_priority(item.as_object());
1299            if p > drop_pri {
1300                drop_pri = p;
1301                drop_idx = Some(i);
1302            }
1303        }
1304        let incoming_pri = inbound_frame_drop_priority(ev.as_object());
1305        if let Some(idx) = drop_idx {
1306            if drop_pri >= DROP_PRIORITY_NORMAL {
1307                q.remove(idx);
1308                q.push_back(ev);
1309                self.note_inbound_drop("priority_evict");
1310                return;
1311            }
1312        }
1313        if incoming_pri >= DROP_PRIORITY_NORMAL {
1314            self.note_inbound_drop("queue_full");
1315            return;
1316        }
1317        // Incoming is CRITICAL/HIGH: force-drop oldest to admit it.
1318        if !q.is_empty() {
1319            q.pop_front();
1320            self.note_inbound_drop("priority_evict");
1321        }
1322        q.push_back(ev);
1323    }
1324
1325    fn note_inbound_drop(&self, reason: &str) {
1326        let n = self.inbound_dropped.fetch_add(1, Ordering::SeqCst) + 1;
1327        if !self.degraded_notified.swap(true, Ordering::SeqCst) {
1328            if let Some(cb) = self.stream_degraded_cb.lock().expect("cb").as_ref() {
1329                cb(n, reason.to_string());
1330            }
1331        }
1332    }
1333}
1334
1335fn parse_daemon_error(msg: &Value) -> DaemonError {
1336    if let Some(err) = msg.get("error") {
1337        let code = err.get("code").and_then(|c| c.as_i64()).unwrap_or(-1);
1338        let message = err
1339            .get("message")
1340            .and_then(|m| m.as_str())
1341            .unwrap_or("daemon error")
1342            .to_string();
1343        let data = err.get("data").cloned();
1344        let mut de = DaemonError::new(code, message);
1345        if let Some(d) = data {
1346            de = de.with_data(d);
1347        }
1348        return de;
1349    }
1350    DaemonError::new(
1351        -1,
1352        msg.get("message")
1353            .and_then(|m| m.as_str())
1354            .unwrap_or("daemon error"),
1355    )
1356}
1357
1358/// Re-export unwrap helper for appkit.
1359pub use crate::protocol::unwrap_next as unwrap_next_frame;
1360
1361#[cfg(test)]
1362mod tests {
1363    use super::*;
1364
1365    #[test]
1366    fn send_input_options_default() {
1367        let o = SendInputOptions::default();
1368        assert!(o.loop_id.is_none());
1369        assert!(o.preferred_subagent.is_none());
1370    }
1371}