SLOPSHOPPER

herdr

Drive the herdr terminal workspace manager: panes, tabs, workspaces, and sibling coding agents

processtimer
★ 18v?MITupdated 2026-10-18bendrucker/claude/plugins/herdr
A shopper browsing a rack in a slop shop
README

Herdr

Drive the herdr terminal workspace manager from a session running inside it.

Contents

  • Skill: herdr drives workspaces, tabs, and panes, and hands whole tasks to coding agents running in other panes
  • Mod: register.ts publishes the session's subagents, teammates, and branch as metadata tokens on its herdr pane

Mod Setup

The mod acts only in an interactive session inside a herdr pane (HERDR_ENV=1). Elsewhere it does nothing. It depends on the mod-events plugin, which logs each herdr call's exit code, stderr, and duration as a herdr.call event. herdr's own integration (herdr integration install) keeps reporting the agent's identity and lifecycle. The mod adds what herdr cannot see from outside the session, as tokens from source bendrucker:herdr:

TokenValue
subagents↳ and the count of live subagents
teammates⇄ and the count of live teammates
agents_waiting? and the count held on background work or a plan approval
agents_idle· and the count of teammates between turns
branchthe session directory's current git branch

A token is cleared while its count is zero and when the session exits. herdr shows a custom token only where config.toml names it in a sidebar row:

[ui.sidebar.agents.rows_by_agent]
claude = [
  ["state_icon", "agent", "$subagents", "$teammates", { token = "$agents_waiting", fg = "#e0405a" }, { token = "$agents_idle", dim = true }],
  [{ token = "$branch", dim = true }],
]

Tests

bun test plugins/herdr runs the skill's bun tests, and bun scripts/mod-test.ts herdr runs the mod's.

