Skip to main content

herdr_sdk/
lib.rs

1//! Herdr's socket, typed.
2//!
3//! Newline-delimited JSON over `$HERDR_SOCKET_PATH`. Two shapes of use: a
4//! request/response [`Client`] for one-shot calls, and [`Events`] which holds a
5//! connection open and yields events as they arrive.
6//!
7//! Deliberately hand-written rather than generated from `herdr api schema
8//! --json`: plugins touch a dozen of the 89 methods, and a generated surface
9//! would be mostly dead code that still has to compile.
10
11use std::io::{BufRead, BufReader, Write};
12use std::os::unix::net::UnixStream;
13use std::path::PathBuf;
14
15use anyhow::{Context as _, Result, anyhow, bail};
16use serde::Deserialize;
17use serde::de::DeserializeOwned;
18
19pub mod cwd;
20pub mod events;
21pub mod model;
22pub mod subagents;
23
24pub use cwd::{Cwd, CwdSource};
25pub use events::{Event, EventKind, Events};
26pub use model::{Agent, AgentSession, Pane, PluginContext};
27pub use subagents::{Subagent, SubagentRoster, SubagentStatus};
28
29fn socket_path() -> Result<PathBuf> {
30    std::env::var_os("HERDR_SOCKET_PATH")
31        .map(PathBuf::from)
32        .context("HERDR_SOCKET_PATH is unset — not running under Herdr")
33}
34
35/// One request, one response, one connection — Herdr's rule, not a choice.
36///
37/// ▲ Measured against 0.7.5: the server answers the **first** request on a
38/// connection and then sends FIN. A second request on the same stream is never
39/// answered. So this holds the socket path, not a stream, and dials afresh per
40/// [`Client::call`]; a long-lived `Client` is fine, a long-lived connection is
41/// not. (`events.subscribe` is the exception — see [`Events`].)
42pub struct Client {
43    path: PathBuf,
44    seq: u64,
45}
46
47#[derive(Deserialize)]
48struct Envelope {
49    id: Option<String>,
50    result: Option<serde_json::Value>,
51    error: Option<ErrorBody>,
52}
53
54#[derive(Deserialize)]
55struct ErrorBody {
56    message: Option<String>,
57}
58
59impl Client {
60    /// Resolve the socket, and prove it is reachable before any caller commits
61    /// to a plan that depends on it.
62    pub fn connect() -> Result<Self> {
63        let path = socket_path()?;
64        UnixStream::connect(&path)
65            .with_context(|| format!("connecting to Herdr socket at {}", path.display()))?;
66        Ok(Self { path, seq: 0 })
67    }
68
69    /// Send `method` with `params` and decode the result as `T`.
70    ///
71    /// Herdr answers a well-formed request it dislikes with an error response.
72    /// It hangs up without a word only when params fail to deserialize, so a
73    /// clean EOF here means the request was built wrong — not that the server
74    /// is unhealthy. Saying so beats a bare "connection closed".
75    pub fn call<T: DeserializeOwned>(
76        &mut self,
77        method: &str,
78        params: serde_json::Value,
79    ) -> Result<T> {
80        let mut stream = UnixStream::connect(&self.path)
81            .with_context(|| format!("connecting to Herdr socket for {method}"))?;
82        let mut reader = BufReader::new(stream.try_clone()?);
83
84        self.seq += 1;
85        let id = self.seq.to_string();
86        let request = serde_json::json!({ "id": &id, "method": method, "params": params });
87        writeln!(stream, "{request}").with_context(|| format!("sending {method}"))?;
88        stream.flush()?;
89
90        let mut line = String::new();
91        loop {
92            line.clear();
93            if reader.read_line(&mut line)? == 0 {
94                bail!("{method}: connection closed with no response — params rejected");
95            }
96            if line.trim().is_empty() {
97                continue;
98            }
99            let envelope: Envelope = serde_json::from_str(&line)
100                .with_context(|| format!("decoding response to {method}"))?;
101            if envelope.id.as_deref() != Some(id.as_str()) {
102                continue;
103            }
104            if let Some(error) = envelope.error {
105                return Err(anyhow!(
106                    "{method}: {}",
107                    error.message.unwrap_or_else(|| "request failed".into())
108                ));
109            }
110            let result = envelope.result.unwrap_or(serde_json::Value::Null);
111            return serde_json::from_value(result)
112                .with_context(|| format!("decoding result of {method}"));
113        }
114    }
115}
116
117/// Send `method` and do not wait to be told it worked.
118///
119/// For callers on a latency budget that have nothing to do with the answer — a
120/// hook process, where every millisecond is a millisecond the agent's turn is
121/// blocked. One connect, one write, return; the reply is never read.
122///
123/// Safe because a `SOCK_STREAM` write that fits the socket buffer is already
124/// the server's to read: closing this end queues a FIN *behind* the bytes, so
125/// the server sees the request and then EOF, never a truncated request. What is
126/// given up is the error response — a rejected request fails silently. Use
127/// [`Client::call`] whenever the outcome matters.
128pub fn notify(method: &str, params: serde_json::Value) -> Result<()> {
129    let path = socket_path()?;
130    let mut stream = UnixStream::connect(&path)
131        .with_context(|| format!("connecting to Herdr socket at {}", path.display()))?;
132    let request = serde_json::json!({ "id": "1", "method": method, "params": params });
133    writeln!(stream, "{request}").with_context(|| format!("sending {method}"))?;
134    stream.flush().with_context(|| format!("flushing {method}"))
135}
136
137/// The invocation context Herdr passes to a plugin as JSON in the environment.
138pub fn plugin_context() -> PluginContext {
139    std::env::var("HERDR_PLUGIN_CONTEXT_JSON")
140        .ok()
141        .and_then(|raw| serde_json::from_str(&raw).ok())
142        .unwrap_or_default()
143}
144
145/// The Herdr binary, as Herdr itself reports it.
146///
147/// Never a bare `"herdr"` off `PATH`: plugin processes inherit whatever
148/// environment the server had, which need not include one.
149pub fn herdr_bin() -> Result<PathBuf> {
150    std::env::var_os("HERDR_BIN_PATH")
151        .map(PathBuf::from)
152        .context("HERDR_BIN_PATH is unset — not running under Herdr")
153}