Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(macrod): native herdr integration — live Claude Code / Codex TUIs driven over ACP (#7075)
Wolf Mermelstein6337a4ac630b
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rsindex 84effdc699..5408102427 100644--- a/crates/agent_session/src/domain/model.rs+++ b/crates/agent_session/src/domain/model.rs@@ -18,6 +18,10 @@ pub use agent_fold::domain::model::{Author, AuthorKind, FoldEvent, MessageId, OwnedFoldEvent, TurnId,};+/// The `_meta` key on `session/new`, `session/load` and `session/resume`+/// whose string value is the [`AgentSessionId`] the ACP session serves.+pub const MACRO_AGENT_SESSION_META_KEY: &str = "macro.com/agentSessionId";+/// Identity of one harness participant, minted fresh at construction.////// A restarted process is a new replica: whatever the old identity claimed isdiff --git a/crates/agent_session/src/domain/session/session.rs b/crates/agent_session/src/domain/session/session.rsindex 7049e84440..600ae215e9 100644--- a/crates/agent_session/src/domain/session/session.rs+++ b/crates/agent_session/src/domain/session/session.rs@@ -23,7 +23,7 @@ use macro_user_id::user_id::MacroUserIdStr;use crate::PROTOCOL_VERSION;use crate::domain::error::AgentSessionError;-use crate::domain::model::AgentSessionId;+use crate::domain::model::{AgentSessionId, MACRO_AGENT_SESSION_META_KEY};use super::types::{CloseReason, Effect, Input, OutstandingPermission, PendingAction, PendingElicitation,@@ -636,7 +636,8 @@ impl<Token> SessionMachine<Token> {> {self.build_session_request(ResumeSessionRequest::new(session_id.clone(), self.workspace.clone())- .mcp_servers(self.mcp_servers.clone()),+ .mcp_servers(self.mcp_servers.clone())+ .meta(self.session_meta()),SessionOpening::Resume(session_id),)}@@ -650,11 +651,23 @@ impl<Token> SessionMachine<Token> {> {self.build_session_request(LoadSessionRequest::new(session_id.clone(), self.workspace.clone())- .mcp_servers(self.mcp_servers.clone()),+ .mcp_servers(self.mcp_servers.clone())+ .meta(self.session_meta()),SessionOpening::Load(session_id),)}+ /// Names the Macro session an ACP session belongs to, so a runtime that+ /// multiplexes sessions over one connection (macrod) can tell them apart.+ fn session_meta(&self) -> agent_client_protocol::schema::v1::Meta {+ let mut meta = agent_client_protocol::schema::v1::Meta::new();+ meta.insert(+ MACRO_AGENT_SESSION_META_KEY.to_owned(),+ serde_json::Value::String(self.id.to_string()),+ );+ meta+ }+fn build_initialize_request(&mut self,) -> std::result::Result<(RawJsonRpcMessage, RequestId), agent_client_protocol::Error> {@@ -684,7 +697,9 @@ impl<Token> SessionMachine<Token> {agent_client_protocol::Error,> {self.build_session_request(- NewSessionRequest::new(self.workspace.clone()).mcp_servers(self.mcp_servers.clone()),+ NewSessionRequest::new(self.workspace.clone())+ .mcp_servers(self.mcp_servers.clone())+ .meta(self.session_meta()),SessionOpening::New,)}diff --git a/crates/agent_session/src/domain/session/tests.rs b/crates/agent_session/src/domain/session/tests.rsindex 4fe558eaa9..aae2cc8c74 100644--- a/crates/agent_session/src/domain/session/tests.rs+++ b/crates/agent_session/src/domain/session/tests.rs@@ -1235,6 +1235,35 @@ fn session_new_carries_the_sessions_workspace() {assert_eq!(sent_cwds(&effects, "session/new"), ["/home/operator/code"]);}+#[test]+fn session_new_names_the_macro_session_in_meta() {+ let mut machine = SessionMachine::new(+ AgentSessionId::TEST_A,+ "/home/operator/code".to_owned(),+ Vec::new(),+ PermissionPolicy::AutoAccept,+ );+ machine.handle(acp_ready());+ let effects = machine.handle(initialized());++ let named: Vec<String> = effects+ .iter()+ .filter_map(|effect| match effect {+ Effect::Send {+ message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(request))),+ ..+ } if request.method.as_ref() == "session/new" => {+ let params = request.params.clone()?.into_value();+ params["_meta"][crate::domain::model::MACRO_AGENT_SESSION_META_KEY]+ .as_str()+ .map(str::to_owned)+ }+ _ => None,+ })+ .collect();+ assert_eq!(named, [AgentSessionId::TEST_A.to_string()]);+}+#[test]fn resume_carries_the_sessions_workspace() {let mut machine = SessionMachine::resume(diff --git a/crates/coding_agent_worker/Cargo.toml b/crates/coding_agent_worker/Cargo.tomlindex d2de0d9cb8..d4bfa31499 100644--- a/crates/coding_agent_worker/Cargo.toml+++ b/crates/coding_agent_worker/Cargo.toml@@ -42,7 +42,7 @@ serde_json = { workspace = true }shell-words = { workspace = true }strum = { workspace = true }thiserror = { workspace = true }-tokio = { workspace = true, features = ["macros", "process", "rt-multi-thread", "signal", "time"] }+tokio = { workspace = true, features = ["io-util", "macros", "net", "process", "rt-multi-thread", "signal", "time"] }tokio-retry = { workspace = true }tokio-util = { workspace = true, features = ["compat", "rt"] }tokio-tungstenite = { workspace = true }diff --git a/crates/coding_agent_worker/src/daemon.rs b/crates/coding_agent_worker/src/daemon.rsindex c49db5309a..a0f3ac87de 100644--- a/crates/coding_agent_worker/src/daemon.rs+++ b/crates/coding_agent_worker/src/daemon.rs@@ -37,20 +37,36 @@ impl Daemon {/// Returns once the client is built; the serving itself runs until/// [`Daemon::stop`] or the task fails.pub async fn start(- config: Config,+ mut config: Config,credentials: HarnessCredentials,_config_path: &Path,) -> rootcause::Result<Self> {let cancel = CancellationToken::new();let client = EventStreamClient::new(&config.macro_api, &credentials);let api = HarnessApi::new(&config.macro_api, &credentials);++ #[cfg(unix)]+ let herdr = start_herdr(&mut config, &credentials);+ #[cfg(unix)]+ let tap = herdr+ .as_ref()+ .map(|hub| std::sync::Arc::new(hub.tap()) as crate::harness::LineTap);+ #[cfg(not(unix))]+ let tap = None;+let runtime = Runtime::start(&config.macro_api,&credentials,config.harness.clone(),&config.workspace.path,+ tap,);let executor = Dispatcher::new(api, runtime, config.workspace.clone());+ #[cfg(unix)]+ let executor = match herdr {+ Some(hub) => executor.with_herdr(hub),+ None => executor,+ };tracing::info!(api = %config.macro_api.api_url,@@ -106,6 +122,34 @@ impl Daemon {}}+/// Inside herdr, the directory macrod was started from is the repository+/// every session works in, and each session gets a herdr window.+#[cfg(unix)]+fn start_herdr(config: &mut Config, credentials: &HarnessCredentials) -> Option<crate::herdr::Hub> {+ let herdr = crate::herdr::HerdrSession::detect()?;+ match std::env::current_dir() {+ Ok(cwd) => config.workspace.path = cwd,+ Err(error) => tracing::warn!(error = %error, "could not read the working directory"),+ }+ if crate::herdr::drives_herdr(&config.harness) {+ tracing::info!("herdr detected; the harness opens a herdr window per session");+ return None;+ }+ let api = HarnessApi::new(&config.macro_api, credentials);+ match crate::herdr::Hub::start(+ &herdr,+ api,+ &config.workspace.path,+ &config.macro_api.web_url,+ ) {+ Ok(hub) => Some(hub),+ Err(error) => {+ tracing::warn!(error = %error, "herdr detected but its window socket could not start");+ None+ }+ }+}+fn reconnect_delay(failures: u32) -> Duration {let secs = 1u64.checked_shl(failures.min(5)).unwrap_or(30).min(30);Duration::from_secs(secs)diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rsindex 2f88d6d399..49684a66e5 100644--- a/crates/coding_agent_worker/src/dispatch.rs+++ b/crates/coding_agent_worker/src/dispatch.rs@@ -3,6 +3,8 @@use agent_session::domain::model::AgentSessionId;use agent_session::inbound::axum_router::{CreateAgentSessionRequest, CreateSessionThread};+use macro_user_id::user_id::MacroUserIdStr;+use crate::config::Workspace;use crate::outbound::agent_session::{ApiError, HarnessApi};use crate::runtime::Runtime;@@ -24,6 +26,8 @@ pub struct Dispatcher {api: HarnessApi,runtime: Runtime,workspace: Workspace,+ #[cfg(unix)]+ herdr: Option<crate::herdr::Hub>,}impl Dispatcher {@@ -33,7 +37,36 @@ impl Dispatcher {api,runtime,workspace,+ #[cfg(unix)]+ herdr: None,+ }+ }++ /// Tell `hub` about every session this dispatcher opens or prompts, so+ /// its herdr windows can steer them as the right user.+ #[cfg(unix)]+ #[must_use]+ pub fn with_herdr(mut self, hub: crate::herdr::Hub) -> Self {+ self.herdr = Some(hub);+ self+ }++ fn created(&self, session: AgentSessionId, sender: &MacroUserIdStr<'static>) {+ #[cfg(unix)]+ if let Some(hub) = &self.herdr {+ hub.session_created(session, sender.clone());+ }+ #[cfg(not(unix))]+ let _ = (session, sender);+ }++ fn prompted(&self, session: AgentSessionId, sender: &MacroUserIdStr<'static>) {+ #[cfg(unix)]+ if let Some(hub) = &self.herdr {+ hub.owner_seen(session, sender.clone());}+ #[cfg(not(unix))]+ let _ = (session, sender);}}@@ -104,6 +137,7 @@ impl WorkExecutor for Dispatcher {session: Some(session),}) => {tracing::info!(%thread_id, %session, "thread already has a session; resuming it");+ self.prompted(session, &sender);self.runtime.ensure_connected().await@@ -118,6 +152,7 @@ impl WorkExecutor for Dispatcher {Err(error) => return Err(error.into()),};let session = AgentSessionId::new_from_uuid(created.session.id);+ self.created(session, &sender);self.runtime.ensure_connected().await@@ -155,6 +190,7 @@ impl WorkExecutor for Dispatcher {model: None,};self.api.create_session(&request, &sender).await?;+ self.created(session, &sender);// Be dialed in before the prompt the requester is about to// send arrives, so it lands on a runtime that is serving.self.runtime@@ -168,6 +204,7 @@ impl WorkExecutor for Dispatcher {sender,content,} => {+ self.prompted(session, &sender);self.runtime.ensure_connected().awaitdiff --git a/crates/coding_agent_worker/src/harness.rs b/crates/coding_agent_worker/src/harness.rsindex 23855ae582..297d919ae4 100644--- a/crates/coding_agent_worker/src/harness.rs+++ b/crates/coding_agent_worker/src/harness.rs@@ -2,12 +2,13 @@//! gateway channel.use std::path::Path;+use std::sync::Arc;use std::time::Duration;use crate::config::Harness;use crate::outbound::acp_probe::{ProbeError, ProbeSubprocess, probe_subprocess};use crate::outbound::acp_process::AcpProcess;-use agent_client_protocol::{Client, ConnectTo};+use agent_client_protocol::{Client, ConnectTo, LineDirection};use agent_runtime_protocol::domain::connection::{ConnectionError, ModelProbeHandler, RuntimeChannel, RuntimeConnection,};@@ -29,11 +30,16 @@ pub enum BridgeError {Harness(String),}-/// Spawn the harness in ACP mode and pump frames until either side ends.+/// Observes every line crossing the harness's stdio.+pub type LineTap = Arc<dyn Fn(&str, LineDirection) + Send + Sync>;++/// Spawn the harness in ACP mode and pump frames until either side ends,+/// handing every ACP line to `tap` when there is one.pub async fn bridge(harness: &Harness,cwd: &Path,channel: RuntimeChannel,+ tap: Option<LineTap>,) -> Result<(), BridgeError> {let probes = HarnessModelProbes {process: probe_process(harness, cwd),@@ -44,8 +50,11 @@ pub async fn bridge(.envs(harness.env.clone())// The wire tap: every ndjson line crossing the child's stdio, plus// its stderr. Enable with RUST_LOG=coding_agent_worker=trace.- .with_debug(|line, direction| {+ .with_debug(move |line, direction| {tracing::trace!(?direction, line, "acp line");+ if let Some(tap) = &tap {+ tap(line, direction);+ }});runtimediff --git a/crates/coding_agent_worker/src/harness/test.rs b/crates/coding_agent_worker/src/harness/test.rsindex da744a7a6a..b5e556bcfe 100644--- a/crates/coding_agent_worker/src/harness/test.rs+++ b/crates/coding_agent_worker/src/harness/test.rs@@ -31,6 +31,7 @@ async fn unspawnable_harness_reports_failure() {&harness("macro-no-such-harness-binary"),std::path::Path::new("/"),runtime,+ None,).await.expect_err("a harness that cannot be spawned must not look like success");@@ -50,7 +51,7 @@ async fn harness_that_exits_immediately_disconnects() {// `true` spawns cleanly and closes its stdio at once, which is the// shutdown path rather than the spawn-failure path above.- let _ = bridge(&harness("true"), std::path::Path::new("/"), runtime).await;+ let _ = bridge(&harness("true"), std::path::Path::new("/"), runtime, None).await;assert_eq!(events(service),@@ -65,7 +66,7 @@ async fn dropped_service_channel_does_not_panic_the_bridge() {// Announcing readiness into a closed channel is a failure to announce, not// a harness failure: nothing was ever spawned.- let error = bridge(&harness("true"), std::path::Path::new("/"), runtime)+ let error = bridge(&harness("true"), std::path::Path::new("/"), runtime, None).await.expect_err("announcing into a closed channel must fail");diff --git a/crates/coding_agent_worker/src/herdr.rs b/crates/coding_agent_worker/src/herdr.rsnew file mode 100644index 0000000000..5f4b6a32b9--- /dev/null+++ b/crates/coding_agent_worker/src/herdr.rs@@ -0,0 +1,96 @@+//! Native [herdr](https://herdr.dev) integration.+//!+//! Started from inside a herdr pane (herdr sets `HERDR_ENV=1`), macrod drives+//! the herdr session it lives in: every ACP session it serves opens its own+//! tab in macrod's workspace, rooted at the directory macrod was started+//! from. The tab runs `macrod herdr-pane`, a live terminal view of the session+//! fed from the harness's ACP wire, from which the session can be prompted,+//! interrupted, and have its permission requests answered. herdr's sidebar+//! shows each session as an agent that is working, blocked, or done.+//!+//! The harness still runs under macrod and every session still belongs to+//! Macro: windows steer through the same control API the web app uses.+//!+//! With `macrod herdr-acp` as the harness, the window instead hosts the real+//! Claude Code or Codex TUI, driven over ACP by that adapter (see+//! [`acp_agent`]).++pub(crate) mod acp_agent;+mod claude_log;+mod cli;+mod codex_log;+mod hub;+mod tap;+pub(crate) mod wire;++#[cfg(test)]+mod test;++use std::path::PathBuf;++pub(crate) use hub::Hub;++use crate::config::Harness;++/// Whether the harness is `macrod herdr-acp`, which opens its own herdr+/// windows for real agent TUIs, so no session needs a viewer window.+pub(crate) fn drives_herdr(harness: &Harness) -> bool {+ harness.args.first().map(String::as_str) == Some(acp_agent::SUBCOMMAND)+}++/// The TUI a `macrod herdr-acp` harness runs, if the harness is one.+pub(crate) fn herdr_agent(harness: &Harness) -> Option<acp_agent::TuiAgent> {+ if !drives_herdr(harness) {+ return None;+ }+ let mut args = harness.args.iter().skip(1).map(String::as_str);+ while let Some(arg) = args.next() {+ let kind = match arg {+ "--" => break,+ "--kind" => args.next(),+ arg => arg.strip_prefix("--kind="),+ };+ if let Some(kind) = kind {+ return <acp_agent::TuiAgent as clap::ValueEnum>::from_str(kind, true).ok();+ }+ }+ Some(acp_agent::TuiAgent::default())+}++mod environment {+ macro_env_var::maybe_env_var! {+ pub struct HerdrEnv;+ }+ macro_env_var::maybe_env_var! {+ pub struct HerdrBinPath;+ }+ macro_env_var::maybe_env_var! {+ pub struct HerdrWorkspaceId;+ }+}++/// The herdr session macrod was started in.+#[derive(Debug, Clone)]+pub(crate) struct HerdrSession {+ /// The `herdr` binary attached to that session.+ pub bin: PathBuf,+ /// The workspace macrod's pane belongs to; new windows open there.+ pub workspace_id: Option<String>,+}++impl HerdrSession {+ /// The session macrod is running inside, if any.+ pub(crate) fn detect() -> Option<Self> {+ let inside = environment::HerdrEnv::new().is_some_and(|value| value.value() == Some("1"));+ if !inside {+ return None;+ }+ let bin = environment::HerdrBinPath::new()+ .and_then(|path| path.value().map(PathBuf::from))+ .unwrap_or_else(|| PathBuf::from("herdr"));+ let workspace_id = environment::HerdrWorkspaceId::new()+ .and_then(|id| id.value().map(str::to_owned))+ .filter(|id| !id.is_empty());+ Some(Self { bin, workspace_id })+ }+}diff --git a/crates/coding_agent_worker/src/herdr/acp_agent.rs b/crates/coding_agent_worker/src/herdr/acp_agent.rsnew file mode 100644index 0000000000..8c08aee129--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent.rs@@ -0,0 +1,956 @@+//! `macrod herdr-acp`: an ACP agent whose sessions are live coding-agent TUIs+//! (Claude Code or Codex) in herdr windows.+//!+//! macrod runs this as its harness like any other ACP agent, so sessions+//! still open, prompt, stream, and stop through Macro's ACP infrastructure.+//! Behind the protocol, each session is a real interactive `claude` or+//! `codex` in its own herdr tab, rooted at the session's working directory:+//!+//! - the first `session/prompt` opens the tab and starts the agent there+//! with the session's model (and, for Claude Code, its id and Macro MCP+//! servers);+//! - prompts are typed into the TUI with `herdr agent prompt`;+//! - the agent's own session transcript is tailed and streamed back as+//! `session/update`s, and its end-of-turn record ends the turn;+//! - a permission dialog in the TUI becomes a `session/request_permission`,+//! answered by pressing the matching key; `session/cancel` presses Esc.+//!+//! Anyone watching the herdr window can also type into the TUI directly.++use std::collections::HashMap;+use std::io::{Read as _, Seek as _};+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use serde_json::{Value, json};+use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader};+use tokio::sync::{mpsc, oneshot};+use tokio_util::sync::CancellationToken;++use super::HerdrSession;+use super::claude_log::{ClaudeLog, LogEvent};+use super::cli::{HerdrCli, HerdrError};+use super::codex_log::CodexLog;+use super::hub::title_from;++/// The subcommand macrod's harness config names to run this adapter.+pub(crate) const SUBCOMMAND: &str = "herdr-acp";++const MODEL_CONFIG_ID: &str = "model";+const DEFAULT_MODEL: &str = "default";+const CLAUDE_MODELS: &[(&str, &str)] = &[+ (DEFAULT_MODEL, "Default (Claude Code's choice)"),+ ("opus", "Opus"),+ ("sonnet", "Sonnet"),+ ("haiku", "Haiku"),+];+const CODEX_MODELS: &[(&str, &str)] = &[+ (DEFAULT_MODEL, "Default (Codex's choice)"),+ ("gpt-6-astra", "GPT-6 Astra"),+ ("gpt-5.6", "GPT-5.6"),+ ("gpt-5.5", "GPT-5.5"),+];+const POLL: Duration = Duration::from_millis(250);+/// Transcript polls per herdr status check.+const STATUS_EVERY: u32 = 4;+/// Consecutive ready status checks, with no transcript ending, that end a+/// turn anyway (slash commands and interrupted turns write no final message).+const SETTLED_CHECKS: u32 = 3;+const QUIET_START: Duration = Duration::from_secs(20);+const MISSING_AGENT_CHECKS: u32 = 5;+/// How long a submitted prompt may show no sign of a turn before the+/// adapter presses Enter again: a TUI still settling after launch can take+/// the pasted text but drop the Enter that follows it.+const SUBMIT_GRACE: Duration = Duration::from_secs(5);++/// Which coding-agent TUI each session runs.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]+pub(crate) enum TuiAgent {+ /// Claude Code (`claude`).+ #[default]+ Claude,+ /// OpenAI Codex (`codex`).+ Codex,+}++impl TuiAgent {+ /// herdr's `--kind` for the agent, which is also its command.+ pub(crate) fn herdr_kind(self) -> &'static str {+ match self {+ Self::Claude => "claude",+ Self::Codex => "codex",+ }+ }++ fn models(self) -> &'static [(&'static str, &'static str)] {+ match self {+ Self::Claude => CLAUDE_MODELS,+ Self::Codex => CODEX_MODELS,+ }+ }++ fn log(self) -> Transcript {+ match self {+ Self::Claude => Transcript::Claude(ClaudeLog::default()),+ Self::Codex => Transcript::Codex(CodexLog::default()),+ }+ }+}++/// A session transcript reader for the agent that writes it.+enum Transcript {+ Claude(ClaudeLog),+ Codex(CodexLog),+}++impl Transcript {+ fn entry(&mut self, line: &str) -> Vec<LogEvent> {+ match self {+ Self::Claude(log) => log.entry(line),+ Self::Codex(log) => log.entry(line),+ }+ }+}++/// How `macrod herdr-acp` runs its agents.+#[derive(Debug, Clone, Default)]+pub(crate) struct AdapterOptions {+ /// The agent TUI sessions run.+ pub kind: TuiAgent,+ /// Passed to Claude Code as `--permission-mode`.+ pub permission_mode: Option<String>,+ /// Open session windows in the background instead of switching to them.+ pub no_focus: bool,+ /// Extra arguments for every agent launch, after the adapter's own.+ pub agent_args: Vec<String>,+}++#[derive(Debug)]+struct RpcError {+ code: i64,+ message: String,+}++impl RpcError {+ fn internal(message: impl Into<String>) -> Self {+ Self {+ code: -32603,+ message: message.into(),+ }+ }++ fn invalid(message: impl Into<String>) -> Self {+ Self {+ code: -32602,+ message: message.into(),+ }+ }+}++impl From<HerdrError> for RpcError {+ fn from(error: HerdrError) -> Self {+ Self::internal(error.to_string())+ }+}++mod environment {+ macro_env_var::maybe_env_var! {+ pub struct Home;+ }+}++/// Serve ACP on stdin/stdout until stdin closes.+pub async fn run(options: AdapterOptions) -> rootcause::Result<()> {+ let (out_tx, mut out_rx) = mpsc::unbounded_channel::<Value>();+ let writer = tokio::spawn(async move {+ let mut stdout = tokio::io::stdout();+ while let Some(message) = out_rx.recv().await {+ let mut line = message.to_string();+ line.push('\n');+ if stdout.write_all(line.as_bytes()).await.is_err() || stdout.flush().await.is_err() {+ return;+ }+ }+ });++ let herdr = HerdrSession::detect();+ let adapter = Arc::new(Adapter {+ out: out_tx,+ pending: Mutex::new(HashMap::new()),+ next_id: AtomicU64::new(0),+ sessions: Mutex::new(HashMap::new()),+ herdr: herdr+ .as_ref()+ .map(|herdr| HerdrCli::new(&herdr.bin, herdr.workspace_id.clone())),+ options,+ home: environment::Home::new().and_then(|home| home.value().map(PathBuf::from)),+ claimed: Mutex::new(std::collections::HashSet::new()),+ });++ let mut lines = BufReader::new(tokio::io::stdin()).lines();+ while let Some(line) = lines.next_line().await? {+ let Ok(message) = serde_json::from_str::<Value>(&line) else {+ continue;+ };+ let id = message.get("id").filter(|id| !id.is_null()).cloned();+ let params = message.get("params").cloned().unwrap_or(Value::Null);+ match (message.get("method").and_then(Value::as_str), id) {+ (Some(method), Some(id)) => {+ let adapter = adapter.clone();+ let method = method.to_owned();+ tokio::spawn(async move {+ let result = adapter.request(&method, params).await;+ adapter.respond(id, result);+ });+ }+ (Some("session/cancel"), None) => adapter.cancel(¶ms),+ (Some(_), None) => {}+ (None, Some(id)) => adapter.answered(&id, message),+ (None, None) => {}+ }+ }+ drop(adapter);+ let _ = writer.await;+ Ok(())+}++struct Adapter {+ out: mpsc::UnboundedSender<Value>,+ pending: Mutex<HashMap<String, oneshot::Sender<Value>>>,+ next_id: AtomicU64,+ sessions: Mutex<HashMap<String, Arc<Session>>>,+ herdr: Option<HerdrCli>,+ options: AdapterOptions,+ home: Option<PathBuf>,+ /// Transcripts already bound to a session, so two sessions in the same+ /// directory never read the same Codex rollout.+ claimed: Mutex<std::collections::HashSet<PathBuf>>,+}++struct Session {+ id: String,+ cwd: PathBuf,+ mcp_servers: Vec<Value>,+ model: Mutex<String>,+ live: tokio::sync::Mutex<Option<Live>>,+ cancel: Mutex<Option<CancellationToken>>,+}++/// A session's running TUI.+struct Live {+ session: String,+ cwd: PathBuf,+ started: std::time::SystemTime,+ name: String,+ model: String,+ log: Transcript,+ path: Option<PathBuf>,+ offset: u64,+}++fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {+ mutex+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+}++impl Adapter {+ fn send(&self, message: Value) {+ let _ = self.out.send(message);+ }++ fn respond(&self, id: Value, result: Result<Value, RpcError>) {+ self.send(match result {+ Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),+ Err(error) => json!({+ "jsonrpc": "2.0",+ "id": id,+ "error": {"code": error.code, "message": error.message},+ }),+ });+ }++ fn notify_update(&self, session: &str, update: Value) {+ self.send(json!({+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {"sessionId": session, "update": update},+ }));+ }++ /// Send a request to the client and wait for its answer.+ async fn call(&self, method: &str, params: Value) -> Option<Value> {+ let id = format!(+ "macrod-herdr-{}",+ self.next_id.fetch_add(1, Ordering::Relaxed)+ );+ let (tx, rx) = oneshot::channel();+ lock(&self.pending).insert(Value::String(id.clone()).to_string(), tx);+ self.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));+ rx.await.ok()+ }++ fn answered(&self, id: &Value, message: Value) {+ if let Some(waiter) = lock(&self.pending).remove(&id.to_string()) {+ let _ = waiter.send(message);+ }+ }++ fn session(&self, params: &Value) -> Result<Arc<Session>, RpcError> {+ let id = params+ .get("sessionId")+ .and_then(Value::as_str)+ .ok_or_else(|| RpcError::invalid("missing sessionId"))?;+ lock(&self.sessions)+ .get(id)+ .cloned()+ .ok_or_else(|| RpcError::invalid(format!("unknown session {id}")))+ }++ fn cancel(&self, params: &Value) {+ if let Ok(session) = self.session(params)+ && let Some(cancel) = lock(&session.cancel).as_ref()+ {+ cancel.cancel();+ }+ }++ async fn request(self: &Arc<Self>, method: &str, params: Value) -> Result<Value, RpcError> {+ match method {+ "initialize" => Ok(json!({+ "protocolVersion": 1,+ "agentCapabilities": {+ "loadSession": false,+ "promptCapabilities": {"image": false, "audio": false, "embeddedContext": false},+ },+ "authMethods": [],+ "agentInfo": {"name": "macrod-herdr", "version": env!("CARGO_PKG_VERSION")},+ })),+ "session/new" => Ok(self.new_session(¶ms)),+ "session/set_config_option" => {+ let session = self.session(¶ms)?;+ let config = params.get("configId").and_then(Value::as_str);+ let value = params.get("value").and_then(Value::as_str);+ match (config, value) {+ (Some(MODEL_CONFIG_ID), Some(model))+ if self+ .options+ .kind+ .models()+ .iter()+ .any(|(id, _)| *id == model) =>+ {+ model.clone_into(&mut lock(&session.model));+ Ok(json!({"configOptions": config_options(self.options.kind, model)}))+ }+ _ => Err(RpcError::invalid("unsupported configuration option")),+ }+ }+ "session/prompt" => {+ let session = self.session(¶ms)?;+ let text = prompt_text(params.get("prompt").unwrap_or(&Value::Null));+ self.prompt(&session, &text)+ .await+ .map(|stop| json!({"stopReason": stop}))+ }+ _ => Err(RpcError {+ code: -32601,+ message: format!("{method} is not supported"),+ }),+ }+ }++ fn new_session(&self, params: &Value) -> Value {+ let id = uuid::Uuid::new_v4().to_string();+ let cwd = params+ .get("cwd")+ .and_then(Value::as_str)+ .map_or_else(|| PathBuf::from("."), PathBuf::from);+ let mcp_servers = params+ .get("mcpServers")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ lock(&self.sessions).insert(+ id.clone(),+ Arc::new(Session {+ id: id.clone(),+ cwd,+ mcp_servers,+ model: Mutex::new(DEFAULT_MODEL.to_owned()),+ live: tokio::sync::Mutex::new(None),+ cancel: Mutex::new(None),+ }),+ );+ json!({"sessionId": id, "configOptions": config_options(self.options.kind, DEFAULT_MODEL)})+ }++ async fn prompt(+ self: &Arc<Self>,+ session: &Arc<Session>,+ text: &str,+ ) -> Result<&'static str, RpcError> {+ let herdr = self.herdr.as_ref().ok_or_else(|| {+ RpcError::internal("macrod herdr-acp needs a macrod started inside herdr")+ })?;+ let cancel = CancellationToken::new();+ *lock(&session.cancel) = Some(cancel.clone());++ let mut guard = session.live.lock().await;+ if guard.is_none() {+ *guard = Some(self.launch(herdr, session, text).await?);+ }+ let Some(live) = guard.as_mut() else {+ return Err(RpcError::internal("the Claude Code window did not start"));+ };++ let model = lock(&session.model).clone();+ if model != live.model && self.options.kind == TuiAgent::Claude {+ herdr+ .prompt_agent(&live.name, &format!("/model {model}"))+ .await?;+ live.model = model;+ tokio::time::sleep(Duration::from_secs(1)).await;+ }+ // Anything already in the transcript belongs to earlier turns.+ for event in self.drain(live) {+ if let LogEvent::Update(update) = event {+ self.notify_update(&session.id, update);+ }+ }+ herdr.prompt_agent(&live.name, text).await?;+ let outcome = self.follow(herdr, session, live, &cancel).await;+ if outcome.is_err() {+ *guard = None;+ }+ outcome+ }++ /// Open the session's herdr window and start the agent in it.+ async fn launch(+ &self,+ herdr: &HerdrCli,+ session: &Session,+ first_prompt: &str,+ ) -> Result<Live, RpcError> {+ let kind = self.options.kind;+ let label = title_from(first_prompt).unwrap_or_else(|| kind.herdr_kind().to_owned());+ let window = herdr+ .open_window(&session.cwd, &label, !self.options.no_focus)+ .await?;+ // The tab's shell must reach its prompt before an agent can start.+ tokio::time::sleep(Duration::from_millis(800)).await;++ let model = lock(&session.model).clone();+ let mut args = Vec::new();+ if model != DEFAULT_MODEL {+ args.extend(["--model".to_owned(), model.clone()]);+ }+ if kind == TuiAgent::Claude {+ args.extend(["--session-id".to_owned(), session.id.clone()]);+ if let Some(mode) = &self.options.permission_mode {+ args.extend(["--permission-mode".to_owned(), mode.clone()]);+ }+ if let Some(config) = self.write_mcp_config(session)? {+ args.extend([+ "--mcp-config".to_owned(),+ config.to_string_lossy().into_owned(),+ ]);+ }+ }+ args.extend(self.options.agent_args.iter().cloned());+ let name = agent_name(&session.id);+ let started = std::time::SystemTime::now();+ herdr+ .start_agent(&name, kind.herdr_kind(), &window.pane_id, &args)+ .await?;+ tracing::info!(+ session = %session.id,+ pane = %window.pane_id,+ agent = kind.herdr_kind(),+ "agent started in herdr"+ );+ Ok(Live {+ session: session.id.clone(),+ cwd: session.cwd.clone(),+ started,+ name,+ model,+ log: self.options.kind.log(),+ path: None,+ offset: 0,+ })+ }++ /// Hand Claude Code the MCP servers Macro gave the session, in a file+ /// only this user can read: the entries carry session credentials.+ fn write_mcp_config(&self, session: &Session) -> Result<Option<PathBuf>, RpcError> {+ let servers = claude_mcp_servers(&session.mcp_servers);+ if servers.is_empty() {+ return Ok(None);+ }+ let dir = std::env::temp_dir().join("macrod-herdr");+ std::fs::create_dir_all(&dir).map_err(|error| RpcError::internal(error.to_string()))?;+ let path = dir.join(format!("{}.mcp.json", session.id));+ let body = json!({"mcpServers": servers}).to_string();+ write_private(&path, body.as_bytes())+ .map_err(|error| RpcError::internal(error.to_string()))?;+ Ok(Some(path))+ }++ /// Stream the turn from the transcript until it ends.+ async fn follow(+ self: &Arc<Self>,+ herdr: &HerdrCli,+ session: &Arc<Session>,+ live: &mut Live,+ cancel: &CancellationToken,+ ) -> Result<&'static str, RpcError> {+ let started = Instant::now();+ let mut ticks = 0u32;+ let mut settled = 0u32;+ let mut missing = 0u32;+ let mut active = false;+ let mut open_tool: Option<(String, String)> = None;+ // Bumped whenever a dialog is asked about or goes away, so a late+ // answer from Macro never presses keys into a different dialog.+ let generation = Arc::new(AtomicU64::new(0));+ let mut asking = false;+ let mut resubmitted = false;+ loop {+ tokio::select! {+ () = cancel.cancelled() => {+ herdr.send_keys(&live.name, &["esc"]).await?;+ tokio::time::sleep(Duration::from_secs(1)).await;+ if self.options.kind == TuiAgent::Claude {+ // Claude Code puts an interrupted prompt back in its+ // input box; left there, the next prompt is appended+ // to it. One Ctrl+C clears the box (two would quit).+ herdr.send_keys(&live.name, &["ctrl+c"]).await?;+ }+ self.forward(session, live, &mut open_tool);+ return Ok("cancelled");+ }+ () = tokio::time::sleep(POLL) => {}+ }+ let (moved, ended) = self.forward(session, live, &mut open_tool);+ active |= moved;+ if let Some(stop) = ended {+ return Ok(stop);+ }++ ticks += 1;+ if !ticks.is_multiple_of(STATUS_EVERY) {+ continue;+ }+ let status = match herdr.agent_info(&live.name).await {+ Ok(info) => {+ missing = 0;+ if live.path.is_none() {+ live.path = self.locate(live, info.session_id.as_deref());+ }+ info.status+ }+ Err(error) => {+ missing += 1;+ if missing >= MISSING_AGENT_CHECKS {+ return Err(RpcError::internal(format!(+ "the agent's herdr window is gone: {error}"+ )));+ }+ continue;+ }+ };+ if status != "blocked" && std::mem::take(&mut asking) {+ generation.fetch_add(1, Ordering::SeqCst);+ }+ match status.as_str() {+ "working" => {+ active = true;+ settled = 0;+ }+ "blocked" => {+ settled = 0;+ if !std::mem::replace(&mut asking, true) {+ let current = generation.fetch_add(1, Ordering::SeqCst) + 1;+ self.ask_permission(session, live, open_tool.clone(), current, &generation);+ }+ }+ "idle" | "done" if !active && !resubmitted && started.elapsed() >= SUBMIT_GRACE => {+ resubmitted = true;+ tracing::warn!(agent = %live.name, "prompt shows no activity; pressing Enter again");+ herdr.send_keys(&live.name, &["enter"]).await?;+ }+ "idle" | "done" => {+ settled += 1;+ if settled >= SETTLED_CHECKS && (active || started.elapsed() > QUIET_START) {+ self.forward(session, live, &mut open_tool);+ return Ok("end_turn");+ }+ }+ _ => {}+ }+ }+ }++ /// Relay new transcript lines. Returns whether anything moved and the+ /// stop reason if the turn ended.+ fn forward(+ &self,+ session: &Session,+ live: &mut Live,+ open_tool: &mut Option<(String, String)>,+ ) -> (bool, Option<&'static str>) {+ let mut moved = false;+ let mut ended = None;+ for event in self.drain(live) {+ match event {+ LogEvent::Update(update) => {+ moved = true;+ // Codex logs a command only once it has run, so its log+ // never names the call a permission dialog is about.+ if self.options.kind == TuiAgent::Claude {+ track_open_tool(open_tool, &update);+ }+ self.notify_update(&session.id, update);+ }+ LogEvent::TurnEnded(stop) => ended = Some(stop),+ }+ }+ (moved, ended)+ }++ /// Ask Macro about the TUI's permission dialog, then press the key for+ /// the answer - unless the dialog was already answered in the window.+ fn ask_permission(+ self: &Arc<Self>,+ session: &Arc<Session>,+ live: &Live,+ tool: Option<(String, String)>,+ generation: u64,+ blocked: &Arc<AtomicU64>,+ ) {+ let Some(herdr) = self.herdr.clone() else {+ return;+ };+ let adapter = self.clone();+ let session_id = session.id.clone();+ let name = live.name.clone();+ let blocked = blocked.clone();+ let kind = self.options.kind;+ tokio::spawn(async move {+ let (tool_id, title) = match tool {+ Some(tool) => tool,+ None => {+ let screen = herdr.read_agent(&name).await.unwrap_or_default();+ (+ format!("herdr-permission-{generation}"),+ permission_title(kind, &screen),+ )+ }+ };+ let answer = adapter+ .call(+ "session/request_permission",+ json!({+ "sessionId": session_id,+ "toolCall": {"toolCallId": tool_id, "title": title, "status": "pending"},+ "options": [+ {"optionId": "allow", "name": "Allow", "kind": "allow_once"},+ {"optionId": "reject", "name": "Reject", "kind": "reject_once"},+ ],+ }),+ )+ .await;+ if blocked.load(Ordering::SeqCst) != generation {+ return;+ }+ let allowed = answer+ .as_ref()+ .and_then(|answer| answer.pointer("/result/outcome/optionId"))+ .and_then(Value::as_str)+ == Some("allow");+ let key = if allowed { "enter" } else { "esc" };+ if let Err(error) = herdr.send_keys(&name, &[key]).await {+ tracing::warn!(error = %error, "could not answer the agent's permission dialog");+ }+ });+ }++ /// Where the agent writes the session's transcript, once it exists.+ /// Claude Code names it after the id this adapter gave it; Codex mints+ /// its own id, which herdr reports once the session is live.+ fn locate(&self, live: &Live, agent_session: Option<&str>) -> Option<PathBuf> {+ let home = self.home.as_deref()?;+ let path = match self.options.kind {+ TuiAgent::Claude => find_claude_transcript(&home.join(".claude"), &live.session),+ TuiAgent::Codex => {+ let sessions = home.join(".codex").join("sessions");+ let claimed = lock(&self.claimed);+ agent_session+ .and_then(|id| find_codex_rollout(&sessions, id))+ .or_else(|| newest_codex_rollout(&sessions, &live.cwd, live.started, &claimed))+ }+ }?;+ lock(&self.claimed).insert(path.clone());+ Some(path)+ }++ /// Read whole new lines from the session's transcript.+ fn drain(&self, live: &mut Live) -> Vec<LogEvent> {+ if live.path.is_none() {+ live.path = self.locate(live, None);+ }+ let Some(path) = &live.path else {+ return Vec::new();+ };+ let Ok(mut file) = std::fs::File::open(path) else {+ return Vec::new();+ };+ if file.seek(std::io::SeekFrom::Start(live.offset)).is_err() {+ return Vec::new();+ }+ let mut bytes = Vec::new();+ if file.read_to_end(&mut bytes).is_err() {+ return Vec::new();+ }+ let Some(end) = bytes.iter().rposition(|byte| *byte == b'\n') else {+ return Vec::new();+ };+ live.offset += end as u64 + 1;+ String::from_utf8_lossy(&bytes[..end])+ .lines()+ .flat_map(|line| live.log.entry(line))+ .collect()+ }+}++/// What a permission dialog on the agent's screen is asking about.+pub(crate) fn permission_title(kind: TuiAgent, screen: &str) -> String {+ let lines: Vec<&str> = screen.lines().map(str::trim).collect();+ let asked = lines+ .iter()+ .rposition(|line| line.starts_with("Would you like to"))+ .map(|index| (lines[index], &lines[index + 1..]));+ if let Some((question, rest)) = asked {+ if let Some(command) = rest.iter().find_map(|line| line.strip_prefix("$ ")) {+ return format!("Run {}", clip_title(command));+ }+ if question.contains("edit") {+ return "Edit files".to_owned();+ }+ if let Some(reason) = rest.iter().find_map(|line| line.strip_prefix("Reason: ")) {+ return clip_title(reason);+ }+ }+ match kind {+ TuiAgent::Claude => "Claude Code is asking for permission".to_owned(),+ TuiAgent::Codex => "Codex is asking for permission".to_owned(),+ }+}++fn clip_title(text: &str) -> String {+ const LIMIT: usize = 80;+ let mut clipped: String = text.chars().take(LIMIT).collect();+ if text.chars().count() > LIMIT {+ clipped.push('…');+ }+ clipped+}++fn track_open_tool(open_tool: &mut Option<(String, String)>, update: &Value) {+ let id = update.get("toolCallId").and_then(Value::as_str);+ match update.get("sessionUpdate").and_then(Value::as_str) {+ Some("tool_call") => {+ let title = update+ .get("title")+ .and_then(Value::as_str)+ .unwrap_or_default();+ *open_tool = id.map(|id| (id.to_owned(), title.to_owned()));+ }+ Some("tool_call_update") if open_tool.as_ref().map(|(open, _)| open.as_str()) == id => {+ *open_tool = None;+ }+ _ => {}+ }+}++/// A herdr agent name for the session: `[a-z][a-z0-9_-]{0,31}`.+pub(crate) fn agent_name(session: &str) -> String {+ let short: String = session+ .chars()+ .filter(char::is_ascii_alphanumeric)+ .take(12)+ .collect::<String>()+ .to_ascii_lowercase();+ format!("macro-{short}")+}++fn config_options(kind: TuiAgent, current: &str) -> Value {+ json!([{+ "id": MODEL_CONFIG_ID,+ "name": "Model",+ "category": "model",+ "type": "select",+ "currentValue": current,+ "options": kind+ .models()+ .iter()+ .map(|(value, name)| json!({"value": value, "name": name}))+ .collect::<Vec<_>>(),+ }])+}++pub(crate) fn prompt_text(prompt: &Value) -> String {+ prompt+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|block| match block.get("type").and_then(Value::as_str)? {+ "text" => block.get("text").and_then(Value::as_str).map(str::to_owned),+ "resource_link" => block+ .get("uri")+ .and_then(Value::as_str)+ .map(|uri| format!("@{}", uri.strip_prefix("file://").unwrap_or(uri))),+ _ => None,+ })+ .collect::<Vec<_>>()+ .join("\n")+}++/// ACP `mcpServers` entries in Claude Code's `--mcp-config` shape.+pub(crate) fn claude_mcp_servers(servers: &[Value]) -> serde_json::Map<String, Value> {+ let pairs = |list: Option<&Value>| -> serde_json::Map<String, Value> {+ list.and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(|pair| {+ Some((+ pair.get("name")?.as_str()?.to_owned(),+ pair.get("value")?.clone(),+ ))+ })+ .collect()+ };+ servers+ .iter()+ .filter_map(|server| {+ let name = server.get("name")?.as_str()?.to_owned();+ let config = match server.get("type").and_then(Value::as_str) {+ Some(kind @ ("http" | "sse")) => json!({+ "type": kind,+ "url": server.get("url")?,+ "headers": pairs(server.get("headers")),+ }),+ _ => json!({+ "command": server.get("command")?,+ "args": server.get("args").cloned().unwrap_or_else(|| json!([])),+ "env": pairs(server.get("env")),+ }),+ };+ Some((name, config))+ })+ .collect()+}++fn codex_rollouts(sessions: &Path) -> Vec<PathBuf> {+ let mut found = Vec::new();+ let mut stack = vec![sessions.to_owned()];+ while let Some(dir) = stack.pop() {+ let Ok(entries) = std::fs::read_dir(&dir) else {+ continue;+ };+ for path in entries.filter_map(Result::ok).map(|entry| entry.path()) {+ if path.is_dir() {+ stack.push(path);+ } else if path+ .file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with("rollout-") && name.ends_with(".jsonl"))+ {+ found.push(path);+ }+ }+ }+ found+}++/// The newest unclaimed rollout Codex started in `cwd` since `since`, for+/// when herdr cannot name the Codex session.+fn newest_codex_rollout(+ sessions: &Path,+ cwd: &Path,+ since: std::time::SystemTime,+ claimed: &std::collections::HashSet<PathBuf>,+) -> Option<PathBuf> {+ let since = since+ .checked_sub(Duration::from_secs(2))+ .unwrap_or(std::time::UNIX_EPOCH);+ codex_rollouts(sessions)+ .into_iter()+ .filter(|path| !claimed.contains(path))+ .filter_map(|path| {+ let modified = std::fs::metadata(&path)+ .and_then(|meta| meta.modified())+ .ok()?;+ (modified >= since).then_some((modified, path))+ })+ .filter(|(_, path)| rollout_cwd(path).is_some_and(|dir| dir == cwd))+ .max_by_key(|(modified, _)| *modified)+ .map(|(_, path)| path)+}++/// The working directory in a rollout's leading `session_meta` record.+fn rollout_cwd(path: &Path) -> Option<PathBuf> {+ use std::io::BufRead as _;+ let mut first = String::new();+ std::io::BufReader::new(std::fs::File::open(path).ok()?)+ .read_line(&mut first)+ .ok()?;+ let meta: Value = serde_json::from_str(&first).ok()?;+ (meta.get("type")?.as_str()? == "session_meta")+ .then(|| meta.pointer("/payload/cwd")?.as_str().map(PathBuf::from))+ .flatten()+}++/// `rollout-<time>-<session>.jsonl` under Codex's dated session folders.+fn find_codex_rollout(sessions: &Path, session: &str) -> Option<PathBuf> {+ if session.is_empty() {+ return None;+ }+ let suffix = format!("-{session}.jsonl");+ codex_rollouts(sessions).into_iter().find(|path| {+ path.file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.ends_with(&suffix))+ })+}++fn find_claude_transcript(claude_home: &Path, session: &str) -> Option<PathBuf> {+ if session.is_empty() {+ return None;+ }+ let file = format!("{session}.jsonl");+ std::fs::read_dir(claude_home.join("projects"))+ .ok()?+ .filter_map(Result::ok)+ .map(|project| project.path().join(&file))+ .find(|path| path.is_file())+}++fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {+ use std::io::Write as _;+ use std::os::unix::fs::OpenOptionsExt as _;+ std::fs::OpenOptions::new()+ .write(true)+ .create(true)+ .truncate(true)+ .mode(0o600)+ .open(path)?+ .write_all(bytes)+}++#[cfg(test)]+mod test;diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs b/crates/coding_agent_worker/src/herdr/acp_agent/test.rsnew file mode 100644index 0000000000..cecf3ff2fb--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/test.rs@@ -0,0 +1,155 @@+use super::*;++#[test]+fn agent_names_satisfy_herdr() {+ let name = agent_name("A2089F46-70e2-4439-935e-1b9c23319df1");+ assert_eq!(name, "macro-a2089f4670e2");+ assert!(name.len() <= 32);+}++#[test]+fn prompts_keep_text_and_reference_files() {+ let prompt = json!([+ {"type": "text", "text": "build a todo app"},+ {"type": "resource_link", "uri": "file:///repo/spec.md", "name": "spec.md"},+ {"type": "image", "data": "..."},+ ]);+ assert_eq!(prompt_text(&prompt), "build a todo app\n@/repo/spec.md");+}++#[test]+fn macro_mcp_servers_become_claude_config() {+ let servers = [+ json!({"type": "http", "name": "macro", "url": "https://x/mcp",+ "headers": [{"name": "Authorization", "value": "Bearer t"}]}),+ json!({"name": "local", "command": "srv", "args": ["--x"], "env": [{"name": "K", "value": "V"}]}),+ json!({"type": "http", "url": "https://nameless"}),+ ];+ assert_eq!(+ Value::Object(claude_mcp_servers(&servers)),+ json!({+ "macro": {"type": "http", "url": "https://x/mcp", "headers": {"Authorization": "Bearer t"}},+ "local": {"command": "srv", "args": ["--x"], "env": {"K": "V"}},+ })+ );+}++#[test]+fn the_model_option_lists_claude_aliases() {+ let options = config_options(TuiAgent::Claude, "sonnet");+ assert_eq!(options[0]["id"], MODEL_CONFIG_ID);+ assert_eq!(options[0]["currentValue"], "sonnet");+ let values: Vec<_> = options[0]["options"]+ .as_array()+ .unwrap()+ .iter()+ .map(|option| option["value"].as_str().unwrap())+ .collect();+ assert_eq!(values, ["default", "opus", "sonnet", "haiku"]);+}++#[test]+fn an_open_tool_is_forgotten_once_it_reports() {+ let mut open = None;+ track_open_tool(+ &mut open,+ &json!({"sessionUpdate": "tool_call", "toolCallId": "t", "title": "Bash ls"}),+ );+ assert_eq!(open, Some(("t".to_owned(), "Bash ls".to_owned())));+ track_open_tool(+ &mut open,+ &json!({"sessionUpdate": "tool_call_update", "toolCallId": "other"}),+ );+ assert!(open.is_some());+ track_open_tool(+ &mut open,+ &json!({"sessionUpdate": "tool_call_update", "toolCallId": "t"}),+ );+ assert_eq!(open, None);+}++#[test]+fn codex_offers_its_own_models() {+ let options = config_options(TuiAgent::Codex, DEFAULT_MODEL);+ let values: Vec<_> = options[0]["options"]+ .as_array()+ .unwrap()+ .iter()+ .map(|option| option["value"].as_str().unwrap())+ .collect();+ assert_eq!(values, ["default", "gpt-6-astra", "gpt-5.6", "gpt-5.5"]);+}++#[test]+fn codex_rollouts_are_found_by_session_id() {+ let root = tempfile::tempdir().unwrap();+ let day = root.path().join("2026/09/27");+ std::fs::create_dir_all(&day).unwrap();+ let wanted = day.join("rollout-2026-09-27T05-45-49-01a0e165-f280.jsonl");+ std::fs::write(&wanted, "").unwrap();+ std::fs::write(+ day.join("rollout-2026-09-27T05-45-13-01a0e165-6546.jsonl"),+ "",+ )+ .unwrap();+ assert_eq!(+ find_codex_rollout(root.path(), "01a0e165-f280"),+ Some(wanted)+ );+ assert_eq!(find_codex_rollout(root.path(), "missing"), None);+ assert_eq!(find_codex_rollout(root.path(), ""), None);+}++#[test]+fn an_unnamed_codex_session_takes_the_newest_unclaimed_rollout_in_its_directory() {+ let root = tempfile::tempdir().unwrap();+ let day = root.path().join("2026/09/27");+ std::fs::create_dir_all(&day).unwrap();+ let meta = |cwd: &str| {+ format!(+ "{}\n",+ json!({"type": "session_meta", "payload": {"cwd": cwd}})+ )+ };+ let since = std::time::SystemTime::now();+ let elsewhere = day.join("rollout-a-1.jsonl");+ std::fs::write(&elsewhere, meta("/other")).unwrap();+ let mine = day.join("rollout-b-2.jsonl");+ std::fs::write(&mine, meta("/repo")).unwrap();++ let mut claimed = std::collections::HashSet::new();+ assert_eq!(+ newest_codex_rollout(root.path(), Path::new("/repo"), since, &claimed),+ Some(mine.clone())+ );+ claimed.insert(mine);+ assert_eq!(+ newest_codex_rollout(root.path(), Path::new("/repo"), since, &claimed),+ None+ );+}++#[test]+fn codex_permission_dialogs_are_titled_from_the_screen() {+ let screen = " Would you like to run the following command?\n\n Environment: local\n\n Reason: May I run the browser checks?\n\n $ node /tmp/daylight-check.js\n\n› 1. Yes, proceed (y)\n";+ assert_eq!(+ permission_title(TuiAgent::Codex, screen),+ "Run node /tmp/daylight-check.js"+ );+ let reason_only = "Would you like to allow network access?\nReason: fetch the npm registry\n";+ assert_eq!(+ permission_title(TuiAgent::Codex, reason_only),+ "fetch the npm registry"+ );+ assert_eq!(+ permission_title(+ TuiAgent::Codex,+ "Would you like to make the following edits?\n"+ ),+ "Edit files"+ );+ assert_eq!(+ permission_title(TuiAgent::Codex, "nothing recognizable"),+ "Codex is asking for permission"+ );+}diff --git a/crates/coding_agent_worker/src/herdr/claude_log.rs b/crates/coding_agent_worker/src/herdr/claude_log.rsnew file mode 100644index 0000000000..7c811c5110--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/claude_log.rs@@ -0,0 +1,181 @@+//! Claude Code's session transcript, read back as ACP.+//!+//! Interactive Claude Code appends every message of a session to+//! `~/.claude/projects/<cwd>/<session-id>.jsonl` as it happens. Tailing that+//! file is how the herdr adapter streams a TUI-driven turn to Macro without+//! scraping the screen: each assistant block becomes a `session/update`, and+//! the assistant message that stops for a reason other than a tool call ends+//! the turn.++use std::collections::HashSet;++use serde_json::{Value, json};++#[cfg(test)]+mod test;++/// Longest tool output forwarded to Macro, in characters.+const TOOL_OUTPUT_LIMIT: usize = 4_000;++/// What one transcript line means for the ACP session.+#[derive(Debug, Clone, PartialEq)]+pub(crate) enum LogEvent {+ /// A `session/update` payload to send.+ Update(Value),+ /// The turn is over, with this ACP stop reason.+ TurnEnded(&'static str),+}++/// Transcript reader state: lines are appended once, but a reader that+/// reopens the file must not replay them.+#[derive(Debug, Default)]+pub(crate) struct ClaudeLog {+ seen: HashSet<String>,+}++impl ClaudeLog {+ /// Translate one transcript line.+ pub(crate) fn entry(&mut self, line: &str) -> Vec<LogEvent> {+ let Ok(entry) = serde_json::from_str::<Value>(line) else {+ return Vec::new();+ };+ if entry.get("isSidechain").and_then(Value::as_bool) == Some(true) {+ return Vec::new();+ }+ if let Some(uuid) = entry.get("uuid").and_then(Value::as_str)+ && !self.seen.insert(uuid.to_owned())+ {+ return Vec::new();+ }+ let Some(message) = entry.get("message") else {+ return Vec::new();+ };+ match entry.get("type").and_then(Value::as_str) {+ Some("assistant") => assistant(message),+ Some("user") => tool_results(message),+ _ => Vec::new(),+ }+ }+}++fn blocks(message: &Value) -> impl Iterator<Item = &Value> {+ message+ .get("content")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+}++fn assistant(message: &Value) -> Vec<LogEvent> {+ let mut events: Vec<LogEvent> = blocks(message)+ .filter_map(|block| {+ let text = |field| block.get(field).and_then(Value::as_str);+ match block.get("type").and_then(Value::as_str)? {+ "text" => Some(json!({+ "sessionUpdate": "agent_message_chunk",+ "content": {"type": "text", "text": text("text")?},+ })),+ "thinking" => Some(json!({+ "sessionUpdate": "agent_thought_chunk",+ "content": {"type": "text", "text": text("thinking")?},+ })),+ "tool_use" => {+ let name = text("name").unwrap_or("tool");+ let input = block.get("input").cloned().unwrap_or(Value::Null);+ Some(json!({+ "sessionUpdate": "tool_call",+ "toolCallId": text("id")?,+ "title": tool_title(name, &input),+ "kind": tool_kind(name),+ "status": "in_progress",+ "rawInput": input,+ }))+ }+ _ => None,+ }+ })+ .map(LogEvent::Update)+ .collect();+ let stop = match message.get("stop_reason").and_then(Value::as_str) {+ Some("end_turn" | "stop_sequence") => Some("end_turn"),+ Some("max_tokens") => Some("max_tokens"),+ Some("refusal") => Some("refusal"),+ _ => None,+ };+ events.extend(stop.map(LogEvent::TurnEnded));+ events+}++fn tool_results(message: &Value) -> Vec<LogEvent> {+ blocks(message)+ .filter(|block| block.get("type").and_then(Value::as_str) == Some("tool_result"))+ .filter_map(|block| {+ let id = block.get("tool_use_id")?.as_str()?;+ let failed = block.get("is_error").and_then(Value::as_bool) == Some(true);+ let mut update = json!({+ "sessionUpdate": "tool_call_update",+ "toolCallId": id,+ "status": if failed { "failed" } else { "completed" },+ });+ let output = result_text(block.get("content"));+ if !output.is_empty() {+ update["content"] = json!([{+ "type": "content",+ "content": {"type": "text", "text": truncate(&output)},+ }]);+ }+ Some(LogEvent::Update(update))+ })+ .collect()+}++fn result_text(content: Option<&Value>) -> String {+ match content {+ Some(Value::String(text)) => text.clone(),+ Some(Value::Array(parts)) => parts+ .iter()+ .filter_map(|part| part.get("text").and_then(Value::as_str))+ .collect::<Vec<_>>()+ .join("\n"),+ _ => String::new(),+ }+}++pub(crate) fn truncate(text: &str) -> String {+ if text.chars().count() <= TOOL_OUTPUT_LIMIT {+ return text.to_owned();+ }+ let mut kept: String = text.chars().take(TOOL_OUTPUT_LIMIT).collect();+ kept.push_str("\n… [truncated]");+ kept+}++fn tool_title(name: &str, input: &Value) -> String {+ let field = |key| input.get(key).and_then(Value::as_str);+ let detail = match name {+ "Bash" => field("description").or_else(|| field("command")),+ "Read" | "Write" | "Edit" | "MultiEdit" | "NotebookEdit" => {+ field("file_path").or_else(|| field("notebook_path"))+ }+ "Grep" | "Glob" => field("pattern"),+ "WebFetch" => field("url"),+ "WebSearch" => field("query"),+ "Task" | "Agent" => field("description"),+ _ => None,+ };+ match detail {+ Some(detail) => format!("{name} {detail}"),+ None => name.to_owned(),+ }+}++fn tool_kind(name: &str) -> &'static str {+ match name {+ "Read" => "read",+ "Write" | "Edit" | "MultiEdit" | "NotebookEdit" => "edit",+ "Bash" => "execute",+ "Grep" | "Glob" | "WebSearch" => "search",+ "WebFetch" => "fetch",+ _ => "other",+ }+}diff --git a/crates/coding_agent_worker/src/herdr/claude_log/test.rs b/crates/coding_agent_worker/src/herdr/claude_log/test.rsnew file mode 100644index 0000000000..e3a9985b16--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/claude_log/test.rs@@ -0,0 +1,112 @@+use super::*;++fn line(value: Value) -> String {+ value.to_string()+}++#[test]+fn a_tool_turn_streams_calls_results_and_its_end() {+ let mut log = ClaudeLog::default();+ let call = line(json!({+ "type": "assistant", "uuid": "u1",+ "message": {"stop_reason": "tool_use", "content": [+ {"type": "thinking", "thinking": "need a file"},+ {"type": "tool_use", "id": "toolu_1", "name": "Write", "input": {"file_path": "/r/todo.html", "content": "<html>"}}+ ]}+ }));+ assert_eq!(+ log.entry(&call),+ [+ LogEvent::Update(json!({+ "sessionUpdate": "agent_thought_chunk",+ "content": {"type": "text", "text": "need a file"},+ })),+ LogEvent::Update(json!({+ "sessionUpdate": "tool_call",+ "toolCallId": "toolu_1",+ "title": "Write /r/todo.html",+ "kind": "edit",+ "status": "in_progress",+ "rawInput": {"file_path": "/r/todo.html", "content": "<html>"},+ })),+ ]+ );+ // Reopening the transcript must not replay a line.+ assert!(log.entry(&call).is_empty());++ let result = line(json!({+ "type": "user", "uuid": "u2",+ "message": {"content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "File created"}]}+ }));+ assert_eq!(+ log.entry(&result),+ [LogEvent::Update(json!({+ "sessionUpdate": "tool_call_update",+ "toolCallId": "toolu_1",+ "status": "completed",+ "content": [{"type": "content", "content": {"type": "text", "text": "File created"}}],+ }))]+ );++ let done = line(json!({+ "type": "assistant", "uuid": "u3",+ "message": {"stop_reason": "end_turn", "content": [{"type": "text", "text": "Built it."}]}+ }));+ assert_eq!(+ log.entry(&done),+ [+ LogEvent::Update(json!({+ "sessionUpdate": "agent_message_chunk",+ "content": {"type": "text", "text": "Built it."},+ })),+ LogEvent::TurnEnded("end_turn"),+ ]+ );+}++#[test]+fn failed_tools_and_block_results_are_reported() {+ let mut log = ClaudeLog::default();+ let result = line(json!({+ "type": "user", "uuid": "u",+ "message": {"content": [{"type": "tool_result", "tool_use_id": "t", "is_error": true,+ "content": [{"type": "text", "text": "exit 1"}, {"type": "text", "text": "boom"}]}]}+ }));+ assert_eq!(+ log.entry(&result),+ [LogEvent::Update(json!({+ "sessionUpdate": "tool_call_update",+ "toolCallId": "t",+ "status": "failed",+ "content": [{"type": "content", "content": {"type": "text", "text": "exit 1\nboom"}}],+ }))]+ );+}++#[test]+fn prompts_bookkeeping_and_sidechains_are_skipped() {+ let mut log = ClaudeLog::default();+ for entry in [+ json!({"type": "user", "uuid": "a", "message": {"content": "build a todo app"}}),+ json!({"type": "attachment", "uuid": "b"}),+ json!({"type": "ai-title", "aiTitle": "Todo app"}),+ json!({"type": "assistant", "uuid": "c", "isSidechain": true,+ "message": {"stop_reason": "end_turn", "content": [{"type": "text", "text": "sub"}]}}),+ ] {+ assert!(log.entry(&line(entry)).is_empty());+ }+ assert!(log.entry("not json").is_empty());+}++#[test]+fn bash_calls_are_titled_by_their_description() {+ assert_eq!(+ tool_title(+ "Bash",+ &json!({"command": "npm test", "description": "Run tests"})+ ),+ "Bash Run tests"+ );+ assert_eq!(tool_title("Bash", &json!({"command": "ls"})), "Bash ls");+ assert_eq!(tool_title("TodoWrite", &json!({})), "TodoWrite");+}diff --git a/crates/coding_agent_worker/src/herdr/cli.rs b/crates/coding_agent_worker/src/herdr/cli.rsnew file mode 100644index 0000000000..922609ebb4--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/cli.rs@@ -0,0 +1,279 @@+//! The `herdr` CLI, as the one outbound door into the herdr session that+//! launched this daemon. Every command talks to that session's socket+//! through the environment herdr injected into macrod's pane.++use std::path::{Path, PathBuf};++use serde::Deserialize;+use serde_json::Value;++use super::wire::AgentState;++/// The agent source macrod reports under. herdr scopes reported state per+/// source, so this must not collide with a built-in integration's name.+const REPORT_SOURCE: &str = "macrod";+const REPORT_AGENT: &str = "macro";++/// A failure running a herdr command.+#[derive(Debug, thiserror::Error)]+pub(crate) enum HerdrError {+ /// The binary could not be started.+ #[error("could not run herdr")]+ Spawn(#[source] std::io::Error),+ /// herdr ran and refused.+ #[error("herdr {command} failed: {stderr}")]+ Refused {+ /// The subcommand that failed.+ command: String,+ /// What herdr printed to stderr.+ stderr: String,+ },+ /// herdr answered with JSON this daemon does not understand.+ #[error("herdr {command} answered unexpectedly")]+ Unparsable {+ /// The subcommand that answered.+ command: String,+ /// The parse failure.+ #[source]+ source: serde_json::Error,+ },+}++/// The tab and root pane a new herdr window opened with.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct Window {+ /// The tab, e.g. `w1:t2`.+ pub tab_id: String,+ /// The tab's only pane, e.g. `w1:p2`.+ pub pane_id: String,+}++/// What herdr knows about a running agent.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct AgentInfo {+ /// `idle`, `working`, `blocked`, `done`, or `unknown`.+ pub status: String,+ /// The agent's own session id, when its integration reports one.+ pub session_id: Option<String>,+}++/// Drives the herdr session through its CLI.+#[derive(Debug, Clone)]+pub(crate) struct HerdrCli {+ bin: PathBuf,+ workspace_id: Option<String>,+}++impl HerdrCli {+ /// Drive the session the given binary is attached to, opening windows in+ /// `workspace_id` (herdr's focused workspace when absent).+ pub(crate) fn new(bin: impl Into<PathBuf>, workspace_id: Option<String>) -> Self {+ Self {+ bin: bin.into(),+ workspace_id,+ }+ }++ /// Open a tab in macrod's workspace, switching herdr to it when `focus`.+ pub(crate) async fn open_window(+ &self,+ cwd: &Path,+ label: &str,+ focus: bool,+ ) -> Result<Window, HerdrError> {+ let mut args = vec!["tab".to_owned(), "create".to_owned()];+ if let Some(workspace) = &self.workspace_id {+ args.extend(["--workspace".to_owned(), workspace.clone()]);+ }+ args.extend([+ "--cwd".to_owned(),+ cwd.to_string_lossy().into_owned(),+ "--label".to_owned(),+ label.to_owned(),+ if focus { "--focus" } else { "--no-focus" }.to_owned(),+ ]);+ let output = self.run(&args).await?;+ parse_window(&output)+ }++ /// Type a command into a pane's shell and press Enter.+ pub(crate) async fn run_in_pane(&self, pane_id: &str, command: &str) -> Result<(), HerdrError> {+ self.run(&["pane", "run", pane_id, command]).await.map(drop)+ }++ /// Relabel a tab.+ pub(crate) async fn rename_tab(&self, tab_id: &str, label: &str) -> Result<(), HerdrError> {+ self.run(&["tab", "rename", tab_id, label]).await.map(drop)+ }++ /// Report the lifecycle state of the agent a pane hosts, which is what+ /// herdr's sidebar and notifications are driven by.+ pub(crate) async fn report_state(+ &self,+ pane_id: &str,+ state: AgentState,+ message: Option<&str>,+ seq: u64,+ ) -> Result<(), HerdrError> {+ let seq = seq.to_string();+ let mut args = vec![+ "pane",+ "report-agent",+ pane_id,+ "--source",+ REPORT_SOURCE,+ "--agent",+ REPORT_AGENT,+ "--state",+ state.as_herdr(),+ "--seq",+ &seq,+ ];+ if let Some(message) = message {+ args.extend(["--message", message]);+ }+ self.run(&args).await.map(drop)+ }++ /// Name the agent and its task in herdr's sidebar.+ pub(crate) async fn report_title(+ &self,+ pane_id: &str,+ display_agent: &str,+ title: Option<&str>,+ ) -> Result<(), HerdrError> {+ let mut args = vec![+ "pane",+ "report-metadata",+ pane_id,+ "--source",+ REPORT_SOURCE,+ "--agent",+ REPORT_AGENT,+ "--display-agent",+ display_agent,+ ];+ if let Some(title) = title {+ args.extend(["--title", title]);+ }+ self.run(&args).await.map(drop)+ }++ /// Start a recognized agent CLI in an idle shell pane under a unique+ /// name, returning once herdr sees it ready for input.+ pub(crate) async fn start_agent(+ &self,+ name: &str,+ kind: &str,+ pane_id: &str,+ agent_args: &[String],+ ) -> Result<(), HerdrError> {+ let mut args: Vec<&str> = vec![+ "agent",+ "start",+ name,+ "--kind",+ kind,+ "--pane",+ pane_id,+ "--timeout",+ "60000",+ "--",+ ];+ args.extend(agent_args.iter().map(String::as_str));+ self.run(&args).await.map(drop)+ }++ /// Submit a prompt to a named agent's TUI, returning once it is typed.+ pub(crate) async fn prompt_agent(&self, name: &str, text: &str) -> Result<(), HerdrError> {+ self.run(&["agent", "prompt", name, text]).await.map(drop)+ }++ /// A named agent's lifecycle state and the agent's own session id.+ pub(crate) async fn agent_info(&self, name: &str) -> Result<AgentInfo, HerdrError> {+ let output = self.run(&["agent", "get", name]).await?;+ let answer: Value =+ serde_json::from_str(output.trim()).map_err(|source| HerdrError::Unparsable {+ command: "agent get".to_owned(),+ source,+ })?;+ Ok(AgentInfo {+ status: answer+ .pointer("/result/agent/agent_status")+ .and_then(Value::as_str)+ .unwrap_or("unknown")+ .to_owned(),+ session_id: answer+ .pointer("/result/agent/agent_session/value")+ .and_then(Value::as_str)+ .map(str::to_owned),+ })+ }++ /// The text a named agent's pane currently shows.+ pub(crate) async fn read_agent(&self, name: &str) -> Result<String, HerdrError> {+ self.run(&["agent", "read", name, "--source", "visible"])+ .await+ }++ /// Press logical keys (`enter`, `esc`, `ctrl+c`) in a named agent's TUI.+ pub(crate) async fn send_keys(&self, name: &str, keys: &[&str]) -> Result<(), HerdrError> {+ let mut args = vec!["agent", "send-keys", name];+ args.extend(keys);+ self.run(&args).await.map(drop)+ }++ async fn run<Arg: AsRef<str>>(&self, args: &[Arg]) -> Result<String, HerdrError> {+ let output = tokio::process::Command::new(&self.bin)+ .args(args.iter().map(AsRef::as_ref))+ .stdin(std::process::Stdio::null())+ .kill_on_drop(true)+ .output()+ .await+ .map_err(HerdrError::Spawn)?;+ if !output.status.success() {+ return Err(HerdrError::Refused {+ command: describe(args),+ stderr: String::from_utf8_lossy(&output.stderr).trim().to_owned(),+ });+ }+ Ok(String::from_utf8_lossy(&output.stdout).into_owned())+ }+}++fn describe<Arg: AsRef<str>>(args: &[Arg]) -> String {+ args.iter()+ .take(2)+ .map(AsRef::as_ref)+ .collect::<Vec<_>>()+ .join(" ")+}++#[derive(Deserialize)]+struct TabCreated {+ result: TabCreatedResult,+}++#[derive(Deserialize)]+struct TabCreatedResult {+ root_pane: CreatedPane,+}++#[derive(Deserialize)]+struct CreatedPane {+ pane_id: String,+ tab_id: String,+}++/// Read the new window out of `tab create`'s JSON answer.+pub(crate) fn parse_window(output: &str) -> Result<Window, HerdrError> {+ let created: TabCreated =+ serde_json::from_str(output.trim()).map_err(|source| HerdrError::Unparsable {+ command: "tab create".to_owned(),+ source,+ })?;+ Ok(Window {+ tab_id: created.result.root_pane.tab_id,+ pane_id: created.result.root_pane.pane_id,+ })+}diff --git a/crates/coding_agent_worker/src/herdr/codex_log.rs b/crates/coding_agent_worker/src/herdr/codex_log.rsnew file mode 100644index 0000000000..0905a1ae9f--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/codex_log.rs@@ -0,0 +1,241 @@+//! Codex's session rollout, read back as ACP.+//!+//! The interactive Codex TUI appends each session's events to+//! `~/.codex/sessions/YYYY/MM/DD/rollout-<time>-<session-id>.jsonl`. Its+//! `event_msg` entries carry one `item_completed` per finished item (agent+//! messages, reasoning, commands, file changes, tool calls) and a+//! `task_complete` or `turn_aborted` when a turn ends.++use std::collections::HashSet;++use serde_json::{Value, json};++use super::claude_log::{LogEvent, truncate};++#[cfg(test)]+mod test;++const TITLE_LIMIT: usize = 80;++/// Rollout reader state, so a reopened file never replays an item.+#[derive(Debug, Default)]+pub(crate) struct CodexLog {+ seen: HashSet<String>,+}++impl CodexLog {+ /// Translate one rollout line.+ pub(crate) fn entry(&mut self, line: &str) -> Vec<LogEvent> {+ let Ok(entry) = serde_json::from_str::<Value>(line) else {+ return Vec::new();+ };+ if entry.get("type").and_then(Value::as_str) != Some("event_msg") {+ return Vec::new();+ }+ let Some(payload) = entry.get("payload") else {+ return Vec::new();+ };+ match payload.get("type").and_then(Value::as_str) {+ Some("item_completed") => {+ let Some(item) = payload.get("item") else {+ return Vec::new();+ };+ if let Some(id) = item.get("id").and_then(Value::as_str)+ && !self.seen.insert(id.to_owned())+ {+ return Vec::new();+ }+ item_update(item)+ .map(LogEvent::Update)+ .into_iter()+ .collect()+ }+ Some("task_complete") => vec![LogEvent::TurnEnded("end_turn")],+ Some("turn_aborted") => vec![LogEvent::TurnEnded("cancelled")],+ _ => Vec::new(),+ }+ }+}++fn texts(value: Option<&Value>, field: &str) -> String {+ value+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(|part| match part {+ Value::String(text) => Some(text.as_str()),+ part => part.get(field).and_then(Value::as_str),+ })+ .collect::<Vec<_>>()+ .join("\n")+}++fn item_update(item: &Value) -> Option<Value> {+ let id = item.get("id").and_then(Value::as_str).unwrap_or_default();+ let field = |name: &str| item.get(name).and_then(Value::as_str);+ match item.get("type").and_then(Value::as_str)? {+ "AgentMessage" => {+ let text = texts(item.get("content"), "text");+ (!text.is_empty()).then(|| {+ json!({+ "sessionUpdate": "agent_message_chunk",+ "content": {"type": "text", "text": text},+ })+ })+ }+ "Reasoning" => {+ let mut text = texts(item.get("summary_text"), "text");+ if text.is_empty() {+ text = texts(item.get("raw_content"), "text");+ }+ (!text.is_empty()).then(|| {+ json!({+ "sessionUpdate": "agent_thought_chunk",+ "content": {"type": "text", "text": text},+ })+ })+ }+ "CommandExecution" => {+ let command = command_line(item);+ let failed = field("status") == Some("failed")+ || item+ .get("exit_code")+ .and_then(Value::as_i64)+ .is_some_and(|code| code != 0);+ Some(tool_call(+ id,+ &format!("Run {}", clip(&command)),+ command_kind(item),+ failed,+ field("aggregated_output").unwrap_or_default(),+ json!({"command": command}),+ ))+ }+ "FileChange" => {+ let paths = changed_paths(item);+ let title = if paths.is_empty() {+ "Edit files".to_owned()+ } else {+ format!("Edit {}", clip(&paths.join(", ")))+ };+ Some(tool_call(+ id,+ &title,+ "edit",+ field("status") == Some("failed"),+ "",+ json!({"paths": paths}),+ ))+ }+ "McpToolCall" => {+ let name = [field("server"), field("tool")]+ .into_iter()+ .flatten()+ .collect::<Vec<_>>()+ .join(".");+ Some(tool_call(+ id,+ &format!("Call {}", if name.is_empty() { "tool" } else { &name }),+ "other",+ field("status") == Some("failed"),+ "",+ item.get("arguments").cloned().unwrap_or(Value::Null),+ ))+ }+ "WebSearch" => Some(tool_call(+ id,+ &format!("Search {}", clip(field("query").unwrap_or("the web"))),+ "search",+ false,+ "",+ Value::Null,+ )),+ _ => None,+ }+}++fn tool_call(+ id: &str,+ title: &str,+ kind: &str,+ failed: bool,+ output: &str,+ raw_input: Value,+) -> Value {+ let mut update = json!({+ "sessionUpdate": "tool_call",+ "toolCallId": id,+ "title": title,+ "kind": kind,+ "status": if failed { "failed" } else { "completed" },+ "rawInput": raw_input,+ });+ if !output.is_empty() {+ update["content"] = json!([{+ "type": "content",+ "content": {"type": "text", "text": truncate(output)},+ }]);+ }+ update+}++/// The script a command ran, without the `bash -lc` wrapper.+fn command_line(item: &Value) -> String {+ let argv: Vec<&str> = item+ .get("command")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .collect();+ match argv.as_slice() {+ [shell, flag, script] if shell.ends_with("sh") && flag.starts_with('-') => {+ (*script).to_owned()+ }+ argv => argv.join(" "),+ }+}++fn command_kind(item: &Value) -> &'static str {+ let kinds: Vec<&str> = item+ .get("parsed_cmd")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(|parsed| parsed.get("type").and_then(Value::as_str))+ .collect();+ if kinds.is_empty() {+ "execute"+ } else if kinds.iter().all(|kind| *kind == "read") {+ "read"+ } else if kinds+ .iter()+ .all(|kind| matches!(*kind, "search" | "list_files" | "read"))+ {+ "search"+ } else {+ "execute"+ }+}++fn changed_paths(item: &Value) -> Vec<String> {+ match item.get("changes") {+ Some(Value::Object(changes)) => changes.keys().cloned().collect(),+ Some(Value::Array(changes)) => changes+ .iter()+ .filter_map(|change| change.get("path").and_then(Value::as_str))+ .map(str::to_owned)+ .collect(),+ _ => Vec::new(),+ }+}++/// The first line of `text`, short enough for a tool title.+fn clip(text: &str) -> String {+ let line = text.lines().next().unwrap_or_default();+ let mut clipped: String = line.chars().take(TITLE_LIMIT).collect();+ if line.chars().count() > TITLE_LIMIT || text.lines().nth(1).is_some() {+ clipped.push('…');+ }+ clipped+}diff --git a/crates/coding_agent_worker/src/herdr/codex_log/test.rs b/crates/coding_agent_worker/src/herdr/codex_log/test.rsnew file mode 100644index 0000000000..7775836525--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/codex_log/test.rs@@ -0,0 +1,123 @@+use super::*;++fn event(payload: Value) -> String {+ json!({"timestamp": "2026-09-27T05:45:49Z", "type": "event_msg", "payload": payload})+ .to_string()+}++fn completed(item: Value) -> String {+ event(json!({"type": "item_completed", "thread_id": "t", "turn_id": "u", "item": item}))+}++#[test]+fn a_command_turn_streams_messages_commands_and_its_end() {+ let mut log = CodexLog::default();+ assert!(+ log.entry(&completed(+ json!({"type": "UserMessage", "id": "u1", "content": [{"type": "text", "text": "hi"}]})+ ))+ .is_empty()+ );+ assert_eq!(+ log.entry(&completed(json!({+ "type": "AgentMessage", "id": "m1", "phase": "commentary",+ "content": [{"type": "Text", "text": "I'll create hello.txt."}]+ }))),+ [LogEvent::Update(json!({+ "sessionUpdate": "agent_message_chunk",+ "content": {"type": "text", "text": "I'll create hello.txt."},+ }))]+ );+ let command = completed(json!({+ "type": "CommandExecution", "id": "exec-1",+ "command": ["/bin/bash", "-lc", "cat hello.txt"],+ "parsed_cmd": [{"type": "read", "cmd": "cat hello.txt", "name": "hello.txt"}],+ "status": "completed", "aggregated_output": "hi", "exit_code": 0+ }));+ assert_eq!(+ log.entry(&command),+ [LogEvent::Update(json!({+ "sessionUpdate": "tool_call",+ "toolCallId": "exec-1",+ "title": "Run cat hello.txt",+ "kind": "read",+ "status": "completed",+ "rawInput": {"command": "cat hello.txt"},+ "content": [{"type": "content", "content": {"type": "text", "text": "hi"}}],+ }))]+ );+ // A reopened rollout does not replay an item.+ assert!(log.entry(&command).is_empty());+ assert_eq!(+ log.entry(&event(+ json!({"type": "task_complete", "last_agent_message": "done"})+ )),+ [LogEvent::TurnEnded("end_turn")]+ );+}++#[test]+fn failed_multiline_commands_are_clipped_and_marked() {+ let mut log = CodexLog::default();+ let events = log.entry(&completed(json!({+ "type": "CommandExecution", "id": "exec-2",+ "command": ["/bin/bash", "-lc", "npm test\necho done"],+ "parsed_cmd": [{"type": "unknown", "cmd": "npm test"}],+ "status": "completed", "aggregated_output": "", "exit_code": 1+ })));+ let [LogEvent::Update(update)] = events.as_slice() else {+ panic!("one update, got {events:?}");+ };+ assert_eq!(update["title"], "Run npm test…");+ assert_eq!(update["kind"], "execute");+ assert_eq!(update["status"], "failed");+ assert!(update.get("content").is_none());+}++#[test]+fn reasoning_file_changes_and_aborts_are_translated() {+ let mut log = CodexLog::default();+ assert_eq!(+ log.entry(&completed(json!({"type": "Reasoning", "id": "r", "summary_text": ["Plan the app"], "raw_content": []}))),+ [LogEvent::Update(json!({+ "sessionUpdate": "agent_thought_chunk",+ "content": {"type": "text", "text": "Plan the app"},+ }))]+ );+ assert!(+ log.entry(&completed(+ json!({"type": "Reasoning", "id": "r2", "summary_text": [], "raw_content": []})+ ))+ .is_empty()+ );+ let events = log.entry(&completed(json!({+ "type": "FileChange", "id": "fc", "status": "completed",+ "changes": {"/r/index.html": {"type": "add"}, "/r/app.js": {"type": "add"}}+ })));+ let [LogEvent::Update(update)] = events.as_slice() else {+ panic!("one update, got {events:?}");+ };+ assert_eq!(update["kind"], "edit");+ assert!(update["title"].as_str().unwrap().starts_with("Edit /r/"));+ assert_eq!(+ log.entry(&event(+ json!({"type": "turn_aborted", "reason": "interrupted"})+ )),+ [LogEvent::TurnEnded("cancelled")]+ );+}++#[test]+fn bookkeeping_is_ignored() {+ let mut log = CodexLog::default();+ for line in [+ json!({"type": "session_meta", "payload": {"id": "s"}}).to_string(),+ json!({"type": "response_item", "payload": {"type": "message", "role": "assistant"}})+ .to_string(),+ event(json!({"type": "token_count"})),+ event(json!({"type": "task_started"})),+ "garbage".to_owned(),+ ] {+ assert!(log.entry(&line).is_empty());+ }+}diff --git a/crates/coding_agent_worker/src/herdr/hub.rs b/crates/coding_agent_worker/src/herdr/hub.rsnew file mode 100644index 0000000000..05ad2250ba--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/hub.rs@@ -0,0 +1,543 @@+//! The daemon-side half of the herdr integration: follows every ACP session+//! on the wire tap, opens a herdr window per session, keeps herdr's sidebar+//! in step with each turn, and serves the windows over a local socket.+//!+//! Nothing here speaks ACP to the agent. Windows steer a session through the+//! Macro control API, exactly as the web app does, so a prompt typed in herdr+//! is the same turn Macro records, folds, and shows.++use std::collections::{HashMap, VecDeque};+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex, MutexGuard};++use agent_client_protocol::LineDirection;+use agent_runtime_protocol::domain::action::AgentAction;+use agent_session::domain::model::AgentSessionId;+use macro_user_id::user_id::MacroUserIdStr;+use serde_json::Value;+use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader};+use tokio::net::{UnixListener, UnixStream};+use tokio::sync::mpsc;+use tokio_util::task::AbortOnDropHandle;++use super::HerdrSession;+use super::cli::{HerdrCli, Window};+use super::tap::{TapEvent, WireTap};+use super::wire::{AgentState, FromPane, ToPane};+use crate::outbound::agent_session::HarnessApi;++#[cfg(test)]+mod test;++/// How many wire events a window can replay on attach. Chunked agent output+/// is many small updates per message, so this is sized in updates, not turns.+const BACKLOG_LIMIT: usize = 20_000;+const TITLE_LIMIT: usize = 48;+const DISPLAY_AGENT: &str = "Macro agent";++type Owner = MacroUserIdStr<'static>;++/// A handle on the running integration. Cheap to clone; the socket and its+/// tasks stop when the last clone drops.+#[derive(Clone)]+pub(crate) struct Hub {+ inner: Arc<Inner>,+ _running: Arc<Running>,+}++struct Running {+ _serve: AbortOnDropHandle<()>,+ _windows: AbortOnDropHandle<()>,+ socket: PathBuf,+}++impl Drop for Running {+ fn drop(&mut self) {+ let _ = std::fs::remove_file(&self.socket);+ }+}++struct Inner {+ state: Mutex<HubState>,+ api: HarnessApi,+ web_url: String,+}++impl Hub {+ /// Bind the window socket and start opening windows in `herdr`.+ pub(crate) fn start(+ herdr: &HerdrSession,+ api: HarnessApi,+ workspace: &Path,+ web_url: &str,+ ) -> std::io::Result<Self> {+ let socket = socket_path();+ let _ = std::fs::remove_file(&socket);+ let listener = UnixListener::bind(&socket)?;+ restrict_to_owner(&socket)?;++ let (work_tx, work_rx) = mpsc::unbounded_channel();+ let inner = Arc::new(Inner {+ state: Mutex::new(HubState::new(work_tx)),+ api,+ web_url: web_url.trim_end_matches('/').to_owned(),+ });+ let launcher = Launcher {+ cli: HerdrCli::new(&herdr.bin, herdr.workspace_id.clone()),+ workspace: workspace.to_owned(),+ pane_command: pane_command(&socket),+ windows: HashMap::new(),+ seq: 0,+ };+ tracing::info!(+ socket = %socket.display(),+ workspace = %workspace.display(),+ "herdr detected; each agent session opens in its own herdr tab"+ );+ Ok(Self {+ _running: Arc::new(Running {+ _serve: AbortOnDropHandle::new(tokio::spawn(serve(inner.clone(), listener))),+ _windows: AbortOnDropHandle::new(tokio::spawn(launcher.run(work_rx))),+ socket,+ }),+ inner,+ })+ }++ /// The observer to hang on the harness's ACP wire.+ pub(crate) fn tap(&self) -> impl Fn(&str, LineDirection) + Send + Sync + 'static {+ let inner = self.inner.clone();+ move |line, direction| inner.lock().observe(line, direction)+ }++ /// The daemon opened a Macro session for `owner`; its ACP session is+ /// about to open (or just has).+ pub(crate) fn session_created(&self, session: AgentSessionId, owner: Owner) {+ self.inner.lock().session_created(session, owner);+ }++ /// `owner` prompted an existing session from Macro.+ pub(crate) fn owner_seen(&self, session: AgentSessionId, owner: Owner) {+ self.inner.lock().owners.insert(session, owner);+ }+}++impl Inner {+ fn lock(&self) -> MutexGuard<'_, HubState> {+ self.state+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ }++ fn web_url(&self, session: Option<AgentSessionId>) -> Option<String> {+ session.map(|session| format!("{}/agent/{session}", self.web_url))+ }+}++/// Work for herdr, done in order on one task so a report never races the+/// window it reports on.+#[derive(Debug, Clone, PartialEq)]+pub(crate) enum Work {+ Open {+ session: String,+ },+ Report {+ session: String,+ state: AgentState,+ message: Option<String>,+ },+ Title {+ session: String,+ title: String,+ },+}++#[derive(Default)]+struct SessionView {+ macro_session: Option<AgentSessionId>,+ backlog: VecDeque<ToPane>,+ subscribers: Vec<mpsc::UnboundedSender<ToPane>>,+ titled: bool,+ opened: bool,+}++impl SessionView {+ fn push(&mut self, message: ToPane) {+ self.subscribers+ .retain(|subscriber| subscriber.send(message.clone()).is_ok());+ if self.backlog.len() == BACKLOG_LIMIT {+ self.backlog.pop_front();+ }+ self.backlog.push_back(message);+ }+}++pub(crate) struct HubState {+ tap: WireTap,+ sessions: HashMap<String, SessionView>,+ owners: HashMap<AgentSessionId, Owner>,+ /// Macro sessions this daemon created that no ACP session has claimed,+ /// for services that do not name the Macro session in `_meta`.+ unclaimed_macro: VecDeque<AgentSessionId>,+ unclaimed_acp: VecDeque<String>,+ work: mpsc::UnboundedSender<Work>,+}++impl HubState {+ pub(crate) fn new(work: mpsc::UnboundedSender<Work>) -> Self {+ Self {+ tap: WireTap::default(),+ sessions: HashMap::new(),+ owners: HashMap::new(),+ unclaimed_macro: VecDeque::new(),+ unclaimed_acp: VecDeque::new(),+ work,+ }+ }++ fn observe(&mut self, line: &str, direction: LineDirection) {+ for event in self.tap.observe(line, direction) {+ self.apply(event);+ }+ }++ fn queue(&self, work: Work) {+ let _ = self.work.send(work);+ }++ fn session_created(&mut self, session: AgentSessionId, owner: Owner) {+ self.owners.insert(session, owner);+ if self+ .sessions+ .values()+ .any(|view| view.macro_session == Some(session))+ {+ return;+ }+ match self.unclaimed_acp.pop_front() {+ Some(acp) => self.bind(&acp, session),+ None => self.unclaimed_macro.push_back(session),+ }+ }++ fn bind(&mut self, acp: &str, session: AgentSessionId) {+ self.unclaimed_macro+ .retain(|unclaimed| *unclaimed != session);+ let view = self.sessions.entry(acp.to_owned()).or_default();+ view.macro_session = Some(session);+ }++ pub(crate) fn apply(&mut self, event: TapEvent) {+ match event {+ TapEvent::Opened {+ session,+ macro_session,+ } => {+ let known = self+ .sessions+ .get(&session)+ .and_then(|view| view.macro_session);+ match (macro_session, known) {+ (Some(named), _) => self.bind(&session, named),+ (None, Some(_)) => {}+ (None, None) => match self.unclaimed_macro.pop_front() {+ Some(claimed) => self.bind(&session, claimed),+ None => {+ self.sessions.entry(session.clone()).or_default();+ self.unclaimed_acp.push_back(session.clone());+ }+ },+ }+ let view = self.sessions.entry(session.clone()).or_default();+ if !view.opened {+ view.opened = true;+ self.queue(Work::Open {+ session: session.clone(),+ });+ self.queue(Work::Report {+ session,+ state: AgentState::Idle,+ message: None,+ });+ }+ }+ TapEvent::Prompted { session, text } => {+ let view = self.sessions.entry(session.clone()).or_default();+ view.push(ToPane::Prompted { text: text.clone() });+ view.push(ToPane::State {+ state: AgentState::Working,+ detail: None,+ });+ let first = !std::mem::replace(&mut view.titled, true);+ if first && let Some(title) = title_from(&text) {+ self.queue(Work::Title {+ session: session.clone(),+ title,+ });+ }+ self.queue(Work::Report {+ session,+ state: AgentState::Working,+ message: None,+ });+ }+ TapEvent::Update { session, update } => {+ let title = (update.get("sessionUpdate").and_then(Value::as_str)+ == Some("session_info_update"))+ .then(|| {+ update+ .get("title")+ .and_then(Value::as_str)+ .and_then(title_from)+ })+ .flatten();+ let view = self.sessions.entry(session.clone()).or_default();+ view.push(ToPane::Update { update });+ if let Some(title) = title {+ view.titled = true;+ self.queue(Work::Title { session, title });+ }+ }+ TapEvent::TurnEnded {+ session,+ stop_reason,+ } => {+ let view = self.sessions.entry(session.clone()).or_default();+ view.push(ToPane::State {+ state: AgentState::Idle,+ detail: Some(stop_reason.clone()),+ });+ self.queue(Work::Report {+ session,+ state: AgentState::Idle,+ message: Some(stop_reason),+ });+ }+ TapEvent::PermissionAsked {+ session,+ request_id,+ title,+ options,+ } => {+ let view = self.sessions.entry(session.clone()).or_default();+ view.push(ToPane::Permission {+ request_id,+ title: title.clone(),+ options,+ });+ view.push(ToPane::State {+ state: AgentState::Blocked,+ detail: title.clone(),+ });+ self.queue(Work::Report {+ session,+ state: AgentState::Blocked,+ message: title.map(|title| format!("permission: {title}")),+ });+ }+ TapEvent::PermissionAnswered { session } => {+ let view = self.sessions.entry(session.clone()).or_default();+ view.push(ToPane::PermissionSettled);+ view.push(ToPane::State {+ state: AgentState::Working,+ detail: None,+ });+ self.queue(Work::Report {+ session,+ state: AgentState::Working,+ message: None,+ });+ }+ }+ }++ /// Who may steer `session` from a window, and as whom.+ fn control_target(&self, session: &str) -> Option<(AgentSessionId, Owner)> {+ let macro_session = self.sessions.get(session)?.macro_session?;+ let owner = self.owners.get(¯o_session)?.clone();+ Some((macro_session, owner))+ }+}++/// The first line of a prompt, short enough for a tab label.+pub(crate) fn title_from(text: &str) -> Option<String> {+ let line = text.lines().map(str::trim).find(|line| !line.is_empty())?;+ let mut title: String = line.chars().take(TITLE_LIMIT).collect();+ if line.chars().count() > TITLE_LIMIT {+ title.push('…');+ }+ Some(title)+}++struct Launcher {+ cli: HerdrCli,+ workspace: PathBuf,+ pane_command: Vec<String>,+ windows: HashMap<String, Window>,+ seq: u64,+}++impl Launcher {+ async fn run(mut self, mut work: mpsc::UnboundedReceiver<Work>) {+ while let Some(item) = work.recv().await {+ if let Err(error) = self.handle(item).await {+ tracing::warn!(error = %error, "herdr command failed");+ }+ }+ }++ async fn handle(&mut self, work: Work) -> Result<(), super::cli::HerdrError> {+ match work {+ Work::Open { session } => {+ let window = self+ .cli+ .open_window(&self.workspace, "macro", false)+ .await?;+ let mut command = self.pane_command.clone();+ command.extend(["--session".to_owned(), session.clone()]);+ self.cli+ .run_in_pane(&window.pane_id, &shell_words::join(&command))+ .await?;+ self.cli+ .report_title(&window.pane_id, DISPLAY_AGENT, None)+ .await?;+ tracing::info!(+ %session,+ tab = %window.tab_id,+ pane = %window.pane_id,+ "opened a herdr window for the session"+ );+ self.windows.insert(session, window);+ }+ Work::Report {+ session,+ state,+ message,+ } => {+ let Some(window) = self.windows.get(&session) else {+ return Ok(());+ };+ self.seq += 1;+ self.cli+ .report_state(&window.pane_id, state, message.as_deref(), self.seq)+ .await?;+ }+ Work::Title { session, title } => {+ let Some(window) = self.windows.get(&session) else {+ return Ok(());+ };+ self.cli.rename_tab(&window.tab_id, &title).await?;+ self.cli+ .report_title(&window.pane_id, DISPLAY_AGENT, Some(&title))+ .await?;+ }+ }+ Ok(())+ }+}++fn socket_path() -> PathBuf {+ std::env::temp_dir().join(format!("macrod-herdr-{}.sock", std::process::id()))+}++fn restrict_to_owner(socket: &Path) -> std::io::Result<()> {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o600))+}++/// `macrod herdr-pane --socket …`, before the session argument.+fn pane_command(socket: &Path) -> Vec<String> {+ let exe = std::env::current_exe()+ .map(|exe| exe.to_string_lossy().into_owned())+ .unwrap_or_else(|_| "macrod".to_owned());+ vec![+ exe,+ "herdr-pane".to_owned(),+ "--socket".to_owned(),+ socket.to_string_lossy().into_owned(),+ ]+}++async fn serve(inner: Arc<Inner>, listener: UnixListener) {+ loop {+ match listener.accept().await {+ Ok((stream, _)) => {+ tokio::spawn(serve_window(inner.clone(), stream));+ }+ Err(error) => {+ tracing::warn!(error = %error, "herdr window socket failed");+ return;+ }+ }+ }+}++async fn serve_window(inner: Arc<Inner>, stream: UnixStream) {+ let (read, mut write) = stream.into_split();+ let mut lines = BufReader::new(read).lines();+ let Ok(Some(first)) = lines.next_line().await else {+ return;+ };+ let Ok(FromPane::Attach { session }) = serde_json::from_str(&first) else {+ return;+ };++ let (tx, mut rx) = mpsc::unbounded_channel();+ {+ let mut state = inner.lock();+ let view = state.sessions.entry(session.clone()).or_default();+ let _ = tx.send(ToPane::Hello {+ session: session.clone(),+ web_url: inner.web_url(view.macro_session),+ });+ for message in &view.backlog {+ let _ = tx.send(message.clone());+ }+ view.subscribers.push(tx.clone());+ }++ loop {+ tokio::select! {+ message = rx.recv() => {+ let Some(message) = message else { return };+ let Ok(mut line) = serde_json::to_string(&message) else { continue };+ line.push('\n');+ if write.write_all(line.as_bytes()).await.is_err() {+ return;+ }+ }+ line = lines.next_line() => {+ let Ok(Some(line)) = line else { return };+ let Ok(request) = serde_json::from_str::<FromPane>(&line) else { continue };+ let inner = inner.clone();+ let session = session.clone();+ let tx = tx.clone();+ tokio::spawn(async move {+ if let Err(text) = steer(&inner, &session, request).await {+ let _ = tx.send(ToPane::Notice { text, error: true });+ }+ });+ }+ }+ }+}++/// Carry a window's request to the session through Macro.+async fn steer(inner: &Inner, session: &str, request: FromPane) -> Result<(), String> {+ let action = match request {+ FromPane::Attach { .. } => return Ok(()),+ FromPane::Prompt { text } => AgentAction::prompt(text),+ FromPane::Stop => AgentAction::Stop,+ };+ let target = inner.lock().control_target(session);+ let Some((macro_session, owner)) = target else {+ return Err(+ "this session was not opened by this macrod run; steer it from Macro".to_owned(),+ );+ };+ inner+ .api+ .control(macro_session, &owner, action)+ .await+ .map_err(|error| format!("Macro refused: {error}"))+}diff --git a/crates/coding_agent_worker/src/herdr/hub/test.rs b/crates/coding_agent_worker/src/herdr/hub/test.rsnew file mode 100644index 0000000000..9656d03491--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/hub/test.rs@@ -0,0 +1,158 @@+use super::*;++fn owner() -> Owner {+ MacroUserIdStr::try_from_email("[email protected]").unwrap()+}++fn macro_id(n: u128) -> AgentSessionId {+ AgentSessionId::new_from_uuid(uuid::Uuid::from_u128(n))+}++fn state() -> (HubState, mpsc::UnboundedReceiver<Work>) {+ let (tx, rx) = mpsc::unbounded_channel();+ (HubState::new(tx), rx)+}++fn drain(rx: &mut mpsc::UnboundedReceiver<Work>) -> Vec<Work> {+ std::iter::from_fn(|| rx.try_recv().ok()).collect()+}++fn opened(session: &str, macro_session: Option<AgentSessionId>) -> TapEvent {+ TapEvent::Opened {+ session: session.to_owned(),+ macro_session,+ }+}++#[test]+fn a_named_session_opens_one_window_and_is_steerable() {+ let (mut hub, mut work) = state();+ hub.session_created(macro_id(1), owner());+ hub.apply(opened("acp-1", Some(macro_id(1))));+ // A later load of the same session does not open a second window.+ hub.apply(opened("acp-1", Some(macro_id(1))));++ assert_eq!(+ drain(&mut work),+ [+ Work::Open {+ session: "acp-1".to_owned()+ },+ Work::Report {+ session: "acp-1".to_owned(),+ state: AgentState::Idle,+ message: None,+ },+ ]+ );+ assert_eq!(hub.control_target("acp-1"), Some((macro_id(1), owner())));+ assert!(hub.unclaimed_macro.is_empty());+}++#[test]+fn unnamed_sessions_pair_with_created_ones_in_order_either_way() {+ let (mut hub, _work) = state();+ // The create answered before the agent did.+ hub.session_created(macro_id(1), owner());+ hub.apply(opened("acp-1", None));+ // The agent answered before the create did.+ hub.apply(opened("acp-2", None));+ hub.session_created(macro_id(2), owner());++ assert_eq!(hub.control_target("acp-1").map(|t| t.0), Some(macro_id(1)));+ assert_eq!(hub.control_target("acp-2").map(|t| t.0), Some(macro_id(2)));+}++#[test]+fn a_session_without_an_owner_is_view_only() {+ let (mut hub, _work) = state();+ hub.apply(opened("acp-1", Some(macro_id(1))));+ assert_eq!(hub.control_target("acp-1"), None);+ hub.owners.insert(macro_id(1), owner());+ assert!(hub.control_target("acp-1").is_some());+}++#[test]+fn a_turn_titles_the_window_once_and_reports_each_state() {+ let (mut hub, mut work) = state();+ hub.apply(opened("s", None));+ drain(&mut work);++ hub.apply(TapEvent::Prompted {+ session: "s".to_owned(),+ text: "\n Fix the flaky login test in the auth service please\nmore".to_owned(),+ });+ hub.apply(TapEvent::Prompted {+ session: "s".to_owned(),+ text: "second".to_owned(),+ });+ hub.apply(TapEvent::TurnEnded {+ session: "s".to_owned(),+ stop_reason: "end_turn".to_owned(),+ });++ let work = drain(&mut work);+ let titles: Vec<_> = work+ .iter()+ .filter_map(|item| match item {+ Work::Title { title, .. } => Some(title.as_str()),+ _ => None,+ })+ .collect();+ assert_eq!(+ titles,+ ["Fix the flaky login test in the auth service ple…"]+ );+ let states: Vec<_> = work+ .iter()+ .filter_map(|item| match item {+ Work::Report { state, .. } => Some(*state),+ _ => None,+ })+ .collect();+ assert_eq!(+ states,+ [AgentState::Working, AgentState::Working, AgentState::Idle]+ );+}++#[test]+fn windows_replay_the_backlog_and_follow_live() {+ let (mut hub, _work) = state();+ hub.apply(opened("s", None));+ hub.apply(TapEvent::Prompted {+ session: "s".to_owned(),+ text: "hi".to_owned(),+ });+ let (tx, mut rx) = mpsc::unbounded_channel();+ let view = hub.sessions.get_mut("s").unwrap();+ assert_eq!(+ view.backlog.front(),+ Some(&ToPane::Prompted {+ text: "hi".to_owned()+ })+ );+ view.subscribers.push(tx);++ hub.apply(TapEvent::PermissionAsked {+ session: "s".to_owned(),+ request_id: serde_json::json!(4),+ title: Some("Edit main.rs".to_owned()),+ options: Vec::new(),+ });+ assert_eq!(+ rx.try_recv().unwrap(),+ ToPane::Permission {+ request_id: serde_json::json!(4),+ title: Some("Edit main.rs".to_owned()),+ options: Vec::new(),+ }+ );+ assert_eq!(+ rx.try_recv().unwrap(),+ ToPane::State {+ state: AgentState::Blocked,+ detail: Some("Edit main.rs".to_owned()),+ }+ );+}diff --git a/crates/coding_agent_worker/src/herdr/tap.rs b/crates/coding_agent_worker/src/herdr/tap.rsnew file mode 100644index 0000000000..dbc8acfca8--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/tap.rs@@ -0,0 +1,249 @@+//! Reads the per-session story out of the ACP lines crossing the harness's+//! stdio. The harness serves every session over one process, so the tap+//! follows request ids to learn which session a response closes.++use std::collections::HashMap;++use agent_client_protocol::LineDirection;+use agent_session::domain::model::{AgentSessionId, MACRO_AGENT_SESSION_META_KEY};+use serde_json::Value;++use super::wire::PermissionChoice;++#[cfg(test)]+mod test;++/// Something that happened to one ACP session.+#[derive(Debug, Clone, PartialEq)]+pub(crate) enum TapEvent {+ /// The agent is serving a session: `session/new` answered, or a+ /// `session/load`/`session/resume` named it.+ Opened {+ /// The ACP session id.+ session: String,+ /// The Macro session, when the service named it in `_meta`.+ macro_session: Option<AgentSessionId>,+ },+ /// A prompt went to the agent.+ Prompted {+ /// The ACP session id.+ session: String,+ /// The prompt's text blocks, joined.+ text: String,+ },+ /// The agent streamed a `session/update`.+ Update {+ /// The ACP session id.+ session: String,+ /// The notification's `update` object.+ update: Value,+ },+ /// The agent answered a prompt.+ TurnEnded {+ /// The ACP session id.+ session: String,+ /// The stop reason, or `error` for a failed prompt.+ stop_reason: String,+ },+ /// The agent asked permission for a tool call.+ PermissionAsked {+ /// The ACP session id.+ session: String,+ /// The agent's JSON-RPC request id, which the answer must echo.+ request_id: Value,+ /// The tool call's title, when it has one.+ title: Option<String>,+ /// The choices the agent offered.+ options: Vec<PermissionChoice>,+ },+ /// The client answered the agent's permission request.+ PermissionAnswered {+ /// The ACP session id.+ session: String,+ },+}++/// Correlation state across lines.+#[derive(Debug, Default)]+pub(crate) struct WireTap {+ /// `session/new` requests awaiting their answer, by request id.+ opening: HashMap<String, Option<AgentSessionId>>,+ /// `session/prompt` requests awaiting their answer, by request id.+ prompts: HashMap<String, String>,+ /// Permission requests from the agent awaiting an answer, by request id.+ permissions: HashMap<String, String>,+}++impl WireTap {+ /// Observe one line. Lines that are not JSON-RPC (stderr, garbage) and+ /// traffic this tap does not follow produce nothing.+ pub(crate) fn observe(&mut self, line: &str, direction: LineDirection) -> Vec<TapEvent> {+ let to_agent = match direction {+ LineDirection::Stdin => true,+ LineDirection::Stdout => false,+ LineDirection::Stderr => return Vec::new(),+ };+ let Ok(message) = serde_json::from_str::<Value>(line) else {+ return Vec::new();+ };+ let id = message+ .get("id")+ .filter(|id| !id.is_null())+ .map(Value::to_string);+ let method = message.get("method").and_then(Value::as_str);+ let params = message.get("params");++ let raw_id = message.get("id").filter(|id| !id.is_null());++ match (method, id) {+ (Some(method), id) if to_agent => self.client_sent(method, id, params),+ (Some(method), id) => self.agent_sent(method, id, raw_id, params),+ (None, Some(id)) if to_agent => self+ .permissions+ .remove(&id)+ .map(|session| vec![TapEvent::PermissionAnswered { session }])+ .unwrap_or_default(),+ (None, Some(id)) => self.agent_answered(&id, &message),+ (None, None) => Vec::new(),+ }+ }++ fn client_sent(+ &mut self,+ method: &str,+ id: Option<String>,+ params: Option<&Value>,+ ) -> Vec<TapEvent> {+ match method {+ "session/new" => {+ if let Some(id) = id {+ self.opening.insert(id, macro_session(params));+ }+ Vec::new()+ }+ "session/load" | "session/resume" => session_id(params)+ .map(|session| {+ vec![TapEvent::Opened {+ session,+ macro_session: macro_session(params),+ }]+ })+ .unwrap_or_default(),+ "session/prompt" => {+ let Some(session) = session_id(params) else {+ return Vec::new();+ };+ if let Some(id) = id {+ self.prompts.insert(id, session.clone());+ }+ let text = params+ .and_then(|params| params.get("prompt"))+ .map(prompt_text)+ .unwrap_or_default();+ vec![TapEvent::Prompted { session, text }]+ }+ _ => Vec::new(),+ }+ }++ fn agent_sent(+ &mut self,+ method: &str,+ id: Option<String>,+ raw_id: Option<&Value>,+ params: Option<&Value>,+ ) -> Vec<TapEvent> {+ let Some(session) = session_id(params) else {+ return Vec::new();+ };+ match method {+ "session/update" => params+ .and_then(|params| params.get("update"))+ .map(|update| {+ vec![TapEvent::Update {+ session,+ update: update.clone(),+ }]+ })+ .unwrap_or_default(),+ "session/request_permission" => {+ let Some(id) = id else {+ return Vec::new();+ };+ let Some(request_id) = raw_id.cloned() else {+ return Vec::new();+ };+ self.permissions.insert(id, session.clone());+ let title = params+ .and_then(|params| params.pointer("/toolCall/title"))+ .and_then(Value::as_str)+ .map(str::to_owned);+ let options = params+ .and_then(|params| params.get("options"))+ .and_then(|options| {+ serde_json::from_value::<Vec<PermissionChoice>>(options.clone()).ok()+ })+ .unwrap_or_default();+ vec![TapEvent::PermissionAsked {+ session,+ request_id,+ title,+ options,+ }]+ }+ _ => Vec::new(),+ }+ }++ fn agent_answered(&mut self, id: &str, message: &Value) -> Vec<TapEvent> {+ if let Some(macro_session) = self.opening.remove(id) {+ return message+ .pointer("/result/sessionId")+ .and_then(Value::as_str)+ .map(|session| {+ vec![TapEvent::Opened {+ session: session.to_owned(),+ macro_session,+ }]+ })+ .unwrap_or_default();+ }+ if let Some(session) = self.prompts.remove(id) {+ let stop_reason = message+ .pointer("/result/stopReason")+ .and_then(Value::as_str)+ .unwrap_or("error")+ .to_owned();+ return vec![TapEvent::TurnEnded {+ session,+ stop_reason,+ }];+ }+ Vec::new()+ }+}++fn session_id(params: Option<&Value>) -> Option<String> {+ params?.get("sessionId")?.as_str().map(str::to_owned)+}++fn macro_session(params: Option<&Value>) -> Option<AgentSessionId> {+ let raw = params?+ .get("_meta")?+ .get(MACRO_AGENT_SESSION_META_KEY)?+ .as_str()?;+ uuid::Uuid::parse_str(raw)+ .ok()+ .map(AgentSessionId::new_from_uuid)+}++fn prompt_text(prompt: &Value) -> String {+ prompt+ .as_array()+ .into_iter()+ .flatten()+ .filter(|block| block.get("type").and_then(Value::as_str) == Some("text"))+ .filter_map(|block| block.get("text").and_then(Value::as_str))+ .collect::<Vec<_>>()+ .join("\n")+}diff --git a/crates/coding_agent_worker/src/herdr/tap/test.rs b/crates/coding_agent_worker/src/herdr/tap/test.rsnew file mode 100644index 0000000000..0948aaa378--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/tap/test.rs@@ -0,0 +1,194 @@+use agent_client_protocol::LineDirection::{Stderr, Stdin, Stdout};+use serde_json::json;++use super::*;++fn line(value: Value) -> String {+ value.to_string()+}++#[test]+fn session_new_answer_opens_the_session_with_its_macro_id() {+ let mut tap = WireTap::default();+ let macro_id = "0195d2dd-5de9-71f2-9d59-5d9734f1adb7";+ let request = line(json!({+ "jsonrpc": "2.0", "id": 7, "method": "session/new",+ "params": {"cwd": "/repo", "mcpServers": [], "_meta": {MACRO_AGENT_SESSION_META_KEY: macro_id}}+ }));+ assert!(tap.observe(&request, Stdin).is_empty());++ let answer = line(json!({"jsonrpc": "2.0", "id": 7, "result": {"sessionId": "acp-1"}}));+ assert_eq!(+ tap.observe(&answer, Stdout),+ [TapEvent::Opened {+ session: "acp-1".to_owned(),+ macro_session: Some(AgentSessionId::new_from_uuid(+ uuid::Uuid::parse_str(macro_id).unwrap()+ )),+ }]+ );+}++#[test]+fn session_new_without_meta_opens_an_unnamed_session() {+ let mut tap = WireTap::default();+ tap.observe(+ &line(+ json!({"jsonrpc": "2.0", "id": "a", "method": "session/new", "params": {"cwd": "/"}}),+ ),+ Stdin,+ );+ assert_eq!(+ tap.observe(+ &line(json!({"jsonrpc": "2.0", "id": "a", "result": {"sessionId": "acp-2"}})),+ Stdout+ ),+ [TapEvent::Opened {+ session: "acp-2".to_owned(),+ macro_session: None,+ }]+ );+}++#[test]+fn load_names_the_session_directly() {+ let mut tap = WireTap::default();+ let events = tap.observe(+ &line(json!({+ "jsonrpc": "2.0", "id": 1, "method": "session/load",+ "params": {"sessionId": "acp-3", "cwd": "/", "mcpServers": []}+ })),+ Stdin,+ );+ assert_eq!(+ events,+ [TapEvent::Opened {+ session: "acp-3".to_owned(),+ macro_session: None,+ }]+ );+}++#[test]+fn a_prompt_turn_runs_until_its_answer() {+ let mut tap = WireTap::default();+ let prompt = line(json!({+ "jsonrpc": "2.0", "id": 9, "method": "session/prompt",+ "params": {"sessionId": "acp-1", "prompt": [+ {"type": "text", "text": "fix the bug"},+ {"type": "resource_link", "uri": "file:///a", "name": "a"},+ {"type": "text", "text": "please"}+ ]}+ }));+ assert_eq!(+ tap.observe(&prompt, Stdin),+ [TapEvent::Prompted {+ session: "acp-1".to_owned(),+ text: "fix the bug\nplease".to_owned(),+ }]+ );++ let update = json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "on it"}});+ assert_eq!(+ tap.observe(+ &line(json!({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "acp-1", "update": update}})),+ Stdout+ ),+ [TapEvent::Update {+ session: "acp-1".to_owned(),+ update,+ }]+ );++ assert_eq!(+ tap.observe(+ &line(json!({"jsonrpc": "2.0", "id": 9, "result": {"stopReason": "end_turn"}})),+ Stdout+ ),+ [TapEvent::TurnEnded {+ session: "acp-1".to_owned(),+ stop_reason: "end_turn".to_owned(),+ }]+ );+}++#[test]+fn a_failed_prompt_ends_the_turn_as_an_error() {+ let mut tap = WireTap::default();+ tap.observe(+ &line(json!({"jsonrpc": "2.0", "id": 2, "method": "session/prompt", "params": {"sessionId": "s", "prompt": []}})),+ Stdin,+ );+ assert_eq!(+ tap.observe(+ &line(json!({"jsonrpc": "2.0", "id": 2, "error": {"code": -32603, "message": "boom"}})),+ Stdout+ ),+ [TapEvent::TurnEnded {+ session: "s".to_owned(),+ stop_reason: "error".to_owned(),+ }]+ );+}++#[test]+fn a_permission_request_blocks_until_answered() {+ let mut tap = WireTap::default();+ let ask = line(json!({+ "jsonrpc": "2.0", "id": 0, "method": "session/request_permission",+ "params": {"sessionId": "acp-1", "toolCall": {"toolCallId": "t", "title": "Run rm -rf"}, "options": [+ {"optionId": "allow", "name": "Allow", "kind": "allow_once"},+ {"optionId": "reject", "name": "Reject", "kind": "reject_once"}+ ]}+ }));+ assert_eq!(+ tap.observe(&ask, Stdout),+ [TapEvent::PermissionAsked {+ session: "acp-1".to_owned(),+ request_id: json!(0),+ title: Some("Run rm -rf".to_owned()),+ options: vec![+ PermissionChoice {+ option_id: "allow".to_owned(),+ name: "Allow".to_owned(),+ kind: "allow_once".to_owned(),+ },+ PermissionChoice {+ option_id: "reject".to_owned(),+ name: "Reject".to_owned(),+ kind: "reject_once".to_owned(),+ },+ ],+ }]+ );+ // The agent's own request ids live in a separate space from the+ // client's: the same id answered on stdin is the permission answer.+ assert_eq!(+ tap.observe(+ &line(+ json!({"jsonrpc": "2.0", "id": 0, "result": {"outcome": {"outcome": "cancelled"}}})+ ),+ Stdin+ ),+ [TapEvent::PermissionAnswered {+ session: "acp-1".to_owned(),+ }]+ );+}++#[test]+fn stderr_and_noise_are_ignored() {+ let mut tap = WireTap::default();+ assert!(+ tap.observe("{\"method\":\"session/update\"}", Stderr)+ .is_empty()+ );+ assert!(tap.observe("not json", Stdout).is_empty());+ assert!(+ tap.observe(+ &line(json!({"jsonrpc": "2.0", "id": 99, "result": {}})),+ Stdout+ )+ .is_empty()+ );+}diff --git a/crates/coding_agent_worker/src/herdr/test.rs b/crates/coding_agent_worker/src/herdr/test.rsnew file mode 100644index 0000000000..03ae1eb3c8--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/test.rs@@ -0,0 +1,38 @@+use super::acp_agent::TuiAgent;+use super::*;++fn harness(args: &[&str]) -> Harness {+ Harness {+ command: "/bin/macrod".to_owned(),+ args: args.iter().map(|arg| (*arg).to_owned()).collect(),+ env: Default::default(),+ }+}++#[test]+fn herdr_harnesses_name_their_agent() {+ assert_eq!(+ herdr_agent(&harness(&["herdr-acp"])),+ Some(TuiAgent::Claude)+ );+ assert_eq!(+ herdr_agent(&harness(&["herdr-acp", "--permission-mode", "acceptEdits"])),+ Some(TuiAgent::Claude)+ );+ assert_eq!(+ herdr_agent(&harness(&["herdr-acp", "--kind", "codex"])),+ Some(TuiAgent::Codex)+ );+ assert_eq!(+ herdr_agent(&harness(&[+ "herdr-acp",+ "--kind=codex",+ "--",+ "--kind",+ "claude"+ ])),+ Some(TuiAgent::Codex)+ );+ assert_eq!(herdr_agent(&harness(&["acp"])), None);+ assert!(!drives_herdr(&harness(&["acp"])));+}diff --git a/crates/coding_agent_worker/src/herdr/wire.rs b/crates/coding_agent_worker/src/herdr/wire.rsnew file mode 100644index 0000000000..867a91fd6f--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/wire.rs@@ -0,0 +1,106 @@+//! The local protocol between macrod and a `macrod herdr-pane` window:+//! newline-delimited JSON over a Unix socket only this user can open.++use serde::{Deserialize, Serialize};++/// Where an ACP session's turn stands, as herdr understands agents.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub(crate) enum AgentState {+ /// Waiting for a prompt.+ Idle,+ /// Running a turn.+ Working,+ /// Waiting on a permission answer.+ Blocked,+}++impl AgentState {+ /// The `--state` value `herdr pane report-agent` takes.+ pub(crate) fn as_herdr(self) -> &'static str {+ match self {+ Self::Idle => "idle",+ Self::Working => "working",+ Self::Blocked => "blocked",+ }+ }+}++/// One answer an agent offered to a permission request.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub(crate) struct PermissionChoice {+ /// The id the answer must name.+ pub option_id: String,+ /// What to show.+ pub name: String,+ /// `allow_once`, `allow_always`, `reject_once` or `reject_always`.+ pub kind: String,+}++/// macrod to a pane window.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "type", rename_all = "snake_case")]+pub(crate) enum ToPane {+ /// Sent first, once per attach.+ Hello {+ /// The ACP session this window shows.+ session: String,+ /// Where the session opens in the Macro web app, once known.+ web_url: Option<String>,+ },+ /// A prompt delivered to the agent, whoever sent it.+ Prompted {+ /// The prompt's text blocks, joined.+ text: String,+ },+ /// One ACP `session/update` payload, verbatim.+ Update {+ /// The `update` object of the notification.+ update: serde_json::Value,+ },+ /// The session's turn state changed.+ State {+ /// The new state.+ state: AgentState,+ /// Why, when there is something to say (a stop reason, a permission).+ detail: Option<String>,+ },+ /// The agent is waiting on a permission answer, which only a user in+ /// Macro may give: the service refuses approvals a runtime forwards.+ Permission {+ /// The agent's request id.+ request_id: serde_json::Value,+ /// The tool call it is about.+ title: Option<String>,+ /// What the agent offered.+ options: Vec<PermissionChoice>,+ },+ /// A permission request was answered, from here or from Macro.+ PermissionSettled,+ /// Something the window should tell its reader.+ Notice {+ /// The text.+ text: String,+ /// Whether it reports a failure.+ error: bool,+ },+}++/// A pane window to macrod.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "type", rename_all = "snake_case")]+pub(crate) enum FromPane {+ /// Subscribe to one ACP session. Must be the first message.+ Attach {+ /// The ACP session id.+ session: String,+ },+ /// Prompt the session through Macro.+ Prompt {+ /// The text to send.+ text: String,+ },+ /// Interrupt the running turn.+ Stop,+}diff --git a/crates/coding_agent_worker/src/main.rs b/crates/coding_agent_worker/src/main.rsindex 7e5a8dff01..9493318fcc 100644--- a/crates/coding_agent_worker/src/main.rs+++ b/crates/coding_agent_worker/src/main.rs@@ -19,6 +19,8 @@ mod config;mod daemon;mod dispatch;mod harness;+#[cfg(unix)]+mod herdr;mod outbound;mod runtime;mod trigger;@@ -36,6 +38,43 @@ struct Args {/// Internal browser helper, isolated so terminal browsers cannot claim the TUI's stdin.#[arg(long, hide = true)]open_url: Option<String>,+ #[command(subcommand)]+ command: Option<Command>,+}++#[derive(clap::Subcommand)]+enum Command {+ /// Show one agent session live inside a herdr window. macrod opens these+ /// itself when it runs inside herdr.+ #[cfg(unix)]+ #[command(hide = true)]+ HerdrPane {+ /// The running macrod's window socket.+ #[arg(long)]+ socket: std::path::PathBuf,+ /// The ACP session to follow.+ #[arg(long)]+ session: String,+ },+ /// Serve ACP on stdio with each session as a live coding-agent TUI in+ /// its own herdr window. Set as the harness of a macrod run inside herdr.+ #[cfg(unix)]+ HerdrAcp {+ /// Which agent TUI each session runs.+ #[arg(long, value_enum, default_value_t)]+ kind: herdr::acp_agent::TuiAgent,+ /// Claude Code's `--permission-mode` for every session, e.g.+ /// `acceptEdits` or `bypassPermissions`.+ #[arg(long)]+ permission_mode: Option<String>,+ /// Open each session's tab in the background rather than switching+ /// herdr to it.+ #[arg(long)]+ no_focus: bool,+ /// Extra arguments for every agent launch, e.g. `-- -s workspace-write`.+ #[arg(last = true)]+ agent_args: Vec<String>,+ },}#[tokio::main]@@ -55,6 +94,44 @@ async fn main() -> ExitCode {}};}+ #[cfg(unix)]+ match args.command {+ Some(Command::HerdrPane { socket, session }) => {+ return match tui::run_herdr_pane(&socket, &session).await {+ Ok(()) => ExitCode::SUCCESS,+ Err(error) => {+ eprintln!("macrod herdr-pane: {error:?}");+ ExitCode::FAILURE+ }+ };+ }+ Some(Command::HerdrAcp {+ kind,+ permission_mode,+ no_focus,+ agent_args,+ }) => {+ // stdout is the protocol: logs go to stderr, which macrod drains.+ tracing_subscriber::fmt()+ .with_writer(std::io::stderr)+ .init();+ return match herdr::acp_agent::run(herdr::acp_agent::AdapterOptions {+ kind,+ permission_mode,+ no_focus,+ agent_args,+ })+ .await+ {+ Ok(()) => ExitCode::SUCCESS,+ Err(error) => {+ eprintln!("macrod herdr-acp: {error:?}");+ ExitCode::FAILURE+ }+ };+ }+ None => {}+ }let config_path = std::path::Path::new("macrod.toml");// The TUI owns the terminal, so its logs go to a ring buffer it renders.diff --git a/crates/coding_agent_worker/src/runtime.rs b/crates/coding_agent_worker/src/runtime.rsindex 44eb2c8bd2..da529ba66d 100644--- a/crates/coding_agent_worker/src/runtime.rs+++ b/crates/coding_agent_worker/src/runtime.rs@@ -13,7 +13,7 @@ use tokio_tungstenite::tungstenite;use tokio_util::task::AbortOnDropHandle;use crate::config::{Harness, HarnessCredentials, MacroApi};-use crate::harness;+use crate::harness::{self, LineTap};use crate::outbound::link;#[cfg(test)]@@ -40,6 +40,7 @@ impl Runtime {credentials: &HarnessCredentials,harness: Harness,cwd: &Path,+ tap: Option<LineTap>,) -> Self {let (connected_tx, connected) = watch::channel(false);let task = tokio::spawn(serve(@@ -47,6 +48,7 @@ impl Runtime {credentials.token.clone(),harness,cwd.to_owned(),+ tap,connected_tx,));Self {@@ -78,6 +80,7 @@ async fn serve(token: String,harness: Harness,cwd: PathBuf,+ tap: Option<LineTap>,connected: watch::Sender<bool>,) {let mut backoff = reconnect_strategy();@@ -87,7 +90,7 @@ async fn serve(connected.send_replace(true);tracing::info!("harness bridge starting");let started = Instant::now();- match harness::bridge(&harness, &cwd, channel).await {+ match harness::bridge(&harness, &cwd, channel, tap.clone()).await {Ok(()) => tracing::info!("harness bridge ended; reconnecting"),Err(error) => {tracing::warn!(error = ?error, "harness bridge ended; reconnecting");diff --git a/crates/coding_agent_worker/src/runtime/test.rs b/crates/coding_agent_worker/src/runtime/test.rsindex 80bd3f16ed..474e97ac09 100644--- a/crates/coding_agent_worker/src/runtime/test.rs+++ b/crates/coding_agent_worker/src/runtime/test.rs@@ -23,6 +23,7 @@ fn start_runtime(listener: &TcpListener) -> Runtime {env: Default::default(),},Path::new("/"),+ None,)}diff --git a/crates/coding_agent_worker/src/tui.rs b/crates/coding_agent_worker/src/tui.rsindex 7abad01820..172806c864 100644--- a/crates/coding_agent_worker/src/tui.rs+++ b/crates/coding_agent_worker/src/tui.rs@@ -10,6 +10,8 @@ mod agent_catalog;mod api;mod app;mod config_form;+#[cfg(unix)]+mod herdr_pane;mod input;mod logging;mod platform;@@ -18,5 +20,7 @@ mod quickstart;mod runner;mod ui;+#[cfg(unix)]+pub use herdr_pane::run_herdr_pane;pub use logging::LogBuffer;pub use runner::run;diff --git a/crates/coding_agent_worker/src/tui/agent_catalog.rs b/crates/coding_agent_worker/src/tui/agent_catalog.rsindex ad78e82553..d7dc70e072 100644--- a/crates/coding_agent_worker/src/tui/agent_catalog.rs+++ b/crates/coding_agent_worker/src/tui/agent_catalog.rs@@ -2,6 +2,8 @@mod claude_code;mod codex;+#[cfg(unix)]+mod herdr_tui;mod hermes;mod npm_adapter;mod open_claw;@@ -27,6 +29,10 @@ mod environment {}static PRESETS: &[&dyn AgentPreset] = &[+ #[cfg(unix)]+ &herdr_tui::HerdrTui(crate::herdr::acp_agent::TuiAgent::Claude),+ #[cfg(unix)]+ &herdr_tui::HerdrTui(crate::herdr::acp_agent::TuiAgent::Codex),&hermes::Hermes,&claude_code::ClaudeCode,&codex::Codex,@@ -90,6 +96,8 @@ impl DetectedAgent {pub enum AgentKind {Hermes,ClaudeCode,+ HerdrClaude,+ HerdrCodex,Codex,OpenClaw,OpenCode,@@ -132,6 +140,7 @@ impl PathCommands {"hermes-acp","claude","codex",+ "herdr","npm","openclaw","opencode",diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/herdr_tui.rs b/crates/coding_agent_worker/src/tui/agent_catalog/herdr_tui.rsnew file mode 100644index 0000000000..7f2a78b8c9--- /dev/null+++ b/crates/coding_agent_worker/src/tui/agent_catalog/herdr_tui.rs@@ -0,0 +1,69 @@+use super::{AgentKind, AgentPreset, Availability, CommandLookup, DetectedAgent, LaunchSpec};+use crate::config::Harness;+use crate::herdr::acp_agent::TuiAgent;++/// A coding agent's own TUI, one herdr tab per session, driven over ACP by+/// `macrod herdr-acp`. Offered only when macrod itself runs inside herdr.+pub(super) struct HerdrTui(pub(super) TuiAgent);++impl AgentPreset for HerdrTui {+ fn kind(&self) -> AgentKind {+ match self.0 {+ TuiAgent::Claude => AgentKind::HerdrClaude,+ TuiAgent::Codex => AgentKind::HerdrCodex,+ }+ }++ fn name(&self) -> &'static str {+ match self.0 {+ TuiAgent::Claude => "Claude Code in herdr",+ TuiAgent::Codex => "Codex in herdr",+ }+ }++ fn detect(&self, commands: &dyn CommandLookup) -> Availability {+ let missing: Vec<&'static str> = [self.0.herdr_kind(), "herdr"]+ .into_iter()+ .filter(|command| commands.resolve(command).is_none())+ .collect();+ if !missing.is_empty() {+ return Availability::Unavailable { missing };+ }+ if crate::herdr::HerdrSession::detect().is_none() {+ return Availability::Unavailable {+ missing: vec!["a herdr pane"],+ };+ }+ let Ok(exe) = std::env::current_exe() else {+ return Availability::Unavailable {+ missing: vec!["macrod"],+ };+ };+ let mut args = vec![+ crate::herdr::acp_agent::SUBCOMMAND.to_owned(),+ "--kind".to_owned(),+ self.0.herdr_kind().to_owned(),+ ];+ if self.0 == TuiAgent::Claude {+ args.extend(["--permission-mode".to_owned(), "acceptEdits".to_owned()]);+ }+ Availability::Available(DetectedAgent {+ kind: self.kind(),+ name: self.name(),+ launch: LaunchSpec {+ command: exe.to_string_lossy().into_owned(),+ args,+ env: std::collections::BTreeMap::new(),+ },+ note: Some(match self.0 {+ TuiAgent::Claude => "a live Claude Code tab per session",+ TuiAgent::Codex => "a live Codex tab per session",+ }),+ install: None,+ })+ }++ fn recognizes(&self, harness: &Harness) -> bool {+ crate::herdr::herdr_agent(harness) == Some(self.0)+ }+}diff --git a/crates/coding_agent_worker/src/tui/herdr_pane.rs b/crates/coding_agent_worker/src/tui/herdr_pane.rsnew file mode 100644index 0000000000..f37d8964cf--- /dev/null+++ b/crates/coding_agent_worker/src/tui/herdr_pane.rs@@ -0,0 +1,398 @@+//! `macrod herdr-pane`: one ACP session's live window inside herdr.+//!+//! The window attaches to its macrod over the local socket, replays what the+//! session has done so far, then follows it live: prompts, streamed agent+//! output, thoughts, tool calls, plans. Typing prompts the session and Esc+//! interrupts it, both carried to the session through Macro by the daemon.+//! Permission requests are shown but answered in Macro: the service accepts+//! approvals only from a user, never from the runtime they would unblock.++use std::path::Path;+use std::time::Duration;++use crossterm::event::{Event as TermEvent, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};+use rootcause::prelude::ResultExt as _;+use serde_json::Value;+use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader};+use tokio::net::UnixStream;+use tokio::net::unix::OwnedWriteHalf;+use tui_input::Input;++use super::input::handle_text_input;+use super::ui;+use crate::herdr::wire::{AgentState, FromPane, PermissionChoice, ToPane};++#[cfg(test)]+mod test;++const TICK: Duration = Duration::from_millis(120);+/// How many lines one PageUp/PageDown moves.+const PAGE: usize = 10;++/// One thing the transcript shows.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum Entry {+ /// A prompt the agent received.+ User(String),+ /// Streamed agent output.+ Agent(String),+ /// Streamed agent reasoning.+ Thought(String),+ /// A tool call and its latest status.+ Tool {+ /// The agent's id for it.+ id: String,+ /// What it is doing.+ title: String,+ /// `pending`, `in_progress`, `completed`, or `failed`.+ status: String,+ },+ /// The agent's current plan: `(step, status)`.+ Plan(Vec<(String, String)>),+ /// A turn's end, when it ended for a reason worth saying.+ Stopped(String),+ /// A message from the window itself.+ Notice {+ /// The text.+ text: String,+ /// Whether it reports a failure.+ error: bool,+ },+}++/// The session's story, folded from wire events.+#[derive(Debug, Default)]+pub(crate) struct Transcript {+ pub(crate) entries: Vec<Entry>,+ prompted: bool,+}++impl Transcript {+ fn prompted(&mut self, text: String) {+ self.prompted = true;+ self.entries.push(Entry::User(text));+ }++ fn append_text(&mut self, text: &str, make: fn(String) -> Entry, is: fn(&Entry) -> bool) {+ if let Some(last) = self.entries.last_mut()+ && is(last)+ && let Entry::Agent(existing) | Entry::Thought(existing) | Entry::User(existing) = last+ {+ existing.push_str(text);+ return;+ }+ self.entries.push(make(text.to_owned()));+ }++ /// Fold one `session/update` payload in.+ pub(crate) fn apply_update(&mut self, update: &Value) {+ let text = || {+ update+ .pointer("/content/text")+ .and_then(Value::as_str)+ .unwrap_or_default()+ };+ match update.get("sessionUpdate").and_then(Value::as_str) {+ Some("agent_message_chunk") => {+ self.append_text(text(), Entry::Agent, |e| matches!(e, Entry::Agent(_)));+ }+ Some("agent_thought_chunk") => {+ self.append_text(text(), Entry::Thought, |e| matches!(e, Entry::Thought(_)));+ }+ // Replayed history on load; live prompts arrive as `Prompted`.+ Some("user_message_chunk") if !self.prompted => {+ self.append_text(text(), Entry::User, |e| matches!(e, Entry::User(_)));+ }+ Some("tool_call") => {+ let field = |name: &str| {+ update+ .get(name)+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_owned()+ };+ let status = update+ .get("status")+ .and_then(Value::as_str)+ .unwrap_or("pending")+ .to_owned();+ self.entries.push(Entry::Tool {+ id: field("toolCallId"),+ title: field("title"),+ status,+ });+ }+ Some("tool_call_update") => {+ let Some(id) = update.get("toolCallId").and_then(Value::as_str) else {+ return;+ };+ let found = self.entries.iter_mut().rev().find_map(|entry| match entry {+ Entry::Tool {+ id: tool,+ title,+ status,+ } if tool == id => Some((title, status)),+ _ => None,+ });+ if let Some((title, status)) = found {+ if let Some(new) = update.get("title").and_then(Value::as_str) {+ new.clone_into(title);+ }+ if let Some(new) = update.get("status").and_then(Value::as_str) {+ new.clone_into(status);+ }+ }+ }+ Some("plan") => {+ let steps = update+ .get("entries")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .map(|step| {+ let field = |name| {+ step.get(name)+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_owned()+ };+ (field("content"), field("status"))+ })+ .collect();+ match self.entries.last_mut() {+ Some(Entry::Plan(existing)) => *existing = steps,+ _ => self.entries.push(Entry::Plan(steps)),+ }+ }+ _ => {}+ }+ }+}++/// A permission request waiting on an answer in Macro.+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct PendingPermission {+ pub(crate) title: Option<String>,+ pub(crate) options: Vec<PermissionChoice>,+}++/// Everything the window renders.+#[derive(Debug)]+pub(crate) struct PaneView {+ pub(crate) session: String,+ pub(crate) web_url: Option<String>,+ pub(crate) state: AgentState,+ pub(crate) transcript: Transcript,+ pub(crate) input: Input,+ pub(crate) permission: Option<PendingPermission>,+ /// Lines scrolled up from the bottom; zero follows live output.+ pub(crate) scroll: usize,+ pub(crate) connected: bool,+ pub(crate) tick: usize,+}++/// What a key asks the window to do.+#[derive(Debug, PartialEq)]+pub(crate) enum PaneAction {+ Nothing,+ Send(FromPane),+ Quit,+}++impl PaneView {+ pub(crate) fn new(session: &str) -> Self {+ Self {+ session: session.to_owned(),+ web_url: None,+ state: AgentState::Idle,+ transcript: Transcript::default(),+ input: Input::default(),+ permission: None,+ scroll: 0,+ connected: true,+ tick: 0,+ }+ }++ /// Fold one message from macrod in.+ pub(crate) fn apply(&mut self, message: ToPane) {+ match message {+ ToPane::Hello { session, web_url } => {+ self.session = session;+ self.web_url = web_url;+ }+ ToPane::Prompted { text } => self.transcript.prompted(text),+ ToPane::Update { update } => self.transcript.apply_update(&update),+ ToPane::State { state, detail } => {+ if state == AgentState::Idle+ && let Some(reason) = detail.filter(|reason| reason != "end_turn")+ {+ self.transcript.entries.push(Entry::Stopped(reason));+ }+ self.state = state;+ }+ ToPane::Permission { title, options, .. } => {+ self.permission = Some(PendingPermission { title, options });+ }+ ToPane::PermissionSettled => self.permission = None,+ ToPane::Notice { text, error } => {+ self.transcript.entries.push(Entry::Notice { text, error });+ }+ }+ }++ fn disconnected(&mut self) {+ self.connected = false;+ self.permission = None;+ self.transcript.entries.push(Entry::Notice {+ text: "macrod stopped; this window no longer follows the session. ctrl+c closes it."+ .to_owned(),+ error: true,+ });+ }++ fn stop(&self) -> PaneAction {+ if matches!(self.state, AgentState::Working | AgentState::Blocked) {+ PaneAction::Send(FromPane::Stop)+ } else {+ PaneAction::Nothing+ }+ }++ /// React to a terminal event.+ pub(crate) fn on_event(&mut self, event: TermEvent) -> PaneAction {+ match event {+ TermEvent::Key(key) if key.kind != KeyEventKind::Release => self.on_key(key),+ TermEvent::Paste(text) => {+ for ch in text.chars().map(|ch| if ch == '\n' { ' ' } else { ch }) {+ self.input.handle(tui_input::InputRequest::InsertChar(ch));+ }+ PaneAction::Nothing+ }+ _ => PaneAction::Nothing,+ }+ }++ fn on_key(&mut self, key: KeyEvent) -> PaneAction {+ if key.code == KeyCode::Char('c') && key.modifiers == KeyModifiers::CONTROL {+ if !self.connected {+ return PaneAction::Quit;+ }+ return match self.stop() {+ PaneAction::Nothing => PaneAction::Quit,+ stop => stop,+ };+ }+ match key.code {+ KeyCode::Enter => {+ let text = self.input.value().trim().to_owned();+ if text.is_empty() {+ return PaneAction::Nothing;+ }+ self.input.reset();+ self.scroll = 0;+ PaneAction::Send(FromPane::Prompt { text })+ }+ KeyCode::Esc => self.stop(),+ KeyCode::PageUp => {+ self.scroll = self.scroll.saturating_add(PAGE);+ PaneAction::Nothing+ }+ KeyCode::PageDown => {+ self.scroll = self.scroll.saturating_sub(PAGE);+ PaneAction::Nothing+ }+ _ => {+ handle_text_input(&mut self.input, key);+ PaneAction::Nothing+ }+ }+ }+}++async fn send(write: &mut OwnedWriteHalf, message: &FromPane) -> std::io::Result<()> {+ let mut line = serde_json::to_string(message).map_err(std::io::Error::other)?;+ line.push('\n');+ write.write_all(line.as_bytes()).await+}++/// Attach to `session` on the macrod listening at `socket` and show it+/// until the user quits.+pub async fn run_herdr_pane(socket: &Path, session: &str) -> rootcause::Result<()> {+ let stream = UnixStream::connect(socket)+ .await+ .context("could not reach macrod; is it still running?")?;+ let (read, mut write) = stream.into_split();+ send(+ &mut write,+ &FromPane::Attach {+ session: session.to_owned(),+ },+ )+ .await+ .context("could not attach to the session")?;++ let (message_tx, mut message_rx) = tokio::sync::mpsc::unbounded_channel();+ tokio::spawn(async move {+ let mut lines = BufReader::new(read).lines();+ while let Ok(Some(line)) = lines.next_line().await {+ if let Ok(message) = serde_json::from_str::<ToPane>(&line)+ && message_tx.send(Some(message)).is_err()+ {+ return;+ }+ }+ let _ = message_tx.send(None);+ });++ let (input_tx, mut input_rx) = tokio::sync::mpsc::unbounded_channel();+ std::thread::spawn(move || {+ while let Ok(event) = crossterm::event::read() {+ if input_tx.send(event).is_err() {+ return;+ }+ }+ });++ let mut terminal = ratatui::init();+ let _ = crossterm::execute!(std::io::stdout(), crossterm::event::EnableBracketedPaste);+ let mut view = PaneView::new(session);+ let mut ticker = tokio::time::interval(TICK);+ let outcome = loop {+ if let Err(error) = terminal.draw(|frame| ui::render_herdr_pane(frame, &view)) {+ break Err(error);+ }+ tokio::select! {+ _ = ticker.tick() => view.tick = view.tick.wrapping_add(1),+ Some(event) = input_rx.recv() => match view.on_event(event) {+ PaneAction::Nothing => {}+ PaneAction::Quit => break Ok(()),+ PaneAction::Send(message) => {+ if send(&mut write, &message).await.is_err() {+ view.connected = false;+ }+ }+ },+ message = message_rx.recv(), if view.connected => {+ // A replayed backlog arrives all at once: fold it before+ // drawing again.+ let mut next = message;+ loop {+ let Some(Some(message)) = next else {+ view.disconnected();+ break;+ };+ view.apply(message);+ match message_rx.try_recv() {+ Ok(message) => next = Some(message),+ Err(_) => break,+ }+ }+ }+ }+ };+ let _ = crossterm::execute!(std::io::stdout(), crossterm::event::DisableBracketedPaste);+ ratatui::restore();+ outcome.context("the window's terminal failed")?;+ Ok(())+}diff --git a/crates/coding_agent_worker/src/tui/herdr_pane/test.rs b/crates/coding_agent_worker/src/tui/herdr_pane/test.rsnew file mode 100644index 0000000000..88ba4bc4c6--- /dev/null+++ b/crates/coding_agent_worker/src/tui/herdr_pane/test.rs@@ -0,0 +1,176 @@+use crossterm::event::{KeyEventState, KeyModifiers};+use serde_json::json;++use super::*;++fn key(code: KeyCode, modifiers: KeyModifiers) -> TermEvent {+ TermEvent::Key(KeyEvent {+ code,+ modifiers,+ kind: KeyEventKind::Press,+ state: KeyEventState::NONE,+ })+}++fn press(view: &mut PaneView, code: KeyCode) -> PaneAction {+ view.on_event(key(code, KeyModifiers::NONE))+}++fn update(view: &mut PaneView, update: Value) {+ view.apply(ToPane::Update { update });+}++#[test]+fn streamed_output_folds_into_readable_entries() {+ let mut view = PaneView::new("s");+ view.apply(ToPane::Prompted {+ text: "fix it".to_owned(),+ });+ update(+ &mut view,+ json!({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "hmm "}}),+ );+ update(+ &mut view,+ json!({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "ok"}}),+ );+ update(+ &mut view,+ json!({"sessionUpdate": "tool_call", "toolCallId": "t1", "title": "Read main.rs", "status": "in_progress"}),+ );+ update(+ &mut view,+ json!({"sessionUpdate": "tool_call_update", "toolCallId": "t1", "status": "completed"}),+ );+ update(+ &mut view,+ json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Done"}}),+ );+ update(+ &mut view,+ json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "."}}),+ );+ // Live prompts arrive as `Prompted`; an echoed user chunk is not doubled.+ update(+ &mut view,+ json!({"sessionUpdate": "user_message_chunk", "content": {"type": "text", "text": "fix it"}}),+ );++ assert_eq!(+ view.transcript.entries,+ [+ Entry::User("fix it".to_owned()),+ Entry::Thought("hmm ok".to_owned()),+ Entry::Tool {+ id: "t1".to_owned(),+ title: "Read main.rs".to_owned(),+ status: "completed".to_owned(),+ },+ Entry::Agent("Done.".to_owned()),+ ]+ );+}++#[test]+fn replayed_history_shows_user_messages() {+ let mut view = PaneView::new("s");+ update(+ &mut view,+ json!({"sessionUpdate": "user_message_chunk", "content": {"type": "text", "text": "earlier"}}),+ );+ update(+ &mut view,+ json!({"sessionUpdate": "plan", "entries": [{"content": "a", "status": "completed"}]}),+ );+ update(+ &mut view,+ json!({"sessionUpdate": "plan", "entries": [{"content": "a", "status": "completed"}, {"content": "b", "status": "pending"}]}),+ );+ assert_eq!(+ view.transcript.entries,+ [+ Entry::User("earlier".to_owned()),+ Entry::Plan(vec![+ ("a".to_owned(), "completed".to_owned()),+ ("b".to_owned(), "pending".to_owned()),+ ]),+ ]+ );+}++#[test]+fn enter_sends_the_prompt_and_clears_the_input() {+ let mut view = PaneView::new("s");+ assert_eq!(press(&mut view, KeyCode::Enter), PaneAction::Nothing);+ for ch in "hi there".chars() {+ press(&mut view, KeyCode::Char(ch));+ }+ assert_eq!(+ press(&mut view, KeyCode::Enter),+ PaneAction::Send(FromPane::Prompt {+ text: "hi there".to_owned()+ })+ );+ assert_eq!(view.input.value(), "");+}++#[test]+fn ctrl_c_interrupts_a_turn_and_otherwise_closes() {+ let mut view = PaneView::new("s");+ let ctrl_c = || key(KeyCode::Char('c'), KeyModifiers::CONTROL);+ view.apply(ToPane::State {+ state: AgentState::Working,+ detail: None,+ });+ assert_eq!(view.on_event(ctrl_c()), PaneAction::Send(FromPane::Stop));+ assert_eq!(+ press(&mut view, KeyCode::Esc),+ PaneAction::Send(FromPane::Stop)+ );++ view.apply(ToPane::State {+ state: AgentState::Idle,+ detail: Some("cancelled".to_owned()),+ });+ assert_eq!(press(&mut view, KeyCode::Esc), PaneAction::Nothing);+ assert_eq!(view.on_event(ctrl_c()), PaneAction::Quit);+ assert_eq!(+ view.transcript.entries.last(),+ Some(&Entry::Stopped("cancelled".to_owned()))+ );+}++#[test]+fn permission_requests_are_shown_but_left_to_macro() {+ let mut view = PaneView::new("s");+ view.apply(ToPane::Permission {+ request_id: json!("req-1"),+ title: Some("Run tests".to_owned()),+ options: vec![PermissionChoice {+ option_id: "allow".to_owned(),+ name: "Allow".to_owned(),+ kind: "allow_once".to_owned(),+ }],+ });+ assert_eq!(+ view.permission+ .as_ref()+ .map(|pending| pending.title.as_deref()),+ Some(Some("Run tests"))+ );++ // Keys go to the prompt, and nothing answers the request from here.+ assert_eq!(press(&mut view, KeyCode::Char('1')), PaneAction::Nothing);+ assert_eq!(view.input.value(), "1");++ view.apply(ToPane::PermissionSettled);+ assert!(view.permission.is_none());+}++#[test]+fn wrap_breaks_on_words_and_splits_long_ones() {+ use crate::tui::ui::wrap_for_test as wrap;+ assert_eq!(wrap("the quick brown fox", 9), ["the quick", "brown fox"]);+ assert_eq!(wrap("abcdefghij", 4), ["abcd", "efgh", "ij"]);+ assert_eq!(wrap("a\n\nb", 10), ["a", "", "b"]);+}diff --git a/crates/coding_agent_worker/src/tui/ui.rs b/crates/coding_agent_worker/src/tui/ui.rsindex 00d24716e4..766babc2a6 100644--- a/crates/coding_agent_worker/src/tui/ui.rs+++ b/crates/coding_agent_worker/src/tui/ui.rs@@ -1,5 +1,7 @@//! Rendering for the macrod control panel. Pure: reads [`App`], draws frames.+#[cfg(unix)]+mod herdr_pane;mod layout;mod modals;mod pages;@@ -12,6 +14,10 @@ use ratatui::layout::{Constraint, Direction, Layout};use super::app::{App, Mode};+#[cfg(unix)]+pub(crate) use herdr_pane::render_herdr_pane;+#[cfg(all(unix, test))]+pub(crate) use herdr_pane::wrap as wrap_for_test;pub(crate) use quickstart::render_quickstart;pub(crate) fn render(frame: &mut Frame, app: &App) {diff --git a/crates/coding_agent_worker/src/tui/ui/herdr_pane.rs b/crates/coding_agent_worker/src/tui/ui/herdr_pane.rsnew file mode 100644index 0000000000..6eb6009075--- /dev/null+++ b/crates/coding_agent_worker/src/tui/ui/herdr_pane.rs@@ -0,0 +1,311 @@+//! Rendering for `macrod herdr-pane`. Pure: reads [`PaneView`], draws frames.++use ratatui::Frame;+use ratatui::layout::{Constraint, Direction, Layout, Rect};+use ratatui::style::{Modifier, Style, Stylize as _};+use ratatui::text::{Line, Span};+use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph};++use super::theme::{self, ACCENT, DIM, ERR, OK, SPINNER, THEME, WARN};+use crate::herdr::wire::AgentState;+use crate::tui::herdr_pane::{Entry, PaneView, PendingPermission};++pub(crate) fn render_herdr_pane(frame: &mut Frame, view: &PaneView) {+ theme::render_background(frame);+ let permission_height = view+ .permission+ .as_ref()+ .map_or(0, |permission| permission.options.len() as u16 + 5);+ let [header, body, permission, input, footer] = Layout::default()+ .direction(Direction::Vertical)+ .constraints([+ Constraint::Length(1),+ Constraint::Min(3),+ Constraint::Length(permission_height),+ Constraint::Length(3),+ Constraint::Length(1),+ ])+ .areas(frame.area());++ render_header(frame, view, header);+ render_transcript(frame, view, body);+ if let Some(pending) = &view.permission {+ render_permission(frame, pending, permission);+ }+ render_input(frame, view, input);+ render_footer(frame, view, footer);+}++fn spinner(view: &PaneView) -> &'static str {+ SPINNER[view.tick % SPINNER.len()]+}++fn render_header(frame: &mut Frame, view: &PaneView, area: Rect) {+ let (state, color) = match (view.connected, view.state) {+ (false, _) => ("disconnected".to_owned(), ERR),+ (true, AgentState::Idle) => ("ready".to_owned(), OK),+ (true, AgentState::Working) => (format!("{} working", spinner(view)), WARN),+ (true, AgentState::Blocked) => ("needs permission".to_owned(), ERR),+ };+ let mut spans = vec![+ Span::styled(+ " ◆ Macro agent ",+ Style::new().fg(THEME.accent_text).bg(ACCENT).bold(),+ ),+ Span::raw(" "),+ Span::styled(state, Style::new().fg(color).bold()),+ ];+ if let Some(url) = &view.web_url {+ spans.push(Span::styled(format!(" · {url}"), Style::new().fg(DIM)));+ } else {+ spans.push(Span::styled(+ format!(" · acp {}", view.session),+ Style::new().fg(DIM),+ ));+ }+ frame.render_widget(Paragraph::new(Line::from(spans)), area);+}++/// Greedy word wrap by character count; long words are split.+pub(crate) fn wrap(text: &str, width: usize) -> Vec<String> {+ let width = width.max(1);+ let mut out = Vec::new();+ for raw in text.split('\n') {+ let mut line = String::new();+ let mut len = 0;+ for word in raw.split(' ') {+ let word_len = word.chars().count();+ if len > 0 && len + 1 + word_len > width {+ out.push(std::mem::take(&mut line));+ len = 0;+ }+ if len > 0 {+ line.push(' ');+ len += 1;+ }+ let mut rest: Vec<char> = word.chars().collect();+ while len + rest.len() > width {+ let take = width - len;+ line.extend(rest.drain(..take));+ out.push(std::mem::take(&mut line));+ len = 0;+ }+ len += rest.len();+ line.extend(rest);+ }+ out.push(line);+ }+ out+}++fn push_wrapped(+ lines: &mut Vec<Line<'static>>,+ text: &str,+ width: usize,+ first: Span<'static>,+ style: Style,+) {+ let indent = first.content.chars().count();+ for (index, chunk) in wrap(text.trim_end(), width.saturating_sub(indent))+ .into_iter()+ .enumerate()+ {+ let lead = if index == 0 {+ first.clone()+ } else {+ Span::raw(" ".repeat(indent))+ };+ lines.push(Line::from(vec![lead, Span::styled(chunk, style)]));+ }+}++fn transcript_lines(view: &PaneView, width: usize) -> Vec<Line<'static>> {+ let mut lines = Vec::new();+ for entry in &view.transcript.entries {+ match entry {+ Entry::User(text) => {+ lines.push(Line::default());+ push_wrapped(+ &mut lines,+ text,+ width,+ Span::styled("› ", Style::new().fg(ACCENT).bold()),+ Style::new().fg(THEME.text).bold(),+ );+ lines.push(Line::default());+ }+ Entry::Agent(text) => push_wrapped(+ &mut lines,+ text,+ width,+ Span::styled("● ", Style::new().fg(THEME.text)),+ Style::new().fg(THEME.text),+ ),+ Entry::Thought(text) => push_wrapped(+ &mut lines,+ text,+ width,+ Span::styled("∴ ", Style::new().fg(DIM)),+ Style::new().fg(DIM).add_modifier(Modifier::ITALIC),+ ),+ Entry::Tool { title, status, .. } => {+ let (icon, color) = match status.as_str() {+ "completed" => ("✓ ".to_owned(), OK),+ "failed" => ("✗ ".to_owned(), ERR),+ "in_progress" => (format!("{} ", spinner(view)), WARN),+ _ => ("○ ".to_owned(), DIM),+ };+ push_wrapped(+ &mut lines,+ title,+ width,+ Span::styled(icon, Style::new().fg(color).bold()),+ Style::new().fg(THEME.muted),+ );+ }+ Entry::Plan(steps) => {+ lines.push(Line::from(Span::styled(+ "Plan",+ Style::new().fg(ACCENT).bold(),+ )));+ for (step, status) in steps {+ let (icon, color) = match status.as_str() {+ "completed" => (" ☑ ", OK),+ "in_progress" => (" ◐ ", WARN),+ _ => (" ☐ ", DIM),+ };+ push_wrapped(+ &mut lines,+ step,+ width,+ Span::styled(icon, Style::new().fg(color)),+ Style::new().fg(THEME.muted),+ );+ }+ }+ Entry::Stopped(reason) => lines.push(Line::from(Span::styled(+ format!(" turn ended: {reason}"),+ Style::new().fg(WARN),+ ))),+ Entry::Notice { text, error } => push_wrapped(+ &mut lines,+ text,+ width,+ Span::styled("· ", Style::new().fg(if *error { ERR } else { DIM })),+ Style::new().fg(if *error { ERR } else { DIM }),+ ),+ }+ }+ lines+}++fn render_transcript(frame: &mut Frame, view: &PaneView, area: Rect) {+ let inner = Rect {+ x: area.x + 1,+ width: area.width.saturating_sub(2),+ ..area+ };+ let lines = transcript_lines(view, usize::from(inner.width));+ if lines.is_empty() {+ frame.render_widget(+ Paragraph::new(Line::from(Span::styled(+ "Waiting for the first prompt. Type below, or prompt this agent from Macro.",+ Style::new().fg(DIM),+ ))),+ inner,+ );+ return;+ }+ let height = usize::from(inner.height);+ let max_scroll = lines.len().saturating_sub(height);+ let scroll = view.scroll.min(max_scroll);+ let start = lines.len().saturating_sub(height + scroll);+ let visible: Vec<Line<'static>> = lines.into_iter().skip(start).take(height).collect();+ frame.render_widget(Paragraph::new(visible), inner);+}++fn render_permission(frame: &mut Frame, pending: &PendingPermission, area: Rect) {+ frame.render_widget(Clear, area);+ let title = pending+ .title+ .clone()+ .unwrap_or_else(|| "The agent asks permission".to_owned());+ let block = Block::default()+ .style(Style::new().fg(THEME.text).bg(THEME.surface))+ .title(" Permission ")+ .title_style(Style::new().fg(ERR).bold())+ .borders(Borders::ALL)+ .border_type(BorderType::Rounded)+ .border_style(Style::new().fg(ERR));+ let mut lines = vec![Line::from(Span::styled(title, Style::new().bold()))];+ for option in &pending.options {+ let color = if option.kind.starts_with("allow") {+ OK+ } else {+ ERR+ };+ lines.push(Line::from(vec![+ Span::raw(" · "),+ Span::styled(option.name.clone(), Style::new().fg(color)),+ ]));+ }+ lines.push(Line::from(Span::styled(+ "Approve or deny it in Macro; a runtime cannot answer its own request.",+ Style::new().fg(DIM),+ )));+ frame.render_widget(Paragraph::new(lines).block(block), area);+}++fn render_input(frame: &mut Frame, view: &PaneView, area: Rect) {+ let focused = view.connected;+ let border = if focused { ACCENT } else { THEME.border };+ let block = Block::default()+ .style(Style::new().fg(THEME.text).bg(THEME.surface))+ .borders(Borders::ALL)+ .border_type(BorderType::Rounded)+ .border_style(Style::new().fg(border));+ let inner = block.inner(area);+ let width = usize::from(inner.width.saturating_sub(2));+ let scroll = view.input.visual_scroll(width);+ let text = if view.input.value().is_empty() {+ Line::from(vec![+ Span::styled("› ", Style::new().fg(ACCENT).bold()),+ Span::styled(+ if view.state == AgentState::Idle {+ "Prompt the agent"+ } else {+ "Queue a follow-up"+ },+ Style::new().fg(DIM),+ ),+ ])+ } else {+ Line::from(vec![+ Span::styled("› ", Style::new().fg(ACCENT).bold()),+ Span::raw(view.input.value().chars().skip(scroll).collect::<String>()),+ ])+ };+ frame.render_widget(Paragraph::new(text).block(block), area);+ if focused {+ let cursor = view.input.visual_cursor().saturating_sub(scroll);+ let x = inner.x + 2 + u16::try_from(cursor).unwrap_or(u16::MAX);+ frame.set_cursor_position((x.min(inner.right().saturating_sub(1)), inner.y));+ }+}++fn render_footer(frame: &mut Frame, view: &PaneView, area: Rect) {+ let hints = if view.permission.is_some() {+ "waiting for approval in Macro · esc interrupt"+ } else if view.state == AgentState::Idle {+ "enter send · pgup/pgdn scroll · ctrl+c close"+ } else {+ "enter send · esc interrupt · pgup/pgdn scroll"+ };+ frame.render_widget(+ Paragraph::new(Line::from(Span::styled(+ format!(" {hints}"),+ Style::new().fg(DIM),+ ))),+ area,+ );+}diff --git a/crates/coding_agent_worker/src/tui/ui/quickstart.rs b/crates/coding_agent_worker/src/tui/ui/quickstart.rsindex defa006f02..d924912328 100644--- a/crates/coding_agent_worker/src/tui/ui/quickstart.rs+++ b/crates/coding_agent_worker/src/tui/ui/quickstart.rs@@ -239,7 +239,7 @@ fn render_discovered_agents(frame: &mut Frame, setup: &Quickstart, area: Rect) {Paragraph::new(Line::from(vec![Span::styled(focus_marker(focused), Style::new().fg(ACCENT)),Span::styled(if chosen { "● " } else { "○ " }, Style::new().fg(ACCENT)),- Span::styled(format!("{:<20}", agent.name), focus_style(focused)),+ Span::styled(format!("{:<22}", agent.name), focus_style(focused)),Span::styled(agent.note.unwrap_or(""), Style::new().fg(DIM)),])),row,diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex 253a44dd27..634ad8e194 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -347,6 +347,12 @@ the shimmer.code and click **Look up**. Review the request and click **Approve** to connect.The setup guide contains configuration and pairing screenshots in that order.Enter the code from your own terminal, not the example screenshot.+ Run inside a herdr pane, macrod's Quickstart also offers **Claude Code in herdr**+ and **Codex in herdr**: each session of an agent on that runtime opens a herdr+ tab in the directory macrod started from, running the real Claude Code or Codex+ TUI. The session page streams its tool calls and replies, and its permission+ prompts appear as approvals. Other runtimes started inside herdr get a live+ view tab per session that can prompt and interrupt it; approvals stay in Macro.The agent form retains sharing, name, `@tag`, runtime, default model, connections,channels, instructions, and permission policy.Runtime and short model lists use styled dropdown buttons: open the field and