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
//! Herdr's socket, typed.
//!
//! Newline-delimited JSON over `$HERDR_SOCKET_PATH`. Two shapes of use: a
//! request/response [`Client`] for one-shot calls, and [`Events`] which holds a
//! connection open and yields events as they arrive.
//!
//! Deliberately hand-written rather than generated from `herdr api schema
//! --json`: plugins touch a dozen of the 89 methods, and a generated surface
//! would be mostly dead code that still has to compile.

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

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

pub mod cwd;
pub mod events;
pub mod model;
pub mod subagents;

pub use cwd::{Cwd, CwdSource};
pub use events::{Event, EventKind, Events};
pub use model::{Agent, AgentSession, Pane, PluginContext};
pub use subagents::{Subagent, SubagentRoster, SubagentStatus};

fn socket_path() -> Result<PathBuf> {
    std::env::var_os("HERDR_SOCKET_PATH")
        .map(PathBuf::from)
        .context("HERDR_SOCKET_PATH is unset — not running under Herdr")
}

/// One request, one response, one connection — Herdr's rule, not a choice.
///
/// ▲ Measured against 0.7.5: the server answers the **first** request on a
/// connection and then sends FIN. A second request on the same stream is never
/// answered. So this holds the socket path, not a stream, and dials afresh per
/// [`Client::call`]; a long-lived `Client` is fine, a long-lived connection is
/// not. (`events.subscribe` is the exception — see [`Events`].)
pub struct Client {
    path: PathBuf,
    seq: u64,
}

#[derive(Deserialize)]
struct Envelope {
    id: Option<String>,
    result: Option<serde_json::Value>,
    error: Option<ErrorBody>,
}

#[derive(Deserialize)]
struct ErrorBody {
    message: Option<String>,
}

impl Client {
    /// Resolve the socket, and prove it is reachable before any caller commits
    /// to a plan that depends on it.
    pub fn connect() -> Result<Self> {
        let path = socket_path()?;
        UnixStream::connect(&path)
            .with_context(|| format!("connecting to Herdr socket at {}", path.display()))?;
        Ok(Self { path, seq: 0 })
    }

    /// Send `method` with `params` and decode the result as `T`.
    ///
    /// Herdr answers a well-formed request it dislikes with an error response.
    /// It hangs up without a word only when params fail to deserialize, so a
    /// clean EOF here means the request was built wrong — not that the server
    /// is unhealthy. Saying so beats a bare "connection closed".
    pub fn call<T: DeserializeOwned>(
        &mut self,
        method: &str,
        params: serde_json::Value,
    ) -> Result<T> {
        let mut stream = UnixStream::connect(&self.path)
            .with_context(|| format!("connecting to Herdr socket for {method}"))?;
        let mut reader = BufReader::new(stream.try_clone()?);

        self.seq += 1;
        let id = self.seq.to_string();
        let request = serde_json::json!({ "id": &id, "method": method, "params": params });
        writeln!(stream, "{request}").with_context(|| format!("sending {method}"))?;
        stream.flush()?;

        let mut line = String::new();
        loop {
            line.clear();
            if reader.read_line(&mut line)? == 0 {
                bail!("{method}: connection closed with no response — params rejected");
            }
            if line.trim().is_empty() {
                continue;
            }
            let envelope: Envelope = serde_json::from_str(&line)
                .with_context(|| format!("decoding response to {method}"))?;
            if envelope.id.as_deref() != Some(id.as_str()) {
                continue;
            }
            if let Some(error) = envelope.error {
                return Err(anyhow!(
                    "{method}: {}",
                    error.message.unwrap_or_else(|| "request failed".into())
                ));
            }
            let result = envelope.result.unwrap_or(serde_json::Value::Null);
            return serde_json::from_value(result)
                .with_context(|| format!("decoding result of {method}"));
        }
    }
}

/// Send `method` and do not wait to be told it worked.
///
/// For callers on a latency budget that have nothing to do with the answer — a
/// hook process, where every millisecond is a millisecond the agent's turn is
/// blocked. One connect, one write, return; the reply is never read.
///
/// Safe because a `SOCK_STREAM` write that fits the socket buffer is already
/// the server's to read: closing this end queues a FIN *behind* the bytes, so
/// the server sees the request and then EOF, never a truncated request. What is
/// given up is the error response — a rejected request fails silently. Use
/// [`Client::call`] whenever the outcome matters.
pub fn notify(method: &str, params: serde_json::Value) -> Result<()> {
    let path = socket_path()?;
    let mut stream = UnixStream::connect(&path)
        .with_context(|| format!("connecting to Herdr socket at {}", path.display()))?;
    let request = serde_json::json!({ "id": "1", "method": method, "params": params });
    writeln!(stream, "{request}").with_context(|| format!("sending {method}"))?;
    stream.flush().with_context(|| format!("flushing {method}"))
}

/// The invocation context Herdr passes to a plugin as JSON in the environment.
pub fn plugin_context() -> PluginContext {
    std::env::var("HERDR_PLUGIN_CONTEXT_JSON")
        .ok()
        .and_then(|raw| serde_json::from_str(&raw).ok())
        .unwrap_or_default()
}

/// The Herdr binary, as Herdr itself reports it.
///
/// Never a bare `"herdr"` off `PATH`: plugin processes inherit whatever
/// environment the server had, which need not include one.
pub fn herdr_bin() -> Result<PathBuf> {
    std::env::var_os("HERDR_BIN_PATH")
        .map(PathBuf::from)
        .context("HERDR_BIN_PATH is unset — not running under Herdr")
}