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): drive herdr-core and the herdr app as well as herdr 0.9 (#9237)
Eric Hayes069fe2ce8c8a
diff --git a/Cargo.lock b/Cargo.lockindex e0720ab6ba..231aa62d03 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4581,6 +4581,7 @@ dependencies = ["agent_session","agent_trigger","arboard",+ "base64 0.22.1","bot_id","channel_sender","channels",diff --git a/crates/coding_agent_worker/AGENTS.md b/crates/coding_agent_worker/AGENTS.mdindex ccbb02e248..5c9f5f2a64 100644--- a/crates/coding_agent_worker/AGENTS.md+++ b/crates/coding_agent_worker/AGENTS.md@@ -22,8 +22,9 @@ the local ACP process (Claude Code, Codex, ...), and drives nativecreate/dial/prompt against the live harness service.- `src/tui.rs` (`src/tui/`): the control panel itself (registration, agents,sessions, config form, logs).-- `src/herdr.rs` (`src/herdr/`): native herdr pane integration — only compiled- `#[cfg(unix)]`.+- `src/herdr.rs` (`src/herdr/`): native herdr integration — only compiled+ `#[cfg(unix)]`. `src/herdr/cli.rs` picks herdr 0.9 (`herdr`) or herdr-core+ (`hc`) by environment; both stay supported.- `src/executable.rs`: `PATH` lookup; every spawn of a bare command name goesthrough `launchable`, which finds Windows `.cmd` shims (`npm`, `npx`).- `install/`: `install.sh` and `install.ps1`, the one-line installers the docs@@ -103,6 +104,9 @@ external chat replies depend on it. Direct session controls still mint IDs.Windows-breaking code there without a cfg gate.- The ACP child is killed with its whole tree: a process group on Unix, a JobObject on Windows (`src/outbound/acp_process/job.rs`).+- Every herdr call goes through the `HerdrCli` facade; add a capability to both+ `cli/legacy.rs` and `cli/hc.rs`. herdr-core has no agent registry or+ worktrees, and status comes only from OSC 7501 (README.md, "Herdr versions").- macrod never pulls into the operator's working branch — new herdr worktreesstart from a fresh fetch of `origin/main` (see README.md).- Only release builds update themselves: the tag workflow compiles the tag indiff --git a/crates/coding_agent_worker/Cargo.toml b/crates/coding_agent_worker/Cargo.tomlindex 50c5a93811..741f684917 100644--- a/crates/coding_agent_worker/Cargo.toml+++ b/crates/coding_agent_worker/Cargo.toml@@ -21,6 +21,7 @@ agent_runtime_protocol = { path = "../agent_runtime_protocol" }agent_session = { path = "../agent_session" }agent_trigger = { path = "../agent_trigger" }arboard = { workspace = true }+base64 = { workspace = true }bot_id = { path = "../bot_id" }trigger_context = { path = "../trigger_context" }chrono = { workspace = true }diff --git a/crates/coding_agent_worker/README.md b/crates/coding_agent_worker/README.mdindex eb22cdc6c9..911458a9db 100644--- a/crates/coding_agent_worker/README.md+++ b/crates/coding_agent_worker/README.md@@ -134,6 +134,28 @@ previous agent's model and extra arguments. Storage and focus preferences remainSession metadata stays in the instance directory even with custom worktree storage.Choose a repository in Macro's composer; local sessions always start from `main`.+### Herdr versions++macrod drives both herdrs and picks by where it runs (`src/herdr/cli.rs`):++- **herdr 0.9** (`HERDR_ENV=1`): the `herdr` CLI. Herdr creates worktrees, opens+ tabs, starts agents, and reports their status and session IDs.+- **herdr-core and the herdr app** (`HC_TERMINAL_ID`): the `hc` CLI, which must+ be on `PATH`. Each session is a core terminal labelled with the app's+ `herdr.space` and `herdr.tab`, so the app shows it as a tab in macrod's space.+ A managed worktree gets its own space. macrod starts the shell and then types+ `exec <agent> …` into it, so the agent gets the operator's login environment.+ git creates the worktrees. Tab names and focus go through `herdr-app do`, and+ macrod skips them when the app is not running.++herdr-core does not guess status; it shows what a program reports through+OSC 7501. Claude Code reports it. Codex does not, so under herdr-core a Codex+session loses three things: busy detection before a prompt, remote permission+answers (approve in Herdr), and cancelling a turn Macro did not start.+Transcripts still end its turns. Without a reported session ID, macrod finds+Codex's transcript by working directory and start time. Viewer windows+(`macrod herdr-pane`) report their own state through OSC 7501.+## Replies to chat-agent mentionsTrigger prompts use the source channel/document message UUID as the controldiff --git a/crates/coding_agent_worker/src/daemon.rs b/crates/coding_agent_worker/src/daemon.rsindex 6252688caa..acbf9c2c9c 100644--- a/crates/coding_agent_worker/src/daemon.rs+++ b/crates/coding_agent_worker/src/daemon.rs@@ -83,7 +83,7 @@ impl Daemon {Some(crate::herdr::repositories::Workspaces::new(config.workspace.path.clone(),config.herdr.storage_path.clone().unwrap_or(root),- crate::herdr::cli::HerdrCli::new(herdr.bin, herdr.workspace_id),+ herdr.cli(),))} else {Nonediff --git a/crates/coding_agent_worker/src/herdr.rs b/crates/coding_agent_worker/src/herdr.rsindex a9cd062ed4..2d106ebfef 100644--- a/crates/coding_agent_worker/src/herdr.rs+++ b/crates/coding_agent_worker/src/herdr.rs@@ -1,8 +1,9 @@//! 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+//! Started from inside herdr, macrod drives the herdr it lives in: either a+//! herdr 0.9 pane (`HERDR_ENV=1`) or a herdr-core terminal shown by the herdr+//! app (`HC_TERMINAL_ID`; see [`cli`]). Every ACP session it serves opens its+//! own tab in macrod's workspace or space, 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@@ -35,6 +36,9 @@ pub(crate) use hub::Hub;use crate::config::Harness;+/// herdr-core's CLI, which its installer puts on PATH.+const CORE_COMMAND: &str = "hc";+/// 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 {@@ -73,6 +77,9 @@ mod environment {macro_env_var::maybe_env_var! {pub struct HerdrWorkspaceId;}+ macro_env_var::maybe_env_var! {+ pub struct HcTerminalId;+ }}/// Private state for one paired daemon; shared by its dispatcher and ACP process.@@ -83,18 +90,34 @@ pub(crate) fn instance_directory(id: impl std::fmt::Display) -> rootcause::ResulOk(home.join(".macrod/herdr").join(id.to_string()))}-/// The herdr session macrod was started in.+/// The herdr 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>,+pub(crate) enum HerdrSession {+ /// A pane of herdr 0.9 or earlier.+ Legacy {+ /// The `herdr` binary attached to that session.+ bin: PathBuf,+ /// The workspace macrod's pane belongs to; new windows open there.+ workspace_id: Option<String>,+ },+ /// A herdr-core terminal, usually shown by the herdr app.+ Core {+ /// macrod's own terminal address, e.g. `t3`.+ terminal: String,+ },}impl HerdrSession {- /// The session macrod is running inside, if any.+ /// The herdr macrod is running inside, if any. herdr-core comes first:+ /// a core started from an old herdr pane passes `HERDR_ENV` on to its+ /// terminals.pub(crate) fn detect() -> Option<Self> {+ if let Some(terminal) = environment::HcTerminalId::new()+ .and_then(|id| id.value().map(str::to_owned))+ .filter(|id| !id.is_empty())+ {+ return Some(Self::Core { terminal });+ }let inside = environment::HerdrEnv::new().is_some_and(|value| value.value() == Some("1"));if !inside {return None;@@ -105,7 +128,29 @@ impl HerdrSession {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 })+ Some(Self::Legacy { bin, workspace_id })+ }++ /// The command this herdr is driven through.+ pub(crate) fn command(&self) -> &'static str {+ match self {+ Self::Legacy { .. } => "herdr",+ Self::Core { .. } => CORE_COMMAND,+ }+ }++ /// A client for this herdr.+ pub(crate) fn cli(&self) -> cli::HerdrCli {+ match self {+ Self::Legacy { bin, workspace_id } => cli::HerdrCli::new(bin, workspace_id.clone()),+ Self::Core { terminal } => cli::HerdrCli::core(CORE_COMMAND, terminal.clone()),+ }+ }++ /// Whether panes report their own status (OSC 7501) instead of macrod+ /// reporting it for them.+ pub(crate) fn panes_report_status(&self) -> bool {+ matches!(self, Self::Core { .. })}}diff --git a/crates/coding_agent_worker/src/herdr/acp_agent.rs b/crates/coding_agent_worker/src/herdr/acp_agent.rsindex 7e9b73c89b..4f4ceb2af9 100644--- a/crates/coding_agent_worker/src/herdr/acp_agent.rs+++ b/crates/coding_agent_worker/src/herdr/acp_agent.rs@@ -30,7 +30,7 @@ use tokio_util::sync::CancellationToken;use tracing::Instrument as _;use super::HerdrSession;-use super::cli::{HerdrCli, HerdrError};+use super::cli::{AgentLaunch, HerdrCli, HerdrError};use super::hub::title_from;use super::store::{Record, Store, write_private};use super::tail::Cursor;@@ -72,8 +72,6 @@ const STATUS_EVERY: u32 = 4;const SETTLED_CHECKS: u32 = 3;/// How long the transcript must stay quiet before a ready status ends a turn.const SETTLED_QUIET: Duration = Duration::from_secs(3);-/// How long a new tab's shell may take to reach its prompt.-const SHELL_READY_TIMEOUT: Duration = Duration::from_secs(10);const QUIET_START: Duration = Duration::from_secs(20);const MISSING_AGENT_CHECKS: u32 = 5;/// Esc presses a cancel spends before the native turn is left to run.@@ -109,6 +107,15 @@ impl TuiAgent {}}+ /// Whether the TUI reports its own status through OSC 7501, which+ /// herdr-core relies on to see it working, blocked, or ready.+ pub(crate) fn reports_status(self) -> bool {+ match self {+ Self::Claude => true,+ Self::Codex => false,+ }+ }+fn models(self) -> &'static [(&'static str, &'static str)] {match self {Self::Claude => CLAUDE_MODELS,@@ -222,9 +229,7 @@ pub async fn run(options: AdapterOptions) -> rootcause::Result<()> {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())),+ herdr: herdr.as_ref().map(HerdrSession::cli),options,home,store: Store(state_dir),@@ -877,17 +882,14 @@ impl Adapter {) -> Result<Live, RpcError> {let kind = self.options.kind;let label = title_from(first_prompt).unwrap_or_else(|| kind.herdr_kind().to_owned());- let window = if self.options.managed_worktrees {- let source = crate::outbound::git::primary_worktree(&session.cwd)- .await- .map_err(|error| RpcError::internal(error.to_string()))?;- herdr- .open_worktree(&source, &session.cwd, &label, !self.options.no_focus)- .await?+ let source = if self.options.managed_worktrees {+ Some(+ crate::outbound::git::primary_worktree(&session.cwd)+ .await+ .map_err(|error| RpcError::internal(error.to_string()))?,+ )} else {- herdr- .open_window(&session.cwd, &label, !self.options.no_focus)- .await?+ None};let model = lock(&session.model).clone();@@ -921,40 +923,32 @@ impl Adapter {]);}}+ let mut environment = None;if kind == TuiAgent::Codex && !session.mcp_servers.is_empty() {let prepared = super::mcp::codex(&self.store.0.join("mcp").join(&session.id),&session.mcp_servers,).map_err(|error| RpcError::internal(error.to_string()))?;- herdr- .run_in_pane(- &window.pane_id,- &format!(- ". {}",- shell_words::quote(&prepared.environment.to_string_lossy())- ),- )- .await?;args.extend(prepared.args);+ environment = Some(prepared.environment);}args.extend(self.options.agent_args.iter().cloned());let name = agent_name(&session.id);let started = std::time::SystemTime::now();- // The tab's shell must reach its prompt before an agent can start,- // and a worktree's direnv can hold it for seconds.- let deadline = tokio::time::Instant::now() + SHELL_READY_TIMEOUT;- loop {- match herdr- .start_agent(&name, kind.herdr_kind(), &window.pane_id, &args)- .await- {- Err(error) if error.pane_busy() && tokio::time::Instant::now() < deadline => {- tokio::time::sleep(POLL).await;- }- result => break result?,- }- }+ let window = herdr+ .launch_agent(&AgentLaunch {+ name: &name,+ kind: kind.herdr_kind(),+ reports_status: kind.reports_status(),+ cwd: &session.cwd,+ label: &label,+ focus: !self.options.no_focus,+ worktree_source: source.as_deref(),+ environment: environment.as_deref(),+ args: &args,+ })+ .await?;tracing::info!(session = %session.id,pane = %window.pane_id,diff --git a/crates/coding_agent_worker/src/herdr/cli.rs b/crates/coding_agent_worker/src/herdr/cli.rsindex 8809c7633c..5cb78583a9 100644--- a/crates/coding_agent_worker/src/herdr/cli.rs+++ b/crates/coding_agent_worker/src/herdr/cli.rs@@ -1,18 +1,26 @@-//! 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.+//! The one outbound door into the herdr macrod was started in. Two herdrs+//! exist and macrod drives either:+//!+//! - herdr 0.9 and earlier ([`legacy`]): the `herdr` multiplexer CLI, talking+//! to the session socket herdr injected into macrod's pane;+//! - herdr-core with the herdr app ([`hc`]): the `hc` CLI, whose terminals+//! the app shows as tabs.+//!+//! Callers ask for what they need (launch an agent, open a viewer, read a+//! screen) and never see which one answered.use std::path::{Path, PathBuf};+use std::sync::Arc;-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";+mod hc;+mod legacy;++#[cfg(test)]+mod test;/// A failure running a herdr command.#[derive(Debug, thiserror::Error)]@@ -40,35 +48,43 @@ pub(crate) enum HerdrError {#[source]source: serde_json::Error,},+ /// The agent's terminal is still there, but the agent is not.+ #[error("the agent's herdr terminal no longer runs it")]+ Ended,+ /// The agent started but never reported that it is ready for input.+ #[error("the agent did not become ready; finish any dialog in its Herdr tab")]+ NotReady,}impl HerdrError {/// Only an explicit missing-agent response permits a native session restart.pub(crate) fn missing_agent(&self) -> bool {- self.has_code("agent_not_found")+ matches!(self, Self::Ended)+ || self.has_code("/error/code", "agent_not_found")+ || self.has_code("/error/kind", "not_found")}/// The pane is not yet at its shell prompt, e.g. while direnv loads.pub(crate) fn pane_busy(&self) -> bool {- self.has_code("agent_pane_busy")+ self.has_code("/error/code", "agent_pane_busy")}- fn has_code(&self, code: &str) -> bool {+ fn has_code(&self, pointer: &str, code: &str) -> bool {let Self::Refused { stderr, .. } = self else {return false;};serde_json::from_str::<Value>(stderr).ok()- .is_some_and(|value| value.pointer("/error/code").and_then(Value::as_str) == Some(code))+ .is_some_and(|value| value.pointer(pointer).and_then(Value::as_str) == Some(code))}}/// 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`.+ /// The tab, e.g. `w1:t2`, or a herdr app tab id.pub tab_id: String,- /// The tab's only pane, e.g. `w1:p2`.+ /// The tab's only pane, e.g. `w1:p2`, or a herdr-core terminal like `t7`.pub pane_id: String,}@@ -85,248 +101,181 @@ pub(crate) struct AgentInfo {pub state_change_seq: u64,}+/// An agent TUI to start in its own tab.+#[derive(Debug, Clone, Copy)]+pub(crate) struct AgentLaunch<'a> {+ /// Unique name to address the agent by afterwards.+ pub name: &'a str,+ /// The agent's command, which is also herdr's `--kind` for it.+ pub kind: &'a str,+ /// Whether the agent reports its status itself (OSC 7501), so herdr-core+ /// can tell when it is ready.+ pub reports_status: bool,+ /// Where it runs.+ pub cwd: &'a Path,+ /// The tab's label.+ pub label: &'a str,+ /// Switch to the tab.+ pub focus: bool,+ /// For a managed worktree at `cwd`, the repository's main checkout.+ pub worktree_source: Option<&'a Path>,+ /// A private environment file to source before starting the agent.+ pub environment: Option<&'a Path>,+ /// The agent's arguments.+ pub args: &'a [String],+}+/// Drives the herdr session through its CLI.#[derive(Debug, Clone)]pub(crate) struct HerdrCli {- bin: PathBuf,- workspace_id: Option<String>,+ backend: Backend,+}++#[derive(Debug, Clone)]+enum Backend {+ Legacy(legacy::Legacy),+ Core(hc::Core),}impl HerdrCli {- /// Let Herdr create and register a fresh worktree from the fetched main ref.+ /// Drive the herdr 0.9 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 {+ backend: Backend::Legacy(legacy::Legacy {+ bin: bin.into(),+ workspace_id,+ }),+ }+ }++ /// Drive the herdr-core that runs `terminal`, macrod's own terminal.+ pub(crate) fn core(bin: impl Into<PathBuf>, terminal: impl Into<String>) -> Self {+ Self {+ backend: Backend::Core(hc::Core {+ bin: bin.into(),+ terminal: terminal.into(),+ space: Arc::default(),+ }),+ }+ }++ /// Create a fresh worktree of `source` at `path` from the fetched main ref.pub(crate) async fn create_worktree(&self,source: &Path,path: &Path,branch: &str,- ) -> Result<(), HerdrError> {- self.run(&[- "worktree",- "create",- "--cwd",- &source.to_string_lossy(),- "--path",- &path.to_string_lossy(),- "--branch",- branch,- "--base",- "origin/main",- "--no-focus",- ])- .await- .map(drop)+ ) -> rootcause::Result<()> {+ match &self.backend {+ Backend::Legacy(herdr) => Ok(herdr.create_worktree(source, path, branch).await?),+ Backend::Core(herdr) => herdr.create_worktree(source, path, branch).await,+ }}- /// Reuse Herdr's workspace and its shell pane for a managed session worktree.- pub(crate) async fn open_worktree(+ /// Open a tab for an agent TUI and start it there, returning once it is+ /// ready for input.+ pub(crate) async fn launch_agent(&self,- source: &Path,- path: &Path,- label: &str,- focus: bool,+ launch: &AgentLaunch<'_>,) -> Result<Window, HerdrError> {- let path = path.to_string_lossy();- let output = self- .run(&[- "worktree",- "open",- "--cwd",- &source.to_string_lossy(),- "--path",- &path,- "--label",- label,- if focus { "--focus" } else { "--no-focus" },- ])- .await?;- parse_window(&output)- }- /// 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,+ match &self.backend {+ Backend::Legacy(herdr) => herdr.launch_agent(launch).await,+ Backend::Core(herdr) => herdr.launch_agent(launch).await,}}- /// Open a tab in macrod's workspace, switching herdr to it when `focus`.- pub(crate) async fn open_window(+ /// Open a background tab in `cwd` running `command`.+ pub(crate) async fn open_viewer(&self,cwd: &Path,- label: &str,- focus: bool,+ command: &[String],) -> 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()]);+ match &self.backend {+ Backend::Legacy(herdr) => herdr.open_viewer(cwd, command).await,+ Backend::Core(herdr) => herdr.open_viewer(cwd, command).await,}- 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)+ /// Label a viewer's tab with its session's task.+ pub(crate) async fn name_viewer(&self, window: &Window, title: &str) -> Result<(), HerdrError> {+ match &self.backend {+ Backend::Legacy(herdr) => herdr.name_viewer(window, title).await,+ Backend::Core(herdr) => {+ herdr.name_viewer(window, title).await;+ Ok(())+ }+ }}- /// Report the lifecycle state of the agent a pane hosts, which is what- /// herdr's sidebar and notifications are driven by.+ /// Report the lifecycle state of the session a viewer shows, which is+ /// what herdr's sidebar and notifications are driven by. Under herdr-core+ /// the viewer reports it itself (OSC 7501), so this does nothing.pub(crate) async fn report_state(&self,- pane_id: &str,+ window: &Window,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]);+ match &self.backend {+ Backend::Legacy(herdr) => herdr.report_state(window, state, message, seq).await,+ Backend::Core(_) => Ok(()),}- 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)+ match &self.backend {+ Backend::Legacy(herdr) => herdr.prompt_agent(name, text).await,+ Backend::Core(herdr) => herdr.prompt_agent(name, text).await,+ }}/// 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 {- cwd: answer- .pointer("/result/agent/cwd")- .and_then(Value::as_str)- .map(PathBuf::from),- state_change_seq: answer- .pointer("/result/agent/state_change_seq")- .and_then(Value::as_u64)- .unwrap_or_default(),- 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),- })+ match &self.backend {+ Backend::Legacy(herdr) => herdr.agent_info(name).await,+ Backend::Core(herdr) => herdr.agent_info(name).await,+ }}/// 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+ match &self.backend {+ Backend::Legacy(herdr) => herdr.read_agent(name).await,+ Backend::Core(herdr) => herdr.read_agent(name).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)+ match &self.backend {+ Backend::Legacy(herdr) => herdr.send_keys(name, keys).await,+ Backend::Core(herdr) => herdr.send_keys(name, keys).await,+ }}+}- async fn run<Arg: AsRef<str>>(&self, args: &[Arg]) -> Result<String, HerdrError> {- let output = tokio::time::timeout(- std::time::Duration::from_secs(150),- 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::Timeout)?- .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())+async fn run<Arg: AsRef<str>>(bin: &Path, args: &[Arg]) -> Result<String, HerdrError> {+ let output = tokio::time::timeout(+ std::time::Duration::from_secs(150),+ tokio::process::Command::new(bin)+ .args(args.iter().map(AsRef::as_ref))+ .stdin(std::process::Stdio::null())+ .kill_on_drop(true)+ .output(),+ )+ .await+ .map_err(|_| HerdrError::Timeout)?+ .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 {@@ -336,32 +285,3 @@ fn describe<Arg: AsRef<str>>(args: &[Arg]) -> String {.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/cli/hc.rs b/crates/coding_agent_worker/src/herdr/cli/hc.rsnew file mode 100644index 0000000000..caaf729b1a--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/cli/hc.rs@@ -0,0 +1,357 @@+//! herdr-core (`hc`) and the herdr app: the core runs every terminal and+//! knows nothing about windows; the app shows a core terminal as a tab once+//! it carries the app's `herdr.space` and `herdr.tab` labels.+//!+//! A program's status is whatever it reports through OSC 7501. Claude Code+//! reports it; a TUI that does not (Codex today) has none, so macrod cannot+//! see it working or blocked.++use std::path::{Path, PathBuf};+use std::sync::Arc;+use std::time::Duration;++use serde::Deserialize;+use serde_json::{Value, json};+use tokio::sync::OnceCell;++use super::{AgentInfo, AgentLaunch, HerdrError, Window, run};++/// The labels the herdr app adopts terminals by.+const SPACE_LABEL: &str = "herdr.space";+const TAB_LABEL: &str = "herdr.tab";+/// The agent a session terminal was started for, to tell it from the shell+/// core leaves behind when a kept terminal loses its program.+const AGENT_LABEL: &str = "macro.agent";+/// The herdr app's CLI; optional, so every call to it is best effort.+const APP_BIN: &str = "herdr-app";+/// How long a new agent may take to report it is ready for input.+const AGENT_READY_TIMEOUT: Duration = Duration::from_secs(60);+const AGENT_READY_POLL: Duration = Duration::from_millis(250);+/// Polls with an unchanged screen after which an agent that never reports+/// status counts as ready.+const SETTLED_POLLS: u32 = 8;++#[derive(Debug, Clone)]+pub(super) struct Core {+ pub(super) bin: PathBuf,+ /// macrod's own terminal, whose space new tabs open in.+ pub(super) terminal: String,+ pub(super) space: Arc<OnceCell<Option<String>>>,+}++/// The parts of a core `Terminal` record macrod reads.+#[derive(Debug, Deserialize)]+pub(super) struct Terminal {+ address: String,+ state: String,+ cwd: String,+ #[serde(default)]+ labels: Option<std::collections::BTreeMap<String, String>>,+ #[serde(default)]+ status: Option<Status>,+ #[serde(default)]+ status_ms: Option<u64>,+ #[serde(default)]+ foreground: Option<Foreground>,+}++#[derive(Debug, Deserialize)]+struct Status {+ state: String,+}++#[derive(Debug, Deserialize)]+struct Foreground {+ name: String,+}++impl Terminal {+ fn label(&self, key: &str) -> Option<&str> {+ self.labels.as_ref()?.get(key).map(String::as_str)+ }++ /// Whether the agent it was started for still runs in it. A finished+ /// terminal has no agent; neither does a kept one whose agent was lost+ /// and replaced by a shell. A reported status belongs to a live agent,+ /// since core clears it when the program ends.+ fn agent_running(&self) -> bool {+ if self.state != "live" {+ return false;+ }+ if self.status.is_some() {+ return true;+ }+ match (self.label(AGENT_LABEL), &self.foreground) {+ (Some(agent), Some(foreground)) => foreground.name.contains(agent),+ _ => true,+ }+ }++ pub(super) fn info(self) -> Result<AgentInfo, HerdrError> {+ if !self.agent_running() {+ return Err(HerdrError::Ended);+ }+ Ok(AgentInfo {+ status: self+ .status+ .map(|status| status.state)+ .unwrap_or_else(|| "unknown".to_owned()),+ session_id: None,+ cwd: Some(PathBuf::from(self.cwd)),+ state_change_seq: self.status_ms.unwrap_or_default(),+ })+ }+}++impl Core {+ /// Add a worktree of `source` at `path` on a new branch from the+ /// freshly fetched main. Core has no worktree concept; git does it.+ pub(super) async fn create_worktree(+ &self,+ source: &Path,+ path: &Path,+ branch: &str,+ ) -> rootcause::Result<()> {+ crate::outbound::git::git(+ source,+ &[+ "worktree",+ "add",+ "-b",+ branch,+ &path.to_string_lossy(),+ "origin/main",+ ],+ )+ .await+ .map(drop)+ }++ /// Start a shell in a new tab, then replace it with the agent, so the+ /// agent gets the operator's login environment (PATH, direnv) as it+ /// would in a terminal they opened themselves.+ pub(super) async fn launch_agent(+ &self,+ launch: &AgentLaunch<'_>,+ ) -> Result<Window, HerdrError> {+ self.clear(launch.name).await;+ // A worktree opens as its own space, as herdr's worktree workspaces did.+ let space = match launch.worktree_source {+ Some(_) => new_id(),+ None => self.space().await,+ };+ let tab = new_id();+ let terminal = self+ .start(+ Some(launch.name),+ launch.cwd,+ &space,+ &tab,+ &[format!("{AGENT_LABEL}={}", launch.kind)],+ &[],+ )+ .await?;+ let mut line = String::new();+ if let Some(environment) = launch.environment {+ line.push_str(&format!(+ ". {} && ",+ shell_words::quote(&environment.to_string_lossy())+ ));+ }+ let mut command = vec![launch.kind.to_owned()];+ command.extend(launch.args.iter().cloned());+ line.push_str("exec ");+ line.push_str(&shell_words::join(&command));+ self.run(&["send", &terminal.address, &line]).await?;+ self.wait_ready(launch).await?;+ tracing::debug!(terminal = %terminal.address, agent = launch.kind, "agent ready in herdr-core");+ self.app("tab.rename", json!({"id": tab, "name": launch.label}))+ .await;+ if launch.focus {+ self.app("agent.focus", json!({"terminal": terminal.address}))+ .await;+ }+ Ok(Window {+ tab_id: tab,+ pane_id: terminal.address,+ })+ }++ pub(super) async fn open_viewer(+ &self,+ cwd: &Path,+ command: &[String],+ ) -> Result<Window, HerdrError> {+ let space = self.space().await;+ let tab = new_id();+ let terminal = self.start(None, cwd, &space, &tab, &[], command).await?;+ Ok(Window {+ tab_id: tab,+ pane_id: terminal.address,+ })+ }++ pub(super) async fn name_viewer(&self, window: &Window, title: &str) {+ self.app("tab.rename", json!({"id": window.tab_id, "name": title}))+ .await;+ }++ pub(super) async fn prompt_agent(&self, name: &str, text: &str) -> Result<(), HerdrError> {+ self.run(&["send", name, text]).await.map(drop)+ }++ pub(super) async fn agent_info(&self, name: &str) -> Result<AgentInfo, HerdrError> {+ self.get(name).await?.info()+ }++ pub(super) async fn read_agent(&self, name: &str) -> Result<String, HerdrError> {+ self.run(&["read", name]).await+ }++ pub(super) async fn send_keys(&self, name: &str, keys: &[&str]) -> Result<(), HerdrError> {+ let mut args = vec!["keys", name];+ args.extend(keys);+ self.run(&args).await.map(drop)+ }++ /// Run a terminal in `space`'s tab `tab`, outliving macrod like a tab+ /// someone opened by hand. With no `command`, it runs the user's shell.+ async fn start(+ &self,+ name: Option<&str>,+ cwd: &Path,+ space: &str,+ tab: &str,+ labels: &[String],+ command: &[String],+ ) -> Result<Terminal, HerdrError> {+ let mut args = vec![+ "run".to_owned(),+ "--bg".to_owned(),+ "--json".to_owned(),+ "--no-parent".to_owned(),+ "--cwd".to_owned(),+ cwd.to_string_lossy().into_owned(),+ "--label".to_owned(),+ format!("{SPACE_LABEL}={space}"),+ "--label".to_owned(),+ format!("{TAB_LABEL}={tab}"),+ ];+ for label in labels {+ args.extend(["--label".to_owned(), label.clone()]);+ }+ if let Some(name) = name {+ args.extend(["--name".to_owned(), name.to_owned()]);+ }+ if !command.is_empty() {+ args.push("--".to_owned());+ args.extend(command.iter().cloned());+ }+ let output = self.run(&args).await?;+ parse_terminal("run", &output)+ }++ /// Wait for the agent to report it is idle. One that never reports+ /// status is ready once its screen stops changing; one that does must+ /// say so, or it is likely on a dialog (folder trust, sign-in) where a+ /// typed prompt would answer the wrong question.+ async fn wait_ready(&self, launch: &AgentLaunch<'_>) -> Result<(), HerdrError> {+ let deadline = tokio::time::Instant::now() + AGENT_READY_TIMEOUT;+ let mut screen = String::new();+ let mut settled = 0u32;+ while tokio::time::Instant::now() < deadline {+ tokio::time::sleep(AGENT_READY_POLL).await;+ let terminal = self.get(launch.name).await?;+ if terminal.state != "live" {+ return Err(HerdrError::Ended);+ }+ if let Some(status) = &terminal.status {+ if status.state != "working" {+ return Ok(());+ }+ continue;+ }+ if launch.reports_status+ || !terminal+ .foreground+ .as_ref()+ .is_some_and(|foreground| foreground.name.contains(launch.kind))+ {+ continue;+ }+ let current = self.read_agent(launch.name).await?;+ settled = if current == screen { settled + 1 } else { 0 };+ screen = current;+ if settled >= SETTLED_POLLS {+ return Ok(());+ }+ }+ if launch.reports_status {+ return Err(HerdrError::NotReady);+ }+ Ok(())+ }++ /// Remove a previous terminal of this name: a finished one keeps its+ /// name until removed, and a kept one may be a shell left behind by a+ /// lost agent.+ async fn clear(&self, name: &str) {+ let Ok(terminal) = self.get(name).await else {+ return;+ };+ if terminal.state == "live"+ && let Err(error) = self.run(&["kill", name]).await+ {+ tracing::warn!(%error, terminal = name, "could not end a stale session terminal");+ }+ if let Err(error) = self.run(&["rm", name]).await {+ tracing::debug!(%error, terminal = name, "could not remove a stale session terminal");+ }+ }++ async fn get(&self, terminal: &str) -> Result<Terminal, HerdrError> {+ let output = self.run(&["get", terminal, "--json"]).await?;+ parse_terminal("get", &output)+ }++ /// The herdr app space macrod's terminal is in; a new one when macrod+ /// runs outside the app.+ async fn space(&self) -> String {+ let space = self+ .space+ .get_or_init(|| async {+ match self.get(&self.terminal).await {+ Ok(terminal) => terminal.label(SPACE_LABEL).map(str::to_owned),+ Err(error) => {+ tracing::warn!(%error, "could not read macrod's herdr-core terminal");+ None+ }+ }+ })+ .await;+ space.clone().unwrap_or_else(new_id)+ }++ /// Run an action in the open herdr app window, if there is one. Tabs+ /// work without the app, so failure is only logged.+ async fn app(&self, action: &str, arguments: Value) {+ if let Err(error) = run(Path::new(APP_BIN), &["do", action, &arguments.to_string()]).await {+ tracing::debug!(%error, action, "herdr app action failed");+ }+ }++ async fn run<Arg: AsRef<str>>(&self, args: &[Arg]) -> Result<String, HerdrError> {+ run(&self.bin, args).await+ }+}++fn new_id() -> String {+ uuid::Uuid::now_v7().simple().to_string()+}++pub(super) fn parse_terminal(command: &str, output: &str) -> Result<Terminal, HerdrError> {+ serde_json::from_str(output.trim()).map_err(|source| HerdrError::Unparsable {+ command: command.to_owned(),+ source,+ })+}diff --git a/crates/coding_agent_worker/src/herdr/cli/legacy.rs b/crates/coding_agent_worker/src/herdr/cli/legacy.rsnew file mode 100644index 0000000000..3f7fd9449f--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/cli/legacy.rs@@ -0,0 +1,296 @@+//! herdr 0.9 and earlier: the `herdr` multiplexer CLI, with workspaces, tabs,+//! panes, worktrees, and a built-in agent registry.++use std::path::{Path, PathBuf};+use std::time::Duration;++use serde::Deserialize;+use serde_json::Value;++use super::{AgentInfo, AgentLaunch, HerdrError, Window, run};+use crate::herdr::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";+const DISPLAY_AGENT: &str = "Macro agent";+/// How long a new tab's shell may take to reach its prompt.+const SHELL_READY_TIMEOUT: Duration = Duration::from_secs(10);+const SHELL_READY_POLL: Duration = Duration::from_millis(250);++#[derive(Debug, Clone)]+pub(super) struct Legacy {+ pub(super) bin: PathBuf,+ pub(super) workspace_id: Option<String>,+}++impl Legacy {+ /// Let Herdr create and register a fresh worktree from the fetched main ref.+ pub(super) async fn create_worktree(+ &self,+ source: &Path,+ path: &Path,+ branch: &str,+ ) -> Result<(), HerdrError> {+ self.run(&[+ "worktree",+ "create",+ "--cwd",+ &source.to_string_lossy(),+ "--path",+ &path.to_string_lossy(),+ "--branch",+ branch,+ "--base",+ "origin/main",+ "--no-focus",+ ])+ .await+ .map(drop)+ }++ pub(super) async fn launch_agent(+ &self,+ launch: &AgentLaunch<'_>,+ ) -> Result<Window, HerdrError> {+ let window = match launch.worktree_source {+ Some(source) => {+ self.open_worktree(source, launch.cwd, launch.label, launch.focus)+ .await?+ }+ None => {+ self.open_window(launch.cwd, launch.label, launch.focus)+ .await?+ }+ };+ if let Some(environment) = launch.environment {+ self.run(&[+ "pane",+ "run",+ &window.pane_id,+ &format!(". {}", shell_words::quote(&environment.to_string_lossy())),+ ])+ .await?;+ }+ // The tab's shell must reach its prompt before an agent can start,+ // and a worktree's direnv can hold it for seconds.+ let deadline = tokio::time::Instant::now() + SHELL_READY_TIMEOUT;+ loop {+ match self.start_agent(launch, &window.pane_id).await {+ Err(error) if error.pane_busy() && tokio::time::Instant::now() < deadline => {+ tokio::time::sleep(SHELL_READY_POLL).await;+ }+ result => break result?,+ }+ }+ Ok(window)+ }++ pub(super) async fn open_viewer(+ &self,+ cwd: &Path,+ command: &[String],+ ) -> Result<Window, HerdrError> {+ let window = self.open_window(cwd, "macro", false).await?;+ self.run(&["pane", "run", &window.pane_id, &shell_words::join(command)])+ .await?;+ self.report_title(&window.pane_id, None).await?;+ Ok(window)+ }++ pub(super) async fn name_viewer(&self, window: &Window, title: &str) -> Result<(), HerdrError> {+ self.run(&["tab", "rename", &window.tab_id, title]).await?;+ self.report_title(&window.pane_id, Some(title)).await+ }++ /// Report the lifecycle state of the agent a pane hosts, which is what+ /// herdr's sidebar and notifications are driven by.+ pub(super) async fn report_state(+ &self,+ window: &Window,+ state: AgentState,+ message: Option<&str>,+ seq: u64,+ ) -> Result<(), HerdrError> {+ let seq = seq.to_string();+ let mut args = vec![+ "pane",+ "report-agent",+ &window.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)+ }++ pub(super) async fn prompt_agent(&self, name: &str, text: &str) -> Result<(), HerdrError> {+ self.run(&["agent", "prompt", name, text]).await.map(drop)+ }++ pub(super) 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 {+ cwd: answer+ .pointer("/result/agent/cwd")+ .and_then(Value::as_str)+ .map(PathBuf::from),+ state_change_seq: answer+ .pointer("/result/agent/state_change_seq")+ .and_then(Value::as_u64)+ .unwrap_or_default(),+ 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),+ })+ }++ pub(super) async fn read_agent(&self, name: &str) -> Result<String, HerdrError> {+ self.run(&["agent", "read", name, "--source", "visible"])+ .await+ }++ pub(super) 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)+ }++ /// Reuse Herdr's workspace and its shell pane for a managed session worktree.+ async fn open_worktree(+ &self,+ source: &Path,+ path: &Path,+ label: &str,+ focus: bool,+ ) -> Result<Window, HerdrError> {+ let path = path.to_string_lossy();+ let output = self+ .run(&[+ "worktree",+ "open",+ "--cwd",+ &source.to_string_lossy(),+ "--path",+ &path,+ "--label",+ label,+ if focus { "--focus" } else { "--no-focus" },+ ])+ .await?;+ parse_window(&output)+ }++ /// Open a tab in macrod's workspace, switching herdr to it when `focus`.+ 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)+ }++ /// Start a recognized agent CLI in an idle shell pane under a unique+ /// name, returning once herdr sees it ready for input.+ async fn start_agent(&self, launch: &AgentLaunch<'_>, pane_id: &str) -> Result<(), HerdrError> {+ let mut args: Vec<&str> = vec![+ "agent",+ "start",+ launch.name,+ "--kind",+ launch.kind,+ "--pane",+ pane_id,+ "--timeout",+ "60000",+ "--",+ ];+ args.extend(launch.args.iter().map(String::as_str));+ self.run(&args).await.map(drop)+ }++ /// Name the agent and its task in herdr's sidebar.+ async fn report_title(&self, pane_id: &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)+ }++ async fn run<Arg: AsRef<str>>(&self, args: &[Arg]) -> Result<String, HerdrError> {+ run(&self.bin, args).await+ }+}++#[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/cli/test.rs b/crates/coding_agent_worker/src/herdr/cli/test.rsnew file mode 100644index 0000000000..2a4df7b100--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/cli/test.rs@@ -0,0 +1,151 @@+use std::os::unix::fs::PermissionsExt as _;+use std::path::Path;++use super::hc::parse_terminal;+use super::*;++fn info(record: &str) -> Result<AgentInfo, HerdrError> {+ parse_terminal("get", record).unwrap().info()+}++#[test]+fn a_reporting_agent_shows_its_own_status() {+ let info = info(+ r#"{"address":"t4","state":"live","cwd":"/work","status":{"state":"blocked","app":"claude-code"},"status_ms":42,"foreground":{"pid":1,"name":".claude-wrapped","argv":[],"cwd":"/work/sub"}}"#,+ )+ .unwrap();+ assert_eq!(+ info,+ AgentInfo {+ status: "blocked".to_owned(),+ session_id: None,+ cwd: Some("/work".into()),+ state_change_seq: 42,+ }+ );+}++#[test]+fn an_agent_without_status_is_unknown_while_it_runs() {+ let info = info(+ r#"{"address":"t4","state":"live","cwd":"/work","labels":{"macro.agent":"codex"},"status":null,"foreground":{"pid":1,"name":"codex","argv":[],"cwd":"/work"}}"#,+ )+ .unwrap();+ assert_eq!(info.status, "unknown");+}++#[test]+fn a_finished_or_replaced_agent_is_missing() {+ let finished = info(r#"{"address":"t4","state":"finished","cwd":"/work"}"#).unwrap_err();+ assert!(finished.missing_agent());+ // A kept terminal whose agent was lost runs a fresh shell in its place.+ let replaced = info(+ r#"{"address":"t4","state":"live","cwd":"/work","labels":{"macro.agent":"claude"},"status":null,"foreground":{"pid":1,"name":"bash","argv":[],"cwd":"/work"}}"#,+ )+ .unwrap_err();+ assert!(replaced.missing_agent());+}++#[test]+fn both_herdrs_name_a_missing_agent() {+ let refused = |stderr: &str| HerdrError::Refused {+ command: "get".to_owned(),+ stderr: stderr.to_owned(),+ };+ assert!(refused(r#"{"error":{"code":"agent_not_found"}}"#).missing_agent());+ assert!(refused(r#"{"error":{"kind":"not_found","message":"no terminal"}}"#).missing_agent());+ assert!(!refused(r#"{"error":{"kind":"blocked"}}"#).missing_agent());+ assert!(refused(r#"{"error":{"code":"agent_pane_busy"}}"#).pane_busy());+}++/// A fake `hc` that logs each call and answers like herdr-core does.+fn fake_hc(root: &Path) -> std::path::PathBuf {+ let script = root.join("hc");+ let calls = root.join("calls");+ std::fs::write(+ &script,+ format!(+ r#"#!/bin/sh+printf '%s\n' "$*" >> {calls}+case "$1 $2" in+ "get t1") echo '{{"address":"t1","state":"live","cwd":"/","labels":{{"herdr.space":"space-1"}}}}' ;;+ "get macro-abc") echo '{{"address":"t9","state":"live","cwd":"/work","labels":{{"macro.agent":"codex"}},"status":{{"state":"idle"}}}}' ;;+ run*) echo '{{"address":"t9","state":"live","cwd":"/work"}}' ;;+ *) echo '{{}}' ;;+esac+"#,+ calls = shell_words::quote(&calls.to_string_lossy()),+ ),+ )+ .unwrap();+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();+ script+}++#[tokio::test]+async fn herdr_core_opens_the_agent_as_a_tab_in_macrods_space() {+ let root = tempfile::tempdir().unwrap();+ let herdr = HerdrCli::core(fake_hc(root.path()), "t1");+ let args = ["--model".to_owned(), "gpt 5".to_owned()];+ let window = herdr+ .launch_agent(&AgentLaunch {+ name: "macro-abc",+ kind: "codex",+ reports_status: false,+ cwd: Path::new("/work"),+ label: "fix it",+ focus: false,+ worktree_source: None,+ environment: Some(Path::new("/private/env file")),+ args: &args,+ })+ .await+ .unwrap();+ assert_eq!(window.pane_id, "t9");++ let calls = std::fs::read_to_string(root.path().join("calls")).unwrap();+ let calls: Vec<&str> = calls.lines().collect();+ let run = calls.iter().find(|call| call.starts_with("run ")).unwrap();+ assert!(run.contains("--no-parent"));+ assert!(run.contains("--label herdr.space=space-1"));+ assert!(run.contains(&format!("--label herdr.tab={}", window.tab_id)));+ assert!(run.contains("--label macro.agent=codex"));+ assert!(run.contains("--name macro-abc"));+ // A shell, not the agent: it starts with the operator's login environment.+ assert!(!run.contains(" -- "));+ assert!(calls.contains(&"send t9 . '/private/env file' && exec codex --model 'gpt 5'"));+ // The previous terminal of this name was ended before the new one ran.+ let kill = calls+ .iter()+ .position(|call| *call == "kill macro-abc")+ .unwrap();+ let run = calls+ .iter()+ .position(|call| call.starts_with("run "))+ .unwrap();+ assert!(kill < run);+}++#[tokio::test]+async fn herdr_core_viewers_report_their_own_state() {+ let root = tempfile::tempdir().unwrap();+ let herdr = HerdrCli::core(fake_hc(root.path()), "t1");+ let window = herdr+ .open_viewer(+ Path::new("/work"),+ &["macrod".to_owned(), "herdr-pane".to_owned()],+ )+ .await+ .unwrap();+ herdr+ .report_state(&window, AgentState::Working, None, 1)+ .await+ .unwrap();+ let calls = std::fs::read_to_string(root.path().join("calls")).unwrap();+ assert!(+ calls+ .lines()+ .any(|call| call.starts_with("run ") && call.ends_with("-- macrod herdr-pane"))+ );+ assert!(!calls.contains("report"));+}diff --git a/crates/coding_agent_worker/src/herdr/hub.rs b/crates/coding_agent_worker/src/herdr/hub.rsindex 8208e24893..3315e0f390 100644--- a/crates/coding_agent_worker/src/herdr/hub.rs+++ b/crates/coding_agent_worker/src/herdr/hub.rs@@ -33,7 +33,6 @@ mod test;/// 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>;@@ -83,7 +82,7 @@ impl Hub {web_url: web_url.trim_end_matches('/').to_owned(),});let launcher = Launcher {- cli: HerdrCli::new(&herdr.bin, herdr.workspace_id.clone()),+ cli: herdr.cli(),workspace: workspace.to_owned(),pane_command: pane_command(&socket),windows: HashMap::new(),@@ -389,18 +388,9 @@ impl Launcher {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?;+ let window = self.cli.open_viewer(&self.workspace, &command).await?;tracing::info!(%session,tab = %window.tab_id,@@ -419,17 +409,14 @@ impl Launcher {};self.seq += 1;self.cli- .report_state(&window.pane_id, state, message.as_deref(), self.seq)+ .report_state(window, 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?;+ self.cli.name_viewer(window, &title).await?;}}Ok(())diff --git a/crates/coding_agent_worker/src/herdr/repositories.rs b/crates/coding_agent_worker/src/herdr/repositories.rsindex 436c103b59..b7338fc551 100644--- a/crates/coding_agent_worker/src/herdr/repositories.rs+++ b/crates/coding_agent_worker/src/herdr/repositories.rs@@ -1,4 +1,4 @@-//! Session workspaces: the repository store refreshes Git; Herdr owns worktrees.+//! Session workspaces: the repository store refreshes Git; herdr (git itself under herdr-core) creates worktrees.use super::cli::HerdrCli;use crate::outbound::git::{GitRepositories, git, primary_worktree};diff --git a/crates/coding_agent_worker/src/herdr/test.rs b/crates/coding_agent_worker/src/herdr/test.rsindex 1c2b331bdb..1e63a84b4f 100644--- a/crates/coding_agent_worker/src/herdr/test.rs+++ b/crates/coding_agent_worker/src/herdr/test.rs@@ -80,3 +80,16 @@ fn instance_settings_keep_native_arguments_after_the_separator() {]);}++#[test]+fn viewer_states_encode_as_program_status_reports() {+ use wire::AgentState;+ assert_eq!(+ AgentState::Working.osc_7501(None),+ "\x1b]7501;state=working:app=macro\x1b\\"+ );+ assert_eq!(+ AgentState::Blocked.osc_7501(Some("Run ls?")),+ "\x1b]7501;state=blocked:app=macro:kind=permission:msg=UnVuIGxzPw==\x1b\\"+ );+}diff --git a/crates/coding_agent_worker/src/herdr/wire.rs b/crates/coding_agent_worker/src/herdr/wire.rsindex 867a91fd6f..789dd24d24 100644--- a/crates/coding_agent_worker/src/herdr/wire.rs+++ b/crates/coding_agent_worker/src/herdr/wire.rs@@ -24,6 +24,22 @@ impl AgentState {Self::Blocked => "blocked",}}++ /// The state as an OSC 7501 report, how a program tells herdr-core and+ /// the herdr app what it is doing. A blocked session waits on a+ /// permission answer.+ pub(crate) fn osc_7501(self, message: Option<&str>) -> String {+ use base64::Engine as _;+ let mut fields = vec![format!("state={}", self.as_herdr()), "app=macro".to_owned()];+ if self == Self::Blocked {+ fields.push("kind=permission".to_owned());+ }+ if let Some(message) = message.filter(|message| !message.is_empty()) {+ let message = base64::engine::general_purpose::STANDARD.encode(message);+ fields.push(format!("msg={message}"));+ }+ format!("\x1b]7501;{}\x1b\\", fields.join(":"))+ }}/// One answer an agent offered to a permission request.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.rsindex fb5fa08be5..7aec3d5317 100644--- a/crates/coding_agent_worker/src/tui/agent_catalog/herdr_tui.rs+++ b/crates/coding_agent_worker/src/tui/agent_catalog/herdr_tui.rs@@ -22,18 +22,18 @@ impl AgentPreset for HerdrTui {}fn detect(&self, commands: &dyn CommandLookup) -> Availability {- let missing: Vec<&'static str> = [self.0.herdr_kind(), "herdr"]+ let Some(herdr) = crate::herdr::HerdrSession::detect() else {+ return Availability::Unavailable {+ missing: vec!["a herdr pane"],+ };+ };+ let missing: Vec<&'static str> = [self.0.herdr_kind(), herdr.command()].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"],diff --git a/crates/coding_agent_worker/src/tui/herdr_pane.rs b/crates/coding_agent_worker/src/tui/herdr_pane.rsindex f37d8964cf..59b8e4012c 100644--- a/crates/coding_agent_worker/src/tui/herdr_pane.rs+++ b/crates/coding_agent_worker/src/tui/herdr_pane.rs@@ -356,6 +356,9 @@ pub async fn run_herdr_pane(socket: &Path, session: &str) -> rootcause::Result<(let mut terminal = ratatui::init();let _ = crossterm::execute!(std::io::stdout(), crossterm::event::EnableBracketedPaste);+ // Under herdr-core the window reports the session's state itself.+ let reports_status =+ crate::herdr::HerdrSession::detect().is_some_and(|herdr| herdr.panes_report_status());let mut view = PaneView::new(session);let mut ticker = tokio::time::interval(TICK);let outcome = loop {@@ -382,6 +385,11 @@ pub async fn run_herdr_pane(socket: &Path, session: &str) -> rootcause::Result<(view.disconnected();break;};+ if reports_status+ && let ToPane::State { state, detail } = &message+ {+ report_status(*state, detail.as_deref());+ }view.apply(message);match message_rx.try_recv() {Ok(message) => next = Some(message),@@ -396,3 +404,15 @@ pub async fn run_herdr_pane(socket: &Path, session: &str) -> rootcause::Result<(outcome.context("the window's terminal failed")?;Ok(())}++/// Tell herdr-core what the session is doing, between frames.+fn report_status(state: AgentState, detail: Option<&str>) {+ use std::io::Write as _;+ let mut stdout = std::io::stdout();+ if let Err(error) = stdout+ .write_all(state.osc_7501(detail).as_bytes())+ .and_then(|()| stdout.flush())+ {+ tracing::debug!(%error, "could not report the session's status to herdr");+ }+}diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.mdindex 1fac87b3d7..b29af908fa 100644--- a/docs/agent-guide/ai-chat.md+++ b/docs/agent-guide/ai-chat.md@@ -669,6 +669,10 @@ the shimmer.TUI. The session page streams its tool calls and replies, and its permissionprompts appear as approvals. Other runtimes started inside herdr get a liveview tab per session that can prompt and interrupt it; approvals stay in Macro.+ This works in herdr 0.9 and in the herdr app (herdr-core, with `hc` on `PATH`),+ where session tabs open in macrod's space. Under herdr-core, Codex reports no+ status, so its permission prompts must be answered in Herdr; see "Herdr+ versions" in `crates/coding_agent_worker/README.md`.Native Herdr sessions offer `/compact`, `/init`, and `/fast` in the slash menu;Codex also offers `/ultrafast`. Macro confirms delivery of speed commands;check their result and any confirmation in Herdr. For Claude, use `/fast on`