返回 CodeWhale
herdr.rs
根目录 / crates / tui / src / tui / herdr.rs
1 //! Herdr agent-state reporting for the Codewhale TUI.
2 //!
3 //! Inside a Herdr pane (`HERDR_ENV=1` plus `HERDR_PANE_ID`, `HERDR_BIN_PATH`
4 //! and `HERDR_SOCKET_PATH`) Codewhale reports its state (`idle` / `working` /
5 //! `blocked`), the command that reopens the current session, and releases the
6 //! pane when the user quits. See <https://herdr.dev/docs/add-herdr-support/>.
7 //!
8 //! Reports run on one dedicated background thread that keeps only the latest
9 //! pending report and bounds every CLI call, so Herdr can never slow down or
10 //! break the TUI. Outside Herdr every entry point is a no-op.
11 //!
12 //! Known limitation: a hard abort (panic hook or fatal-signal path) skips
13 //! [`release`]; Herdr's own idle-prompt safety net then clears the pane.
14
15 use std::process::{Command, ExitStatus, Stdio};
16 use std::sync::atomic::{AtomicBool, Ordering};
17 use std::sync::{Arc, Condvar, Mutex, OnceLock};
18 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
19
20 use crate::tui::underwater::ShellPhase;
21
22 /// Stable integration id. Must not start with `herdr:`.
23 const SOURCE: &str = "codewhale";
24 /// Agent name shown in Herdr's sidebar and `herdr agent list`.
25 const AGENT: &str = "codewhale";
26 /// Upper bound on a single Herdr CLI call.
27 const COMMAND_TIMEOUT: Duration = Duration::from_secs(2);
28 /// Herdr's resume argv limits.
29 const MAX_RESUME_ARGS: usize = 64;
30 const MAX_RESUME_BYTES: usize = 8 * 1024;
31 /// Exit code clap-based CLIs such as Herdr use for argument/usage errors.
32 const USAGE_ERROR_EXIT_CODE: i32 = 2;
33
34 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
35 pub enum AgentState {
36 Idle,
37 Working,
38 Blocked,
39 }
40
41 impl AgentState {
42 fn as_str(self) -> &'static str {
43 match self {
44 Self::Idle => "idle",
45 Self::Working => "working",
46 Self::Blocked => "blocked",
47 }
48 }
49 }
50
51 /// Map the TUI's perceptual phase onto Herdr's semantic state. `Typing` is the
52 /// user drafting while the agent waits, so it reports `idle`.
53 #[must_use]
54 pub fn state_for_phase(phase: ShellPhase) -> AgentState {
55 match phase {
56 ShellPhase::Approval | ShellPhase::Waiting => AgentState::Blocked,
57 ShellPhase::Working | ShellPhase::Verifying => AgentState::Working,
58 ShellPhase::Idle | ShellPhase::Typing | ShellPhase::Done | ShellPhase::Failed => {
59 AgentState::Idle
60 }
61 }
62 }
63
64 /// A state report plus, when known, the session that `resume_argv` reopens.
65 #[derive(Debug, Clone, PartialEq, Eq)]
66 struct StateReport {
67 state: AgentState,
68 session_id: Option<String>,
69 resume_argv: Option<Vec<String>>,
70 }
71
72 #[derive(Debug, Clone, PartialEq, Eq)]
73 struct HerdrEnv {
74 bin: String,
75 pane_id: String,
76 }
77
78 impl HerdrEnv {
79 fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Option<Self> {
80 let non_empty = |key: &str| get(key).filter(|value| !value.trim().is_empty());
81 if non_empty("HERDR_ENV").as_deref() != Some("1") {
82 return None;
83 }
84 // The socket must exist for the CLI to reach Herdr; require it as the
85 // docs do, even though we talk to Herdr through its binary.
86 non_empty("HERDR_SOCKET_PATH")?;
87 Some(Self {
88 bin: non_empty("HERDR_BIN_PATH")?,
89 pane_id: non_empty("HERDR_PANE_ID")?,
90 })
91 }
92 }
93
94 enum Job {
95 Report(StateReport),
96 Release,
97 }
98
99 #[derive(Default)]
100 struct Slot {
101 pending: Option<Job>,
102 released: bool,
103 done: bool,
104 }
105
106 struct Reporter {
107 slot: Arc<(Mutex<Slot>, Condvar)>,
108 last_submitted: Mutex<Option<StateReport>>,
109 }
110
111 static REPORTER: OnceLock<Option<Reporter>> = OnceLock::new();
112 static LAST_SEQ: Mutex<u64> = Mutex::new(0);
113 /// Set once Herdr rejects a report carrying a resume command. Herdr before
114 /// 0.9.2 fails the whole report with a usage error on the `--` resume
115 /// separator, so after that we keep reporting state without it.
116 static RESUME_UNSUPPORTED: AtomicBool = AtomicBool::new(false);
117
118 fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
119 mutex.lock().unwrap_or_else(|e| e.into_inner())
120 }
121
122 fn reporter() -> Option<&'static Reporter> {
123 REPORTER
124 .get_or_init(|| {
125 let env = HerdrEnv::from_lookup(|key| std::env::var(key).ok())?;
126 let slot = Arc::new((Mutex::new(Slot::default()), Condvar::new()));
127 let worker_slot = Arc::clone(&slot);
128 let spawned = std::thread::Builder::new()
129 .name("herdr-reporter".into())
130 .spawn(move || {
131 // The CLI call is defined inside the dedicated thread's
132 // closure so its blocking wait never lands on a runtime
133 // worker (scripts/check-blocking-calls-budget.py).
134 let run = |args: &[String]| -> Option<ExitStatus> {
135 let child = Command::new(&env.bin)
136 .args(args)
137 .stdin(Stdio::null())
138 .stdout(Stdio::null())
139 .stderr(Stdio::null())
140 .spawn();
141 let mut child = match child {
142 Ok(child) => child,
143 Err(error) => {
144 tracing::warn!(target: "herdr", %error, "could not run the Herdr binary");
145 return None;
146 }
147 };
148 let deadline = Instant::now() + COMMAND_TIMEOUT;
149 loop {
150 match child.try_wait() {
151 Ok(Some(status)) => return Some(status),
152 Ok(None) if Instant::now() < deadline => {
153 std::thread::sleep(Duration::from_millis(10));
154 }
155 _ => {
156 let _ = child.kill();
157 let _ = child.wait();
158 tracing::warn!(target: "herdr", "the Herdr report timed out");
159 return None;
160 }
161 }
162 }
163 };
164 worker_loop(&env, &worker_slot, &run);
165 });
166 if let Err(error) = spawned {
167 tracing::warn!(target: "herdr", %error, "could not start the Herdr reporter thread");
168 return None;
169 }
170 Some(Reporter {
171 slot,
172 last_submitted: Mutex::new(None),
173 })
174 })
175 .as_ref()
176 }
177
178 /// Report the current phase and session. Cheap enough for every UI tick:
179 /// outside Herdr it returns immediately, and unchanged state is dropped
180 /// without allocating. A newer report replaces one that has not been sent.
181 pub fn sync(phase: ShellPhase, session_id: Option<&str>) {
182 let Some(reporter) = reporter() else {
183 return;
184 };
185 let state = state_for_phase(phase);
186 let report = {
187 let mut last = lock(&reporter.last_submitted);
188 if last
189 .as_ref()
190 .is_some_and(|last| last.state == state && last.session_id.as_deref() == session_id)
191 {
192 return;
193 }
194 let report = StateReport {
195 state,
196 session_id: session_id.map(str::to_owned),
197 resume_argv: session_id.and_then(resume_argv_for_session),
198 };
199 *last = Some(report.clone());
200 report
201 };
202 let (slot_lock, wake) = &*reporter.slot;
203 let mut slot = lock(slot_lock);
204 if slot.released {
205 return;
206 }
207 slot.pending = Some(Job::Report(report));
208 wake.notify_one();
209 }
210
211 /// Release the pane because the user is quitting. The worker sends the release
212 /// and this waits for it off the runtime, bounded by [`COMMAND_TIMEOUT`]. Do
213 /// not call this when Codewhale is about to replace itself in the pane, since
214 /// the same agent keeps running there.
215 pub async fn release() {
216 let Some(reporter) = reporter() else {
217 return;
218 };
219 let slot = Arc::clone(&reporter.slot);
220 {
221 let (slot_lock, wake) = &*slot;
222 let mut guard = lock(slot_lock);
223 if guard.released {
224 return;
225 }
226 guard.released = true;
227 guard.pending = Some(Job::Release);
228 wake.notify_one();
229 }
230 let _ = tokio::task::spawn_blocking(move || {
231 let (slot_lock, wake) = &*slot;
232 let mut guard = lock(slot_lock);
233 while !guard.done {
234 let (next, timeout) = wake
235 .wait_timeout(guard, COMMAND_TIMEOUT)
236 .unwrap_or_else(|e| e.into_inner());
237 guard = next;
238 if timeout.timed_out() {
239 return;
240 }
241 }
242 })
243 .await;
244 }
245
246 fn worker_loop(
247 env: &HerdrEnv,
248 slot: &Arc<(Mutex<Slot>, Condvar)>,
249 run: &impl Fn(&[String]) -> Option<ExitStatus>,
250 ) {
251 let (slot_lock, wake) = &**slot;
252 loop {
253 let job = {
254 let mut guard = lock(slot_lock);
255 loop {
256 if guard.done {
257 return;
258 }
259 if let Some(job) = guard.pending.take() {
260 break job;
261 }
262 guard = wake.wait(guard).unwrap_or_else(|e| e.into_inner());
263 }
264 };
265 match job {
266 Job::Report(mut report) => {
267 if RESUME_UNSUPPORTED.load(Ordering::Relaxed) {
268 report.resume_argv = None;
269 }
270 let status = run(&report_args(&env.pane_id, &report, next_seq()));
271 // Only a usage error on a report that carried a resume command
272 // means "this Herdr predates resume". Timeouts and other
273 // failures are retried naturally by the next state change and
274 // must not disable resume.
275 if !(is_usage_error(status) && resume_command(&report).is_some()) {
276 continue;
277 }
278 report.resume_argv = None;
279 let retry = run(&report_args(&env.pane_id, &report, next_seq()));
280 if retry.is_some_and(|status| status.success()) {
281 RESUME_UNSUPPORTED.store(true, Ordering::Relaxed);
282 tracing::info!(
283 target: "herdr",
284 "this Herdr rejects resume commands (needs 0.9.2+); reporting state only"
285 );
286 }
287 }
288 Job::Release => {
289 run(&release_args(&env.pane_id, next_seq()));
290 lock(slot_lock).done = true;
291 wake.notify_all();
292 return;
293 }
294 }
295 }
296 }
297
298 fn is_usage_error(status: Option<ExitStatus>) -> bool {
299 status.and_then(|status| status.code()) == Some(USAGE_ERROR_EXIT_CODE)
300 }
301
302 /// The resume command [`report_args`] sends after `--`, if any. Herdr only
303 /// accepts one alongside a session id, and only when it passes validation.
304 fn resume_command(report: &StateReport) -> Option<&Vec<String>> {
305 report.session_id.as_ref()?;
306 report
307 .resume_argv
308 .as_ref()
309 .filter(|argv| valid_resume_argv(argv))
310 }
311
312 /// Strictly increasing across reports, sessions, and restarts: wall-clock
313 /// microseconds, bumped past the previous value if the clock stalls.
314 fn next_seq() -> u64 {
315 let now = SystemTime::now()
316 .duration_since(UNIX_EPOCH)
317 .map(|d| d.as_micros() as u64)
318 .unwrap_or(0);
319 let mut last = lock(&LAST_SEQ);
320 *last = now.max(last.saturating_add(1));
321 *last
322 }
323
324 fn report_args(pane_id: &str, report: &StateReport, seq: u64) -> Vec<String> {
325 let mut args: Vec<String> = [
326 "pane",
327 "report-agent",
328 pane_id,
329 "--source",
330 SOURCE,
331 "--agent",
332 AGENT,
333 "--state",
334 ]
335 .iter()
336 .map(|s| s.to_string())
337 .collect();
338 args.push(report.state.as_str().to_string());
339 args.push("--seq".to_string());
340 args.push(seq.to_string());
341 if let Some(session_id) = report.session_id.as_deref() {
342 args.push("--agent-session-id".to_string());
343 args.push(session_id.to_string());
344 if let Some(argv) = resume_command(report) {
345 args.push("--".to_string());
346 args.extend(argv.iter().cloned());
347 }
348 }
349 args
350 }
351
352 fn release_args(pane_id: &str, seq: u64) -> Vec<String> {
353 [
354 "pane",
355 "release-agent",
356 pane_id,
357 "--source",
358 SOURCE,
359 "--agent",
360 AGENT,
361 "--seq",
362 ]
363 .iter()
364 .map(|s| s.to_string())
365 .chain(std::iter::once(seq.to_string()))
366 .collect()
367 }
368
369 /// Herdr rejects resume commands whose first word is a path, that contain an
370 /// apostrophe or control character, or that exceed 64 args / 8 KiB.
371 fn valid_resume_argv(argv: &[String]) -> bool {
372 let Some(program) = argv.first() else {
373 return false;
374 };
375 if program.is_empty() || program.contains('/') || program.contains('\\') {
376 return false;
377 }
378 if argv.len() > MAX_RESUME_ARGS {
379 return false;
380 }
381 let total: usize = argv.iter().map(|arg| arg.len()).sum::<usize>() + argv.len();
382 if total > MAX_RESUME_BYTES {
383 return false;
384 }
385 argv.iter()
386 .all(|arg| !arg.contains('\'') && !arg.chars().any(char::is_control))
387 }
388
389 /// Command that reopens `session_id` from the pane's working directory. The
390 /// model, provider and permission posture live with the saved session.
391 fn resume_argv_for_session(session_id: &str) -> Option<Vec<String>> {
392 let argv = vec![
393 "codewhale".to_string(),
394 "resume".to_string(),
395 session_id.to_string(),
396 ];
397 valid_resume_argv(&argv).then_some(argv)
398 }
399
399 lines RUST