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
//! The in-process subagents running inside one agent.
//!
//! Herdr sees panes and processes. A Claude session's teammates are neither —
//! they live inside a single agent, so `pane.list` cannot see them and nor can
//! anything else Herdr exposes. That asymmetry is the whole reason a panel is
//! worth having: it can show what the multiplexer structurally cannot.
//!
//! ▲ **The roster travels as a path, not a payload.** Measured against 0.7.5,
//! every string `pane.report_metadata` accepts is silently truncated to 80
//! characters — tokens, `title` and `state_labels` alike — and the write still
//! returns `ok`. A write takes at most 16 tokens; a pane accumulates 32 across
//! sources. So a JSON array cannot be carried in a token, and sharding one
//! across the remaining keys would be both fragile and too small: a single
//! `subject` can exceed 80 characters on its own.
//!
//! A filesystem path fits 80 characters comfortably, and it is the shape Herdr
//! already uses for exactly this problem — `agent_session.value` is a transcript
//! *path* for pi and omp. The writer owns the file and updates it from Claude's
//! `SubagentStart` / `SubagentStop` / `TeammateIdle` / `TaskCreated` /
//! `TaskCompleted` hooks; the reader watches it.
//!
//! Writer and reader share this module so the two cannot drift, the way
//! [`crate::cwd::AGENT_CWD_TOKEN`] is shared.

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::model::Pane;

/// The metadata key whose value is an absolute path to a [`SubagentRoster`]
/// JSON file.
///
/// Prefixed because `Pane::tokens` is one flat map shared by every plugin.
pub const SUBAGENT_ROSTER_TOKEN: &str = "vsh-subagents";

/// The schema version the reader understands.
///
/// Present so a reader can refuse a roster it does not understand instead of
/// guessing. Bump it when a change is not backwards compatible; adding an
/// optional field is not.
pub const ROSTER_VERSION: u32 = 1;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SubagentStatus {
    /// Has a task and has not gone idle.
    Working,
    /// `TeammateIdle` — alive, waiting.
    Idle,
    /// `SubagentStop`, or `TaskCompleted` with nothing after it.
    Done,
    #[default]
    Unknown,
}

impl SubagentStatus {
    /// The same vocabulary Herdr uses for `agent_status`, so a panel can render
    /// a subagent row and an agent row with one function.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Working => "working",
            Self::Idle => "idle",
            Self::Done => "done",
            Self::Unknown => "unknown",
        }
    }
}

/// One teammate inside an agent.
///
/// Every field but `name` is optional: the hooks do not all carry the same
/// payload, and a roster that has a name and nothing else is still worth
/// showing. A reader must not require anything it was not promised.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Subagent {
    /// `teammate_name`. The display name, and the only required field.
    pub name: String,
    /// `agent_id`. Stable across a subagent's life, where the hook provides it —
    /// which makes it the better key for retained state than the name.
    pub id: Option<String>,
    /// `agent_type`.
    pub kind: Option<String>,
    /// `task_subject`. The line under the name.
    pub subject: Option<String>,
    pub status: SubagentStatus,
    /// For an elapsed-time display. Milliseconds since the Unix epoch, not a
    /// duration, so a reader can render elapsed time without the writer having
    /// to keep updating it.
    pub started_unix_ms: Option<u64>,
    /// Tokens consumed, when known.
    pub tokens: Option<u64>,
    /// ▲ Where this subagent is working, when it is **not** where its parent
    /// is.
    ///
    /// A subagent can be launched with worktree isolation, genuinely working in
    /// a different directory from the agent that spawned it. No OS-level signal
    /// shows this — the parent process never moves — so the parent's
    /// `vsh-cwd` is the *wrong* answer for such a child. That is why
    /// [`crate::CwdSource::SubagentReported`] outranks it.
    ///
    /// ▲ **Launch directory, not live.** The writer takes it from the record
    /// Claude keeps when a teammate joins, and nothing updates that record on a
    /// `cd`. Contrast [`SubagentRoster::cwd`] one level up, which is live because
    /// it comes from the hook that fires on the change. A reader surfacing
    /// provenance should not present the two as equally current.
    pub cwd: Option<String>,
}

impl Subagent {
    /// This subagent's own directory, if it reported one.
    pub fn working_dir(&self) -> Option<&Path> {
        self.cwd
            .as_deref()
            .filter(|value| !value.is_empty())
            .map(Path::new)
    }

    /// The stable identity to file retained state under: the id where the hook
    /// gave one, else the name.
    pub fn key(&self) -> &str {
        self.id
            .as_deref()
            .filter(|value| !value.is_empty())
            .unwrap_or(&self.name)
    }
}

/// What the writer publishes and the reader watches.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct SubagentRoster {
    pub version: u32,
    pub updated_unix_ms: u64,
    pub subagents: Vec<Subagent>,
    /// Where the **agent itself** is, as of this roster.
    ///
    /// Mirrors [`Subagent::cwd`] one level up: "here is where the agent is, and
    /// here is where each of its teammates is".
    ///
    /// Unlike [`Subagent::cwd`], this one is **live**: it comes from the hook
    /// payload that reports the change, so it moves when the session moves.
    ///
    /// ▲ This is a *better* source than the [`crate::cwd::AGENT_CWD_TOKEN`] it
    /// duplicates, and the reason is the 80-character cap Herdr silently applies
    /// to every metadata string. A worktree path longer than that truncates in a
    /// token into a directory that does not exist, and the write still answers
    /// `ok`. In a file it does not truncate at all. So when a roster carries this,
    /// it wins over the token — same provenance, no length limit.
    ///
    /// Absent rather than `null` when there is none: the writer's contract is
    /// "no directory means no key", so a reader never has to tell a missing
    /// value from an explicit null.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
}