Source 1 files
mod/register.ts 254 lines
1import type { AgentInfo, EngineInterface, On } from "claude-code";
2
3const MOD = "herdr";
4const SOURCE = "bendrucker:herdr";
5
6// A /clear or /resume ends the conversation, not the process, and no
7// session.start follows it.
8const CONTINUING = new Set(["clear", "resume"]);
9
10const ACTIVE = new Set(["pending", "running", "waiting", "idle"]);
11
12// Subagent and teammate events trigger a refresh, and while an agent is counted
13// the counts are also re-read on a timer in case one of those events is missed.
14const POLL_MS = 10_000;
15
16// session.end shares 1.5 seconds across every hook.
17const END_TIMEOUT_MS = 1000;
18
19// A herdr that cannot start (missing binary, hung past the timeout) would
20// otherwise be retried on every event and poll for the rest of the session.
21const SUSPEND_AFTER = 3;
22
23type Tokens = Record<string, string>;
24
25interface Pane {
26  bin: string;
27  id: string;
28}
29
30interface Beacon {
31  pane: Pane | undefined;
32  reported: Tokens;
33  inFlight: Promise<void> | undefined;
34  requests: number;
35  seq: number;
36  spawnFailures: number;
37  poll: { cancel: () => void } | undefined;
38}
39
40function count(agents: AgentInfo[], glyph: string, keep: (agent: AgentInfo) => boolean): string {
41  const n = agents.filter(keep).length;
42  return n === 0 ? "" : `${glyph}${n}`;
43}
44
45export function tokensOf(agents: AgentInfo[], branch: string): Tokens {
46  const active = agents.filter((agent) => ACTIVE.has(agent.status));
47  return {
48    subagents: count(active, "↳", (agent) => agent.teammateId === undefined),
49    teammates: count(active, "⇄", (agent) => agent.teammateId !== undefined),
50    agents_waiting: count(active, "?", (agent) => agent.status === "waiting"),
51    agents_idle: count(active, "·", (agent) => agent.status === "idle"),
52    branch,
53  };
54}
55
56const TOKEN_NAMES = Object.keys(tokensOf([], ""));
57
58// herdr drops a report whose seq is not above the last one, so the seq is taken
59// before any await and a slow report cannot land over a newer one.
60async function herdr(
61  $: EngineInterface,
62  beacon: Beacon,
63  pane: Pane,
64  args: string[],
65  timeoutMs = 3000,
66): Promise<boolean> {
67  beacon.seq += 1;
68  const argv = [
69    pane.bin,
70    "pane",
71    "report-metadata",
72    pane.id,
73    "--source",
74    SOURCE,
75    "--seq",
76    String(beacon.seq),
77    ...args,
78  ];
79  const startedAt = await $.clock.now();
80  const { exitCode, stderr } = await $.process
81    .run(argv, { timeoutMs })
82    .catch((error: unknown) => ({ exitCode: -1, stderr: String(error) }));
83  const ms = (await $.clock.now()) - startedAt;
84  const ok = exitCode === 0;
85  await $.modEvents.emit({
86    mod: MOD,
87    event: "herdr.call",
88    ok,
89    ms,
90    detail: { op: "report-metadata", exitCode, stderr: stderr.trim() },
91  });
92  beacon.spawnFailures = exitCode === -1 ? beacon.spawnFailures + 1 : 0;
93  if (beacon.spawnFailures === SUSPEND_AFTER) {
94    beacon.pane = undefined;
95    poll($, beacon, false);
96    void $.modEvents.emit({
97      mod: MOD,
98      event: "herdr.suspend",
99      ok: false,
100      detail: { suspended: true, spawnFailures: SUSPEND_AFTER },
101    });
102  }
103  return ok;
104}
105
106async function branchOf($: EngineInterface): Promise<string> {
107  try {
108    const { exitCode, stdout } = await $.process.run(["git", "branch", "--show-current"], {
109      timeoutMs: 1000,
110    });
111    return exitCode === 0 ? stdout.trim() : "";
112  } catch {
113    // A session outside git, or without git installed, has no branch to show.
114    return "";
115  }
116}
117
118async function publish($: EngineInterface, beacon: Beacon, tokens: Tokens): Promise<void> {
119  const args: string[] = [];
120  for (const [name, value] of Object.entries(tokens)) {
121    if ((beacon.reported[name] ?? "") === value) continue;
122    args.push(...(value === "" ? ["--clear-token", name] : ["--token", `${name}=${value}`]));
123  }
124  const pane = beacon.pane;
125  if (args.length === 0 || pane === undefined) return;
126  if (await herdr($, beacon, pane, args)) {
127    beacon.reported = Object.fromEntries(
128      Object.entries(tokens).filter(([, value]) => value !== ""),
129    );
130  }
131}
132
133async function drain($: EngineInterface, beacon: Beacon): Promise<void> {
134  const seen = beacon.requests;
135  try {
136    const [agents, branch] = await Promise.all([$.agent.list(), branchOf($)]);
137    const tokens = tokensOf(agents, branch);
138    await publish($, beacon, tokens);
139    poll($, beacon, tokens.subagents !== "" || tokens.teammates !== "");
140  } catch (error) {
141    void $.modEvents.emit({
142      mod: MOD,
143      event: "refresh",
144      ok: false,
145      detail: { error: String(error) },
146    });
147  }
148  if (beacon.requests !== seen && beacon.pane !== undefined) return drain($, beacon);
149  beacon.inFlight = undefined;
150}
151
152function poll($: EngineInterface, beacon: Beacon, hasAgents: boolean): void {
153  if (hasAgents && beacon.pane !== undefined) {
154    beacon.poll ??= $.clock.every(POLL_MS, () => {
155      refresh($, beacon);
156    });
157  } else {
158    beacon.poll?.cancel();
159    beacon.poll = undefined;
160  }
161}
162
163// Events arrive in bursts, so a refresh that lands mid-flight is counted and
164// the running one reads again rather than racing it.
165function refresh($: EngineInterface, beacon: Beacon): void {
166  if (beacon.pane === undefined) return;
167  beacon.requests += 1;
168  beacon.inFlight ??= drain($, beacon);
169}
170
171/**
172 * Publishes what herdr cannot see from outside the session as metadata tokens
173 * on the pane hosting it: its subagents and teammates, how many of them wait or
174 * sit idle, and the branch. Lifecycle stays with herdr's own integration.
175 */
176export function register(on: On): void {
177  const beacon: Beacon = {
178    pane: undefined,
179    reported: {},
180    inFlight: undefined,
181    requests: 0,
182    seq: 0,
183    spawnFailures: 0,
184    poll: undefined,
185  };
186
187  on("session.start", async ($, e, next) => {
188    const [env, id, bin, now] = await Promise.all([
189      $.env.get("HERDR_ENV"),
190      $.env.get("HERDR_PANE_ID"),
191      $.env.get("HERDR_BIN_PATH"),
192      $.clock.now(),
193    ]);
194    // Clock-based, so a restarted session's seqs stay above the last one's.
195    beacon.seq = Math.max(beacon.seq, now * 1000);
196    beacon.reported = {};
197    beacon.spawnFailures = 0;
198    const isHosted = env === "1" && id !== undefined && id !== "" && e.isInteractive;
199    beacon.pane = isHosted
200      ? { bin: bin === undefined || bin === "" ? "herdr" : bin, id }
201      : undefined;
202    void $.modEvents.emit({ mod: MOD, event: "session.start", detail: { isHosted } });
203    refresh($, beacon);
204    return next(e);
205  });
206
207  on("turn.start", ($, e, next) => {
208    refresh($, beacon);
209    return next(e);
210  });
211
212  on("turn.complete", ($, e, next) => {
213    refresh($, beacon);
214    return next(e);
215  });
216
217  on("classic.SubagentStart", ($, e, next) => {
218    refresh($, beacon);
219    return next(e);
220  }).catch(($, e, next) => next(e));
221
222  on("classic.SubagentStop", ($, e, next) => {
223    refresh($, beacon);
224    return next(e);
225  }).catch(($, e, next) => next(e));
226
227  on("classic.TeammateIdle", ($, e, next) => {
228    refresh($, beacon);
229    return next(e);
230  }).catch(($, e, next) => next(e));
231
232  on("session.end", async ($, e, next) => {
233    if (CONTINUING.has(e.reason)) {
234      refresh($, beacon);
235      return next(e);
236    }
237    // Not waiting on a refresh in flight: session.end has a short budget, and
238    // the clear's higher seq makes herdr drop that refresh if it lands later.
239    const pane = beacon.pane;
240    beacon.pane = undefined;
241    poll($, beacon, false);
242    if (pane !== undefined) {
243      await herdr(
244        $,
245        beacon,
246        pane,
247        TOKEN_NAMES.flatMap((name) => ["--clear-token", name]),
248        END_TIMEOUT_MS,
249      );
250    }
251    return next(e);
252  });
253}
254