1use 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
35pub 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 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 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
117pub 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
137pub 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
145pub 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}