impl SubagentRoster {
    /// The agent's own directory, when the roster carries one.
    pub fn working_dir(&self) -> Option<&Path> {
        self.cwd
            .as_deref()
            .filter(|value| !value.is_empty())
            .map(Path::new)
    }

    /// Whether this roster is a version the reader was built for.
    pub fn understood(&self) -> bool {
        // Version 0 means the writer omitted the field, which only an older
        // writer would do; treat it as v1 rather than discarding a roster over
        // a missing integer.
        self.version == 0 || self.version <= ROSTER_VERSION
    }
}

/// The path a pane's roster lives at, if it has published one.
///
/// Deliberately does not read the file: this crate keeps filesystem work out of
/// the caller's hot path, and a panel wants to do the read on its own thread.
pub fn roster_path(pane: &Pane) -> Option<PathBuf> {
    pane.tokens
        .get(SUBAGENT_ROSTER_TOKEN)
        .and_then(Option::as_deref)
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_pane_with_no_token_has_no_roster() {
        assert_eq!(roster_path(&Pane::default()), None);
    }

    #[test]
    fn an_erased_or_empty_token_is_not_a_path() {
        let mut pane = Pane::default();
        pane.tokens.insert(SUBAGENT_ROSTER_TOKEN.into(), None);
        assert_eq!(roster_path(&pane), None);
        pane.tokens
            .insert(SUBAGENT_ROSTER_TOKEN.into(), Some(String::new()));
        assert_eq!(roster_path(&pane), None);
    }

    #[test]
    fn the_token_is_read_as_a_path() {
        let mut pane = Pane::default();
        pane.tokens.insert(
            SUBAGENT_ROSTER_TOKEN.into(),
            Some("/Users/operator/.claude/herdr/subagents/wA-p1.json".into()),
        );
        assert_eq!(
            roster_path(&pane),
            Some(PathBuf::from("/Users/operator/.claude/herdr/subagents/wA-p1.json"))
        );
    }

    /// The pointer has to fit what Herdr will actually store. A realistic path
    /// is well inside 80 characters; this is here so a future scheme that is
    /// not gets caught by a test rather than by silent truncation.
    #[test]
    fn a_realistic_roster_path_fits_the_eighty_character_token_limit() {
        let path = format!(
            "{}/.claude/herdr/subagents/w65378006dc6cb1-p1.json",
            "/Users/operator"
        );
        assert!(path.len() <= 80, "{} chars: {path}", path.len());
    }

    #[test]
    fn a_roster_survives_a_round_trip() {
        let roster = SubagentRoster {
            version: ROSTER_VERSION,
            updated_unix_ms: 1_785_000_000_000,
            subagents: vec![Subagent {
                name: "explorer".into(),
                id: Some("a1b2".into()),
                kind: Some("general-purpose".into()),
                subject: Some("Build agent-aware explorer".into()),
                status: SubagentStatus::Working,
                started_unix_ms: Some(1_785_000_000_000),
                tokens: Some(120_000),
                cwd: Some("/repo/_worktrees/explorer".into()),
            }],
            cwd: Some("/repo".into()),
        };
        let back: SubagentRoster =
            serde_json::from_str(&serde_json::to_string(&roster).unwrap()).unwrap();
        assert_eq!(back.subagents[0].name, "explorer");
        assert_eq!(back.subagents[0].status, SubagentStatus::Working);
        assert_eq!(
            back.subagents[0].working_dir(),
            Some(Path::new("/repo/_worktrees/explorer"))
        );
    }

    /// The writer sends what its hooks happen to carry, which is often only a
    /// name. Requiring more would mean discarding a usable roster.
    #[test]
    fn a_roster_with_only_names_still_parses() {
        let roster: SubagentRoster =
            serde_json::from_str(r#"{"subagents":[{"name":"release"}]}"#).unwrap();
        assert!(roster.understood());
        assert_eq!(roster.subagents[0].name, "release");
        assert_eq!(roster.subagents[0].status, SubagentStatus::Unknown);
        assert_eq!(roster.subagents[0].working_dir(), None);
        // With no id, the name is the identity.
        assert_eq!(roster.subagents[0].key(), "release");
    }

    #[test]
    fn an_id_is_preferred_over_a_name_as_the_state_key() {
        let subagent = Subagent {
            name: "release".into(),
            id: Some("a9".into()),
            ..Subagent::default()
        };
        assert_eq!(subagent.key(), "a9");
    }

    #[test]
    fn a_roster_from_a_newer_writer_is_refused_rather_than_guessed_at() {
        let roster = SubagentRoster {
            version: ROSTER_VERSION + 1,
            ..SubagentRoster::default()
        };
        assert!(!roster.understood());
    }
}