herdr-sdk 0.0.1

A small synchronous client for Herdr's socket API: typed requests, an event stream, and the pane and agent models plugins actually touch.
Documentation
//! A held-open connection that yields Herdr events.
//!
//! ▲ The two spellings are not the same. You *subscribe* with dots
//! (`pane.updated`) and you *receive* underscores (`pane_updated`). Subscribing
//! with the received spelling is accepted-looking and silently yields nothing,
//! so [`EventKind`] owns both and no call site writes either by hand.
//!
//! ▲ `pane.agent_status_changed` is pane-scoped: subscribing to it without a
//! `pane_id` is rejected outright. See [`EventKind::requires_pane_scope`].

use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;

use anyhow::{Context as _, Result, bail};
use serde::Deserialize;

/// The events a panel needs to stay honest about where agents are.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventKind {
    PaneUpdated,
    PaneFocused,
    PaneCreated,
    PaneClosed,
    PaneExited,
    PaneAgentDetected,
    PaneAgentStatusChanged,
    WorkspaceFocused,
}

impl EventKind {
    /// The dotted name `events.subscribe` expects.
    pub fn subscription(self) -> &'static str {
        match self {
            Self::PaneUpdated => "pane.updated",
            Self::PaneFocused => "pane.focused",
            Self::PaneCreated => "pane.created",
            Self::PaneClosed => "pane.closed",
            Self::PaneExited => "pane.exited",
            Self::PaneAgentDetected => "pane.agent_detected",
            Self::PaneAgentStatusChanged => "pane.agent_status_changed",
            Self::WorkspaceFocused => "workspace.focused",
        }
    }

    /// The underscored name that arrives on the wire.
    pub fn wire(self) -> &'static str {
        match self {
            Self::PaneUpdated => "pane_updated",
            Self::PaneFocused => "pane_focused",
            Self::PaneCreated => "pane_created",
            Self::PaneClosed => "pane_closed",
            Self::PaneExited => "pane_exited",
            Self::PaneAgentDetected => "pane_agent_detected",
            Self::PaneAgentStatusChanged => "pane_agent_status_changed",
            Self::WorkspaceFocused => "workspace_focused",
        }
    }

    /// Whether Herdr will only accept this subscription against one pane.
    ///
    /// Three kinds live in the pane-scoped family (`output_matched`,
    /// `agent_status_changed`, `scroll_changed`) and their params carry a
    /// required `pane_id`. Only one of them is worth a panel's attention, and a
    /// panel that watches every agent has no single pane to name — so this
    /// exists to turn a runtime `invalid request: missing field pane_id` into
    /// something [`Events::subscribe`] can refuse up front.
    ///
    /// Agent status is not lost by leaving it out: `pane.updated` carries
    /// `agent_status` on the pane it delivers.
    pub fn requires_pane_scope(self) -> bool {
        matches!(self, Self::PaneAgentStatusChanged)
    }

    pub fn from_wire(value: &str) -> Option<Self> {
        [
            Self::PaneUpdated,
            Self::PaneFocused,
            Self::PaneCreated,
            Self::PaneClosed,
            Self::PaneExited,
            Self::PaneAgentDetected,
            Self::PaneAgentStatusChanged,
            Self::WorkspaceFocused,
        ]
        .into_iter()
        .find(|kind| kind.wire() == value)
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct Event {
    pub event: String,
    #[serde(default)]
    pub data: serde_json::Value,
}

impl Event {
    pub fn kind(&self) -> Option<EventKind> {
        EventKind::from_wire(&self.event)
    }

    /// The pane this event concerns, when it concerns one.
    pub fn pane_id(&self) -> Option<&str> {
        self.data
            .get("pane")
            .and_then(|pane| pane.get("pane_id"))
            .or_else(|| self.data.get("pane_id"))
            .and_then(serde_json::Value::as_str)
    }
}

/// A subscription held open for the life of the plugin.
pub struct Events {
    reader: BufReader<UnixStream>,
}

impl Events {
    /// Open a session-wide subscription.
    ///
    /// Errors on a pane-scoped kind rather than letting Herdr reject the frame
    /// once the connection is already open — see
    /// [`EventKind::requires_pane_scope`].
    pub fn subscribe(kinds: &[EventKind]) -> Result<Self> {
        if let Some(scoped) = kinds.iter().find(|kind| kind.requires_pane_scope()) {
            bail!(
                "{} is pane-scoped and cannot be subscribed session-wide",
                scoped.subscription()
            );
        }
        let path = std::env::var_os("HERDR_SOCKET_PATH")
            .context("HERDR_SOCKET_PATH is unset — not running under Herdr")?;
        let mut stream = UnixStream::connect(&path).context("connecting to Herdr socket")?;

        let subscriptions: Vec<_> = kinds
            .iter()
            .map(|kind| serde_json::json!({ "type": kind.subscription() }))
            .collect();
        let request = serde_json::json!({
            "id": "events",
            "method": "events.subscribe",
            "params": { "subscriptions": subscriptions },
        });
        writeln!(stream, "{request}")?;
        stream.flush()?;

        Ok(Self {
            reader: BufReader::new(stream),
        })
    }
}

/// A blocking stream of events. `Iterator` rather than an inherent `next`
/// because that is exactly the shape — and it means `for event in events` reads
/// the way it behaves.
impl Iterator for Events {
    type Item = Event;

    /// Block for the next event, skipping the subscribe acknowledgement and
    /// anything that is not an event frame. `None` means Herdr hung up.
    fn next(&mut self) -> Option<Event> {
        let mut line = String::new();
        loop {
            line.clear();
            if self.reader.read_line(&mut line).ok()? == 0 {
                return None;
            }
            if line.trim().is_empty() {
                continue;
            }
            if let Ok(event) = serde_json::from_str::<Event>(&line)
                && event.kind().is_some()
            {
                return Some(event);
            }
        }
    }
}