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
fix(macrod): run the installed CLI behind the npm ACP adapters, and own the child spawn (#6882)
Wolf Mermelsteinad9cc42fc7ec
diff --git a/Cargo.lock b/Cargo.lockindex 51fc95672f..ec5adf3ee5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3915,6 +3915,7 @@ dependencies = ["ratatui","reqwest 0.13.4","rootcause",+ "rustix 1.1.4","rustls 0.23.45","serde","serde_json",diff --git a/Cargo.toml b/Cargo.tomlindex 33e8fc9c72..235952b164 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -290,6 +290,9 @@ rmcp = "1.6.0"sse-stream = "0.2"rootcause = { version = "0.12", features = ["compat-anyhow1"] }rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs"] }+# Mirrors the ACP SDK's own declaration: `coding_agent_worker` ports its+# process-group kill and makes the same call.+rustix = { version = "1", default-features = false, features = ["process", "std"] }rootcause-tracing = "0.12.1"schemars = { version = "1.0.4", features = ["chrono04", "uuid1"] }semver = { version = "1", features = ["serde"] }diff --git a/crates/channels/src/domain/dm.rs b/crates/channels/src/domain/dm.rsindex d4d4749eb9..c4c67b5a43 100644--- a/crates/channels/src/domain/dm.rs+++ b/crates/channels/src/domain/dm.rs@@ -58,6 +58,8 @@ pub struct EnsureDms {}impl EnsureDms {+ // Only the service consumes a batch, and that lives behind `ports`.+ #[cfg(feature = "ports")]pub(crate) fn into_requests(self) -> Vec<EnsureDm> {self.requests}diff --git a/crates/coding_agent_worker/Cargo.toml b/crates/coding_agent_worker/Cargo.tomlindex 851bf581f8..d2de0d9cb8 100644--- a/crates/coding_agent_worker/Cargo.toml+++ b/crates/coding_agent_worker/Cargo.toml@@ -44,7 +44,7 @@ strum = { workspace = true }thiserror = { workspace = true }tokio = { workspace = true, features = ["macros", "process", "rt-multi-thread", "signal", "time"] }tokio-retry = { workspace = true }-tokio-util = { workspace = true, features = ["rt"] }+tokio-util = { workspace = true, features = ["compat", "rt"] }tokio-tungstenite = { workspace = true }toml = { workspace = true }toml_edit = { workspace = true }@@ -56,6 +56,9 @@ webbrowser = { workspace = true }webhook = { path = "../webhook", default-features = false }workspace-hack = { version = "0.1", path = "../workspace-hack" }+[target.'cfg(unix)'.dependencies]+rustix = { workspace = true }+[dev-dependencies]bot_id = { path = "../bot_id", features = ["test-utils"] }channel_sender = { path = "../channel_sender" }diff --git a/crates/coding_agent_worker/config.example.toml b/crates/coding_agent_worker/config.example.tomlindex 971f195abd..f6f02a822c 100644--- a/crates/coding_agent_worker/config.example.toml+++ b/crates/coding_agent_worker/config.example.toml@@ -29,6 +29,10 @@ allow_permission_bypass = false[harness]command = "hermes"args = ["acp"]+# Optional: environment added to the harness and to every model probe. The+# Codex and Claude Code presets set it to point their npm adapter at the CLI+# installed on this machine instead of the copy the adapter bundles, e.g.+# env = { CODEX_PATH = "/usr/local/bin/codex" }[workspace]# Every session this daemon serves runs here.diff --git a/crates/coding_agent_worker/src/config.rs b/crates/coding_agent_worker/src/config.rsindex d9458c1daa..16622f0368 100644--- a/crates/coding_agent_worker/src/config.rs+++ b/crates/coding_agent_worker/src/config.rs@@ -7,6 +7,7 @@use harness_id::HarnessId;use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;use std::path::{Path, PathBuf};#[cfg(test)]@@ -159,6 +160,16 @@ pub struct Harness {/// Arguments, e.g. `["acp"]`.#[serde(default)]pub args: Vec<String>,+ /// Environment added to the harness process and to every model probe, on+ /// top of the daemon's own.+ ///+ /// ACP adapters distributed on npm bundle their own copy of the CLI they+ /// wrap and run it unless told otherwise. A bundled CLI older than the+ /// one the operator installed advertises a different model catalogue, so+ /// the presets point the adapter at the installed CLI through the+ /// variable it reads for that - `CODEX_PATH`, `CLAUDE_CODE_EXECUTABLE`.+ #[serde(default)]+ pub env: BTreeMap<String, String>,}/// The workspace every session runs against.diff --git a/crates/coding_agent_worker/src/config/test.rs b/crates/coding_agent_worker/src/config/test.rsindex 8b71b347e2..138a3dc210 100644--- a/crates/coding_agent_worker/src/config/test.rs+++ b/crates/coding_agent_worker/src/config/test.rs@@ -82,6 +82,29 @@ fn identity_args_and_web_url_default() {assert_eq!(config.macro_api.web_url, "https://macro.com/app");}+#[test]+fn harness_env_is_optional() {+ // The example carries no `env`, as every config written before it existed.+ let config: Config = toml::from_str(EXAMPLE).expect("example config parses");+ assert!(config.harness.env.is_empty());++ let with_env = EXAMPLE.replace(+ "args = [\"acp\"]\n",+ "args = [\"acp\"]\nenv = { CODEX_PATH = \"/nix/store/x/bin/codex\", CLAUDE_CODE_EXECUTABLE = \"/bin/claude\" }\n",+ );+ let config: Config = toml::from_str(&with_env).expect("harness env parses");+ assert_eq!(+ config.harness.env,+ BTreeMap::from([+ ("CODEX_PATH".to_owned(), "/nix/store/x/bin/codex".to_owned()),+ (+ "CLAUDE_CODE_EXECUTABLE".to_owned(),+ "/bin/claude".to_owned()+ ),+ ])+ );+}+#[test]fn identity_scope_accepts_team() {let team = EXAMPLE.replace("scope = \"private\"", "scope = \"team\"");diff --git a/crates/coding_agent_worker/src/daemon.rs b/crates/coding_agent_worker/src/daemon.rsindex 5f27252be9..c49db5309a 100644--- a/crates/coding_agent_worker/src/daemon.rs+++ b/crates/coding_agent_worker/src/daemon.rs@@ -4,10 +4,9 @@//! credential changes (a re-pair) and stopping it when the harness is//! removed - which is what makes the TUI and the daemon one process.-use std::path::{Path, PathBuf};+use std::path::Path;use std::time::Duration;-use rootcause::prelude::ResultExt as _;use tokio_util::sync::CancellationToken;use crate::config::{Config, HarnessCredentials};@@ -42,14 +41,6 @@ impl Daemon {credentials: HarnessCredentials,_config_path: &Path,) -> rootcause::Result<Self> {- // The ACP launch config carries command, args, and env but no working- // directory, and every session this daemon serves runs in the one- // configured workspace - so the daemon's own cwd is the harness's cwd.- std::env::set_current_dir(&config.workspace.path).context(format!(- "failed to enter the workspace directory {}",- config.workspace.path.display()- ))?;-let cancel = CancellationToken::new();let client = EventStreamClient::new(&config.macro_api, &credentials);let api = HarnessApi::new(&config.macro_api, &credentials);@@ -115,12 +106,6 @@ impl Daemon {}}-/// Absolute form of the config path, so a `chdir` into the workspace never-/// re-points relative reads and writes of the config.-pub fn absolute_config_path(config_path: &Path) -> PathBuf {- std::path::absolute(config_path).unwrap_or_else(|_| config_path.to_owned())-}-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/daemon/test.rs b/crates/coding_agent_worker/src/daemon/test.rsindex e882166bca..03c9247777 100644--- a/crates/coding_agent_worker/src/daemon/test.rs+++ b/crates/coding_agent_worker/src/daemon/test.rs@@ -13,6 +13,10 @@ async fn stop_does_not_wait_for_in_flight_work() {}#[tokio::test]+#[expect(+ clippy::result_large_err,+ reason = "the handshake callback's error type is fixed by tungstenite's Callback trait"+)]async fn startup_without_agents_serves_model_probes_and_stop_closes_the_runtime() {use agent_runtime_protocol::domain::schema::v0::{ModelProbeResult, SystemEvent, ToRuntimeMessage, ToServerMessage,diff --git a/crates/coding_agent_worker/src/harness.rs b/crates/coding_agent_worker/src/harness.rsindex 05c8d897ff..23855ae582 100644--- a/crates/coding_agent_worker/src/harness.rs+++ b/crates/coding_agent_worker/src/harness.rs@@ -6,7 +6,8 @@ use std::time::Duration;use crate::config::Harness;use crate::outbound::acp_probe::{ProbeError, ProbeSubprocess, probe_subprocess};-use agent_client_protocol::{AcpAgent, AcpAgentConfig, Client, ConnectTo};+use crate::outbound::acp_process::AcpProcess;+use agent_client_protocol::{Client, ConnectTo};use agent_runtime_protocol::domain::connection::{ConnectionError, ModelProbeHandler, RuntimeChannel, RuntimeConnection,};@@ -39,7 +40,8 @@ pub async fn bridge(};let (mut runtime, acp) = RuntimeConnection::connect_with_model_probe_handler(channel, probes);- let agent = AcpAgent::new(AcpAgentConfig::new(&harness.command).args(harness.args.clone()))+ let agent = AcpProcess::new(&harness.command, harness.args.clone(), cwd)+ .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| {@@ -69,6 +71,7 @@ fn probe_process(harness: &Harness, cwd: &Path) -> ProbeSubprocess {command: harness.command.clone().into(),args: harness.args.clone(),cwd: cwd.to_owned(),+ env: harness.env.clone(),}}@@ -90,10 +93,6 @@ impl ModelProbeHandler for HarnessModelProbes {fn safe_probe_error(error: ProbeError) -> String {match error {ProbeError::Timeout(_) => "the ACP model probe timed out".to_owned(),- #[cfg(not(unix))]- ProbeError::UnsupportedWorkingDirectory => {- "the ACP model probe cannot apply the configured working directory".to_owned()- }ProbeError::Protocol(_) => "the ACP model probe protocol failed".to_owned(),ProbeError::Process(_) => "the ACP model probe process failed".to_owned(),}diff --git a/crates/coding_agent_worker/src/harness/test.rs b/crates/coding_agent_worker/src/harness/test.rsindex e664ba8a2a..da744a7a6a 100644--- a/crates/coding_agent_worker/src/harness/test.rs+++ b/crates/coding_agent_worker/src/harness/test.rs@@ -7,6 +7,7 @@ fn harness(command: &str) -> Harness {Harness {command: command.to_owned(),args: Vec::new(),+ env: Default::default(),}}@@ -78,6 +79,7 @@ async fn model_probe_process_failures_are_safely_redacted() {command: "macro-no-such-harness-binary".into(),args: vec!["secret-argument".to_owned()],cwd: "/".into(),+ env: Default::default(),},};diff --git a/crates/coding_agent_worker/src/main.rs b/crates/coding_agent_worker/src/main.rsindex 5295d21302..7e5a8dff01 100644--- a/crates/coding_agent_worker/src/main.rs+++ b/crates/coding_agent_worker/src/main.rs@@ -27,8 +27,6 @@ mod tui;use clap::Parser;use std::process::ExitCode;-use crate::daemon::absolute_config_path;-/// Serve a harness's agent sessions inside the control panel: registration,/// bound agents, live sessions, config editing, pairing, removal, and logs -/// one process.@@ -57,13 +55,11 @@ async fn main() -> ExitCode {}};}- // The daemon chdirs into the workspace, so the config path must stop- // being relative before anything re-reads or rewrites it.- let config_path = absolute_config_path(std::path::Path::new("macrod.toml"));+ let config_path = std::path::Path::new("macrod.toml");// The TUI owns the terminal, so its logs go to a ring buffer it renders.let logs = tui::LogBuffer::install();- match tui::run(&config_path, logs).await {+ match tui::run(config_path, logs).await {Ok(()) => ExitCode::SUCCESS,Err(error) => {// The ring buffer dies with the process and the terminal isdiff --git a/crates/coding_agent_worker/src/outbound/acp_probe.rs b/crates/coding_agent_worker/src/outbound/acp_probe.rsindex 7e422f222e..e8f7f2af2c 100644--- a/crates/coding_agent_worker/src/outbound/acp_probe.rs+++ b/crates/coding_agent_worker/src/outbound/acp_probe.rs@@ -1,5 +1,6 @@//! Prompt-free inspection of a configured ACP subprocess.+use std::collections::BTreeMap;use std::path::{Path, PathBuf};use std::time::Duration;@@ -7,7 +8,9 @@ use agent_client_protocol::schema::ProtocolVersion;use agent_client_protocol::schema::v1::{InitializeRequest, NewSessionRequest, SessionConfigOption,};-use agent_client_protocol::{AcpAgent, AcpAgentConfig, Agent, Channel, Client, ConnectionTo};+use agent_client_protocol::{Agent, Channel, Client, ConnectionTo};++use crate::outbound::acp_process::AcpProcess;#[cfg(test)]mod test;@@ -21,6 +24,9 @@ pub(crate) struct ProbeSubprocess {pub(crate) args: Vec<String>,/// Directory in which the executable runs.pub(crate) cwd: PathBuf,+ /// Environment added on top of this process's own: the same variables+ /// the bridge applies, so the probe inspects the harness that will run.+ pub(crate) env: BTreeMap<String, String>,}/// A failure to discover an ACP agent's session configuration.@@ -36,11 +42,6 @@ pub(crate) enum ProbeError {/// The bounded probe did not complete in time.#[error("ACP model probe timed out after {0:?}")]Timeout(Duration),- /// This platform cannot apply a subprocess working directory while- /// retaining `AcpAgent`'s process-group cleanup.- #[cfg(not(unix))]- #[error("ACP model probe working directories are unsupported on this platform")]- UnsupportedWorkingDirectory,}/// Run `initialize` followed by `session/new` over an already-connected ACP@@ -73,16 +74,13 @@ async fn probe_channel(/// Spawn one configured ACP agent, perform a prompt-free model probe, and/// tear down that exact child connection before returning.-///-/// On Unix the working directory is applied by a small `/bin/sh` wrapper-/// which immediately `exec`s the configured command. The wrapper and agent-/// remain in the process group guarded by [`AcpAgent`].pub(crate) async fn probe_subprocess(process: &ProbeSubprocess,deadline: Duration,) -> Result<Vec<SessionConfigOption>, ProbeError> {let expires = tokio::time::Instant::now() + deadline;- let agent = subprocess_agent(process)?;+ let agent = AcpProcess::new(&process.command, process.args.clone(), &process.cwd)+ .envs(process.env.clone());let (channel, connection) =agent_client_protocol::ConnectTo::<Client>::into_channel_and_future(agent);let mut connection = std::pin::pin!(connection);@@ -98,8 +96,8 @@ pub(crate) async fn probe_subprocess(result = probe => {if matches!(result, Err(ProbeError::Protocol(_))) {// Stdio can close before the child-exit monitor resolves. Let- // the SDK finish shutdown and collect the exit status before- // classifying the failure, within the original probe deadline.+ // the supervisor finish shutdown and collect the exit status+ // before classifying the failure, within the original deadline.if let Ok(Err(error)) = tokio::time::timeout_at(expires, connection).await {return Err(ProbeError::Process(error.to_string()));}@@ -108,24 +106,3 @@ pub(crate) async fn probe_subprocess(},}}--#[cfg(unix)]-fn subprocess_agent(process: &ProbeSubprocess) -> Result<AcpAgent, ProbeError> {- // `$0` is a label, `$1` is cwd, and the remaining positional arguments- // are the configured command and its arguments. No configured value is- // interpolated into shell source.- let mut args = vec![- "-c".to_owned(),- "cd -- \"$1\" && shift && exec \"$@\"".to_owned(),- "acp-model-probe".to_owned(),- process.cwd.to_string_lossy().into_owned(),- process.command.to_string_lossy().into_owned(),- ];- args.extend(process.args.iter().cloned());- Ok(AcpAgent::new(AcpAgentConfig::new("/bin/sh").args(args)))-}--#[cfg(not(unix))]-fn subprocess_agent(_process: &ProbeSubprocess) -> Result<AcpAgent, ProbeError> {- Err(ProbeError::UnsupportedWorkingDirectory)-}diff --git a/crates/coding_agent_worker/src/outbound/acp_probe/test.rs b/crates/coding_agent_worker/src/outbound/acp_probe/test.rsindex a40da30ddf..bf8c927215 100644--- a/crates/coding_agent_worker/src/outbound/acp_probe/test.rs+++ b/crates/coding_agent_worker/src/outbound/acp_probe/test.rs@@ -68,7 +68,6 @@ async fn connected_probe_is_bounded() {assert!(matches!(error, ProbeError::Timeout(_)));}-#[cfg(unix)]#[tokio::test]async fn subprocess_probe_uses_configured_command_arguments_and_cwd() {let cwd = tempfile::tempdir().expect("temporary cwd");@@ -94,6 +93,7 @@ sys.stdin.read()command: "python3".into(),args: vec!["-c".to_owned(), script.to_owned(), "argument".to_owned()],cwd: cwd.path().to_owned(),+ env: Default::default(),};let options = probe_subprocess(&process, Duration::from_secs(2))@@ -120,6 +120,7 @@ async fn subprocess_exit_after_stdio_closes_is_a_process_failure() {"exec 1>&-; sleep 0.05; exit 127".to_owned(),],cwd: "/".into(),+ env: Default::default(),};let error = probe_subprocess(&process, Duration::from_secs(2))diff --git a/crates/coding_agent_worker/src/outbound/acp_process.rs b/crates/coding_agent_worker/src/outbound/acp_process.rsnew file mode 100644index 0000000000..7f55b7b87c--- /dev/null+++ b/crates/coding_agent_worker/src/outbound/acp_process.rs@@ -0,0 +1,649 @@+//! Spawning and supervising the ACP child process.+//!+//! This is a local port of the SDK's `AcpAgent` (`agent-client-protocol`,+//! `src/acp_agent.rs`, at the rev pinned in the workspace `Cargo.toml`). It+//! exists because `AcpAgentConfig` is exactly `{command, args, env}` and the+//! SDK's spawn path never calls `Command::current_dir`, so the only ways to+//! give the child a working directory were mutating the daemon's own cwd or a+//! `/bin/sh -c 'cd …'` wrapper. Here the daemon owns the+//! `std::process::Command`, sets `current_dir` and the process group directly,+//! and hands the pipes to the SDK's public [`Lines`] transport - the same seam+//! `AcpAgent` itself connects through. `ByteStreams` is not usable here: it+//! wraps the line layer internally, and the debug tap and the stdout-EOF+//! signal both hook individual lines.+//!+//! Everything other than the spawn is kept behaviour-for-behaviour with+//! `AcpAgent::connect_to`, and must be re-read against it whenever the SDK+//! pin moves:+//! - process-group kill on drop ([`ChildGuard`]), created before the first poll+//! so cancelling the connection early still tears the group down;+//! - continuous stderr draining with a bounded tail ([`StderrTail`]) that is+//! reported together with a nonzero exit status;+//! - the per-line debug tap on stdin, stdout and stderr;+//! - the stdout-EOF signal that bounds a final stdin write once the child has+//! half-closed stdout ([`write_line_with_shutdown_timeout`]);+//! - the grace periods around protocol shutdown and child exit.+//!+//! Deliberately not ported: the Windows `CREATE_NO_WINDOW` creation flag.+//! `macrod` is itself a console program, so a console child inherits its+//! console rather than opening a new one.+//!+//! If the SDK ever grows a working-directory option on `AcpAgentConfig`,+//! delete this module and go back to `AcpAgent`.++use std::collections::BTreeMap;+use std::collections::VecDeque;+use std::path::PathBuf;+use std::pin::pin;+use std::sync::Arc;+use std::time::Duration;++use agent_client_protocol::util::internal_error;+use agent_client_protocol::{Agent, Client, ConnectTo, Error, LineDirection, Lines};+use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout};+use tokio_util::compat::{TokioAsyncReadCompatExt as _, TokioAsyncWriteCompatExt as _};++#[cfg(test)]+mod test;++type DebugCallback = Arc<dyn Fn(&str, LineDirection) + Send + Sync + 'static>;++const STDERR_CAPTURE_LIMIT: usize = 64 * 1024;+const STDERR_READ_BUFFER_SIZE: usize = 8 * 1024;+const STDERR_LINE_TRUNCATION_MARKER: &str = "… [stderr line truncated]";+const SHUTDOWN_GRACE_PERIOD: Duration = Duration::from_secs(1);++/// An ACP agent launched as a child of this daemon, in a chosen directory.+///+/// The child inherits the daemon's environment. Connecting it (via+/// [`ConnectTo`]) spawns the process and supervises it for the life of the+/// connection.+pub(crate) struct AcpProcess {+ command: PathBuf,+ args: Vec<String>,+ cwd: PathBuf,+ env: BTreeMap<String, String>,+ debug_callback: Option<DebugCallback>,+}++impl AcpProcess {+ pub(crate) fn new(+ command: impl Into<PathBuf>,+ args: Vec<String>,+ cwd: impl Into<PathBuf>,+ ) -> Self {+ Self {+ command: command.into(),+ args,+ cwd: cwd.into(),+ env: BTreeMap::new(),+ debug_callback: None,+ }+ }++ /// Add environment variables on top of the ones this process already has.+ ///+ /// The npm ACP adapters bundle their own copy of the CLI they wrap and+ /// take an absolute path to the one to run instead - `CODEX_PATH`,+ /// `CLAUDE_CODE_EXECUTABLE` - so the bridge and the model probe must be+ /// given the same variables or they inspect one CLI and run another.+ #[must_use]+ pub(crate) fn envs(mut self, env: impl IntoIterator<Item = (String, String)>) -> Self {+ self.env.extend(env);+ self+ }++ /// Observe every line crossing the child's stdin and stdout, plus its+ /// stderr. Exceptionally long stderr lines are truncated.+ #[must_use]+ pub(crate) fn with_debug<Callback>(mut self, callback: Callback) -> Self+ where+ Callback: Fn(&str, LineDirection) + Send + Sync + 'static,+ {+ self.debug_callback = Some(Arc::new(callback));+ self+ }++ fn spawn(&self) -> Result<SpawnedChild, Error> {+ let mut command = std::process::Command::new(&self.command);+ command+ .args(&self.args)+ .current_dir(&self.cwd)+ .envs(&self.env)+ .stdin(std::process::Stdio::piped())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped());+ #[cfg(unix)]+ {+ use std::os::unix::process::CommandExt as _;++ // The child leads its own process group so `ChildGuard` can kill+ // the whole tree. Agents commonly sit behind wrapper launchers+ // (`npx …`, `uvx …`): killing only the immediate child orphans the+ // real agent, which re-parents to pid 1 and does not reliably exit+ // on stdin EOF.+ command.process_group(0);+ }++ let mut child = tokio::process::Command::from(command)+ .spawn()+ .map_err(|error| internal_error(format!("Failed to spawn process: {error}")))?;+ let stdin = child+ .stdin+ .take()+ .ok_or_else(|| internal_error("Failed to open stdin"))?;+ let stdout = child+ .stdout+ .take()+ .ok_or_else(|| internal_error("Failed to open stdout"))?;+ let stderr = child+ .stderr+ .take()+ .ok_or_else(|| internal_error("Failed to open stderr"))?;++ Ok(SpawnedChild {+ stdin,+ stdout,+ stderr,+ guard: ChildGuard::new(child),+ })+ }+}++struct SpawnedChild {+ stdin: ChildStdin,+ stdout: ChildStdout,+ stderr: ChildStderr,+ guard: ChildGuard,+}++/// Kills the child - and, on Unix, its whole process group - when dropped.+struct ChildGuard {+ child: Child,+ /// Captured at spawn: tokio forgets the pid once the child is reaped, and+ /// the group kill must still reach descendants a wrapper left behind.+ #[cfg(unix)]+ process_group: Option<rustix::process::Pid>,+}++impl ChildGuard {+ fn new(child: Child) -> Self {+ #[cfg(unix)]+ let process_group = child+ .id()+ .and_then(|id| rustix::process::Pid::from_raw(id.cast_signed()));+ Self {+ child,+ #[cfg(unix)]+ process_group,+ }+ }++ async fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {+ self.child.wait().await+ }++ fn terminate(&mut self) {+ // SIGKILL the group first: it reaches grandchildren spawned by wrapper+ // launchers, and also the case where the direct child already exited+ // but its wrapper left the real agent running. An error (`ESRCH`)+ // just means the group is already gone.+ #[cfg(unix)]+ if let Some(process_group) = self.process_group {+ let _result =+ rustix::process::kill_process_group(process_group, rustix::process::Signal::KILL);+ }+ // Fallback for platforms without group semantics, and a no-op double+ // tap on Unix.+ drop(self.child.start_kill());+ }+}++impl Drop for ChildGuard {+ fn drop(&mut self) {+ self.terminate();+ }+}++#[derive(Default)]+struct StderrTail {+ bytes: VecDeque<u8>,+ truncated: bool,+}++impl StderrTail {+ fn push(&mut self, bytes: &[u8]) {+ if bytes.len() >= STDERR_CAPTURE_LIMIT {+ self.truncated |= !self.bytes.is_empty() || bytes.len() > STDERR_CAPTURE_LIMIT;+ self.bytes.clear();+ self.bytes+ .extend(bytes[bytes.len() - STDERR_CAPTURE_LIMIT..].iter().copied());+ return;+ }++ let overflow = self+ .bytes+ .len()+ .saturating_add(bytes.len())+ .saturating_sub(STDERR_CAPTURE_LIMIT);+ if overflow > 0 {+ self.truncated = true;+ drop(self.bytes.drain(..overflow));+ }+ self.bytes.extend(bytes.iter().copied());+ }++ fn into_string(mut self) -> String {+ let truncated = self.truncated;+ let stderr = String::from_utf8_lossy(self.bytes.make_contiguous());+ if truncated {+ format!("[stderr truncated; showing last {STDERR_CAPTURE_LIMIT} bytes]\n{stderr}")+ } else {+ stderr.into_owned()+ }+ }+}++#[derive(Default)]+struct StderrDebugLines {+ current: Vec<u8>,+ truncated: bool,+ pending_carriage_return: bool,+}++impl StderrDebugLines {+ fn push(&mut self, bytes: &[u8], callback: &DebugCallback) {+ for &byte in bytes {+ if self.pending_carriage_return {+ if byte == b'\n' {+ self.pending_carriage_return = false;+ self.emit(callback);+ continue;+ }++ self.push_byte(b'\r');+ self.pending_carriage_return = false;+ }++ match byte {+ b'\r' => self.pending_carriage_return = true,+ b'\n' => self.emit(callback),+ byte => self.push_byte(byte),+ }+ }+ }++ fn finish(&mut self, callback: &DebugCallback) {+ if self.pending_carriage_return {+ self.push_byte(b'\r');+ self.pending_carriage_return = false;+ }+ if !self.current.is_empty() || self.truncated {+ self.emit(callback);+ }+ }++ fn push_byte(&mut self, byte: u8) {+ if self.current.len() < STDERR_CAPTURE_LIMIT {+ self.current.push(byte);+ } else {+ self.truncated = true;+ }+ }++ fn emit(&mut self, callback: &DebugCallback) {+ let line = String::from_utf8_lossy(&self.current);++ if self.truncated {+ let mut line = line.into_owned();+ line.push_str(STDERR_LINE_TRUNCATION_MARKER);+ callback(&line, LineDirection::Stderr);+ } else {+ callback(line.as_ref(), LineDirection::Stderr);+ }++ self.current.clear();+ self.truncated = false;+ }+}++struct StderrDrainResult {+ captured: String,+ read_error: Option<std::io::Error>,+}++/// Read stderr to EOF. Never leaving the pipe unread matters: a full pipe+/// buffer blocks the child.+async fn drain_stderr(+ mut stderr: impl futures::AsyncRead + Unpin,+ debug_callback: Option<DebugCallback>,+) -> StderrDrainResult {+ use futures::AsyncReadExt as _;++ let mut tail = StderrTail::default();+ let mut debug_lines = debug_callback.as_ref().map(|_| StderrDebugLines::default());+ let mut buffer = [0; STDERR_READ_BUFFER_SIZE];++ let read_error = loop {+ match stderr.read(&mut buffer).await {+ Ok(0) => break None,+ Ok(read) => {+ let bytes = &buffer[..read];+ tail.push(bytes);+ if let (Some(lines), Some(callback)) =+ (debug_lines.as_mut(), debug_callback.as_ref())+ {+ lines.push(bytes, callback);+ }+ }+ Err(error) => break Some(error),+ }+ };++ if let (Some(lines), Some(callback)) = (debug_lines.as_mut(), debug_callback.as_ref()) {+ lines.finish(callback);+ }++ StderrDrainResult {+ captured: tail.into_string(),+ read_error,+ }+}++struct ExitedChild {+ guard: ChildGuard,+ status: std::process::ExitStatus,+ stderr_rx: futures::channel::oneshot::Receiver<String>,+}++/// Wait for the direct child while retaining its process-group guard and+/// stderr receiver for exit reporting.+async fn wait_for_child(+ mut guard: ChildGuard,+ stderr_rx: futures::channel::oneshot::Receiver<String>,+) -> Result<ExitedChild, Error> {+ let status = guard+ .wait()+ .await+ .map_err(|error| internal_error(format!("Failed to wait for process: {error}")))?;++ Ok(ExitedChild {+ guard,+ status,+ stderr_rx,+ })+}++/// Report an observed child exit, including the bounded stderr tail for a+/// nonzero status.+async fn finish_child_exit(child: ExitedChild) -> Result<(), Error> {+ let ExitedChild {+ mut guard,+ status,+ stderr_rx,+ } = child;++ // A launcher may exit while a descendant remains alive holding inherited+ // stdio. Terminate the rest of the group before waiting for stderr EOF.+ guard.terminate();++ if status.success() {+ return Ok(());+ }++ let grace = pin!(tokio::time::sleep(SHUTDOWN_GRACE_PERIOD));+ let stderr = match futures::future::select(stderr_rx, grace).await {+ futures::future::Either::Left((stderr, _)) => stderr.unwrap_or_default(),+ futures::future::Either::Right((_, stderr_rx)) => {+ tracing::debug!(+ grace = ?SHUTDOWN_GRACE_PERIOD,+ "agent stderr remained open after process exit; reporting status without it"+ );+ drop(stderr_rx);+ String::new()+ }+ };++ let message = if stderr.is_empty() {+ format!("Process exited with {status}")+ } else {+ format!("Process exited with {status}: {stderr}")+ };++ Err(internal_error(message))+}++async fn await_protocol_shutdown_after_successful_child_exit<Protocol>(+ protocol_future: Protocol,+ grace: Duration,+) -> Result<(), Error>+where+ Protocol: Future<Output = Result<(), Error>> + Unpin,+{+ let timer = pin!(tokio::time::sleep(grace));+ match futures::future::select(protocol_future, timer).await {+ futures::future::Either::Left((result, _)) => result,+ futures::future::Either::Right((_, protocol_future)) => {+ tracing::debug!(+ ?grace,+ "protocol transport remained open after successful agent process exit; stopping it"+ );+ drop(protocol_future);+ Ok(())+ }+ }+}++async fn write_line<Writer>(writer: &mut Writer, line: String) -> std::io::Result<()>+where+ Writer: futures::AsyncWrite + Unpin + ?Sized,+{+ use futures::AsyncWriteExt as _;++ let mut bytes = line.into_bytes();+ bytes.push(b'\n');+ writer.write_all(&bytes).await?;+ writer.flush().await+}++async fn write_line_with_shutdown_timeout<Writer>(+ writer: &mut Writer,+ line: String,+ stdout_eof_rx: &mut Option<futures::channel::oneshot::Receiver<()>>,+ stdout_eof_seen: &mut bool,+ grace: Duration,+) -> std::io::Result<()>+where+ Writer: futures::AsyncWrite + Unpin + ?Sized,+{+ let write = Box::pin(write_line(writer, line));++ if *stdout_eof_seen {+ return await_write_during_shutdown(write, grace).await;+ }++ let Some(stdout_eof) = stdout_eof_rx.as_mut() else {+ return write.await;+ };++ match futures::future::select(write, stdout_eof).await {+ futures::future::Either::Left((result, _)) => result,+ futures::future::Either::Right((stdout_eof, write)) => {+ *stdout_eof_rx = None;+ if stdout_eof.is_err() {+ // Dropping the incoming stream cancels the signal. Only an+ // explicit send represents a clean EOF.+ return write.await;+ }++ *stdout_eof_seen = true;+ await_write_during_shutdown(write, grace).await+ }+ }+}++async fn await_write_during_shutdown<Write>(write: Write, grace: Duration) -> std::io::Result<()>+where+ Write: Future<Output = std::io::Result<()>> + Unpin,+{+ let timer = pin!(tokio::time::sleep(grace));+ match futures::future::select(write, timer).await {+ futures::future::Either::Left((result, _)) => result,+ futures::future::Either::Right((_, write)) => {+ tracing::debug!(+ ?grace,+ "pending protocol output did not drain after agent stdout closed"+ );+ drop(write);+ Err(std::io::Error::new(+ std::io::ErrorKind::TimedOut,+ format!(+ "Agent closed its protocol output but pending protocol output did not drain within {grace:?}"+ ),+ ))+ }+ }+}++impl ConnectTo<Client> for AcpProcess {+ async fn connect_to(self, client: impl ConnectTo<Agent>) -> Result<(), Error> {+ use futures::io::BufReader;+ use futures::{AsyncBufReadExt as _, StreamExt as _};++ let SpawnedChild {+ stdin,+ stdout,+ stderr,+ guard,+ } = self.spawn()?;++ let (stderr_tx, stderr_rx) = futures::channel::oneshot::channel::<String>();++ // Raced against the protocol below, so it runs on this task.+ let debug_callback = self.debug_callback.clone();+ let stderr_future = async move {+ let StderrDrainResult {+ captured,+ read_error,+ } = drain_stderr(stderr.compat(), debug_callback).await;+ drop(stderr_tx.send(captured));++ if let Some(error) = read_error {+ tracing::warn!(+ ?error,+ "failed to read process stderr; stderr will no longer be captured"+ );+ }+ };++ // The guard already exists, so cancelling this connection before the+ // monitor is first polled still terminates the whole process group.+ let child_wait = wait_for_child(guard, stderr_rx);++ let incoming_lines: std::pin::Pin<+ Box<dyn futures::Stream<Item = std::io::Result<String>> + Send>,+ > = if let Some(callback) = self.debug_callback.clone() {+ Box::pin(+ BufReader::new(stdout.compat())+ .lines()+ .inspect(move |result| {+ if let Ok(line) = result {+ callback(line, LineDirection::Stdout);+ }+ }),+ )+ } else {+ Box::pin(BufReader::new(stdout.compat()).lines())+ };++ // The JSON-RPC transport keeps polling stdout while it drains stdin.+ // Signal physical EOF so a child that half-closes stdout and stops+ // reading cannot hold a final write open forever. Dropping this stream+ // merely cancels the signal and is not treated as EOF.+ let (stdout_eof_tx, stdout_eof_rx) = futures::channel::oneshot::channel();+ let mut stdout_eof_tx = Some(stdout_eof_tx);+ let mut incoming_lines = incoming_lines;+ let incoming_lines = Box::pin(futures::stream::poll_fn(move |context| {+ let next = incoming_lines.as_mut().poll_next(context);+ if matches!(next, std::task::Poll::Ready(None))+ && let Some(stdout_eof_tx) = stdout_eof_tx.take()+ {+ let _ = stdout_eof_tx.send(());+ }+ next+ }));++ let outgoing_sink: std::pin::Pin<+ Box<dyn futures::Sink<String, Error = std::io::Error> + Send>,+ > = Box::pin(futures::sink::unfold(+ (+ stdin.compat_write(),+ self.debug_callback.clone(),+ Some(stdout_eof_rx),+ false,+ ),+ async move |(mut writer, callback, mut stdout_eof_rx, mut stdout_eof_seen),+ line: String| {+ if let Some(callback) = callback.as_ref() {+ callback(&line, LineDirection::Stdin);+ }+ write_line_with_shutdown_timeout(+ &mut writer,+ line,+ &mut stdout_eof_rx,+ &mut stdout_eof_seen,+ SHUTDOWN_GRACE_PERIOD,+ )+ .await?;+ Ok::<_, std::io::Error>((writer, callback, stdout_eof_rx, stdout_eof_seen))+ },+ ));++ let protocol_future =+ ConnectTo::<Client>::connect_to(Lines::new(outgoing_sink, incoming_lines), client);++ let stderr_future = pin!(stderr_future);+ let protocol_future = Box::pin(protocol_future);+ let child_wait = Box::pin(child_wait);++ // Errors stop the connection immediately. After protocol shutdown+ // succeeds, the child gets a bounded grace period so delayed failures+ // remain observable without a non-exiting launcher hanging shutdown.+ let main_race = async {+ match futures::future::select(protocol_future, child_wait).await {+ futures::future::Either::Left((result, child_wait)) => {+ result?;+ let grace = pin!(tokio::time::sleep(SHUTDOWN_GRACE_PERIOD));+ match futures::future::select(child_wait, grace).await {+ futures::future::Either::Left((child, _)) => {+ finish_child_exit(child?).await+ }+ futures::future::Either::Right((_, child_wait)) => {+ tracing::debug!(+ grace = ?SHUTDOWN_GRACE_PERIOD,+ "agent process did not exit after protocol shutdown; terminating it"+ );+ drop(child_wait);+ Ok(())+ }+ }+ }+ futures::future::Either::Right((child, protocol_future)) => {+ finish_child_exit(child?).await?;+ await_protocol_shutdown_after_successful_child_exit(+ protocol_future,+ SHUTDOWN_GRACE_PERIOD,+ )+ .await+ }+ }+ };++ // Once the main race completes, stderr is no longer needed.+ let main_race = pin!(main_race);+ match futures::future::select(main_race, stderr_future).await {+ futures::future::Either::Left((result, _)) => result,+ futures::future::Either::Right(((), main_race)) => main_race.await,+ }+ }+}diff --git a/crates/coding_agent_worker/src/outbound/acp_process/test.rs b/crates/coding_agent_worker/src/outbound/acp_process/test.rsnew file mode 100644index 0000000000..820b2ff168--- /dev/null+++ b/crates/coding_agent_worker/src/outbound/acp_process/test.rs@@ -0,0 +1,551 @@+//! Ported from the SDK's `acp_agent.rs` tests so the behaviours this module+//! duplicates stay pinned, plus the working-directory guarantee that is the+//! reason the module exists.++use super::*;+use std::sync::Mutex;+use std::sync::atomic::{AtomicUsize, Ordering};++fn recording_debug_callback() -> (DebugCallback, Arc<Mutex<Vec<String>>>) {+ let lines = Arc::new(Mutex::new(Vec::new()));+ let recorded = lines.clone();+ let callback = Arc::new(move |line: &str, direction| {+ assert_eq!(direction, LineDirection::Stderr);+ recorded.lock().unwrap().push(line.to_owned());+ });+ (callback, lines)+}++fn error_detail(error: &Error) -> String {+ error+ .data+ .as_ref()+ .map(serde_json::Value::to_string)+ .unwrap_or_default()+}++#[test]+fn stderr_tail_keeps_last_bytes() {+ let initial = vec![b'a'; STDERR_CAPTURE_LIMIT];++ let mut exact = StderrTail::default();+ exact.push(&initial);+ assert_eq!(exact.into_string(), String::from_utf8(initial).unwrap());++ let mut truncated = StderrTail::default();+ truncated.push(&vec![b'a'; STDERR_CAPTURE_LIMIT]);+ truncated.push(b"the end");+ let captured = truncated.into_string();+ let (notice, tail) = captured.split_once('\n').unwrap();+ assert_eq!(+ notice,+ format!("[stderr truncated; showing last {STDERR_CAPTURE_LIMIT} bytes]")+ );+ assert_eq!(tail.len(), STDERR_CAPTURE_LIMIT);+ assert!(tail.ends_with("the end"));+}++#[test]+fn stderr_debug_callback_preserves_lines() {+ let (callback, recorded) = recording_debug_callback();+ let mut lines = StderrDebugLines::default();++ lines.push(b"one\r", &callback);+ lines.push(b"\n\ntw", &callback);+ lines.push(b"o\nbad\xff\nlast\r", &callback);+ lines.finish(&callback);++ assert_eq!(+ *recorded.lock().unwrap(),+ ["one", "", "two", "bad\u{fffd}", "last\r"]+ );+}++#[test]+fn stderr_debug_callback_truncates_oversized_lines() {+ let (callback, recorded) = recording_debug_callback();+ let mut lines = StderrDebugLines::default();+ let exact = vec![b'y'; STDERR_CAPTURE_LIMIT];+ let oversized = vec![b'x'; STDERR_CAPTURE_LIMIT + 1];++ lines.push(&exact, &callback);+ lines.push(b"\r\n", &callback);+ lines.push(&oversized, &callback);+ assert_eq!(lines.current.len(), STDERR_CAPTURE_LIMIT);+ assert!(lines.truncated);+ lines.push(b"\nnext\n", &callback);++ let recorded = recorded.lock().unwrap();+ assert_eq!(recorded.len(), 3);+ assert_eq!(recorded[0].len(), STDERR_CAPTURE_LIMIT);+ assert!(!recorded[0].ends_with(STDERR_LINE_TRUNCATION_MARKER));+ assert_eq!(+ recorded[1].len(),+ STDERR_CAPTURE_LIMIT + STDERR_LINE_TRUNCATION_MARKER.len()+ );+ assert!(recorded[1].ends_with(STDERR_LINE_TRUNCATION_MARKER));+ assert_eq!(recorded[2], "next");+}++struct ErrorAfterData {+ polls: Arc<AtomicUsize>,+}++impl futures::AsyncRead for ErrorAfterData {+ fn poll_read(+ self: std::pin::Pin<&mut Self>,+ _context: &mut std::task::Context<'_>,+ buffer: &mut [u8],+ ) -> std::task::Poll<std::io::Result<usize>> {+ match self.polls.fetch_add(1, Ordering::SeqCst) {+ 0 => {+ buffer[..7].copy_from_slice(b"partial");+ std::task::Poll::Ready(Ok(7))+ }+ 1 => std::task::Poll::Ready(Err(std::io::Error::other("read failed"))),+ _ => panic!("stderr reader was polled again after an error"),+ }+ }+}++#[tokio::test]+async fn stderr_drain_stops_after_read_error() {+ let polls = Arc::new(AtomicUsize::new(0));+ let (callback, recorded) = recording_debug_callback();++ let result = drain_stderr(+ ErrorAfterData {+ polls: polls.clone(),+ },+ Some(callback),+ )+ .await;++ assert_eq!(result.captured, "partial");+ assert_eq!(result.read_error.unwrap().to_string(), "read failed");+ assert_eq!(polls.load(Ordering::SeqCst), 2);+ assert_eq!(*recorded.lock().unwrap(), ["partial"]);+}++#[tokio::test]+async fn successful_child_exit_bounds_protocol_shutdown_cleanly() {+ let grace = Duration::from_millis(10);+ tokio::time::timeout(+ Duration::from_secs(1),+ await_protocol_shutdown_after_successful_child_exit(+ futures::future::pending::<Result<(), Error>>(),+ grace,+ ),+ )+ .await+ .expect("protocol shutdown wait should be bounded")+ .expect("a successful child exit should stop the pending protocol cleanly");+}++#[tokio::test]+async fn successful_child_exit_preserves_ready_protocol_error() {+ let error = await_protocol_shutdown_after_successful_child_exit(+ futures::future::ready(Err(internal_error("protocol failed during shutdown"))),+ Duration::from_secs(1),+ )+ .await+ .expect_err("a ready protocol error should remain authoritative");++ assert!(+ error_detail(&error).contains("protocol failed during shutdown"),+ "unexpected protocol error: {error:?}"+ );+}++#[cfg(unix)]+fn shell(script: &str, cwd: impl Into<PathBuf>) -> AcpProcess {+ AcpProcess::new("/bin/sh", vec!["-c".to_owned(), script.to_owned()], cwd)+}++#[cfg(unix)]+#[tokio::test]+async fn child_sees_the_configured_environment() {+ // The npm ACP adapters are pointed at an already-installed CLI through+ // `CODEX_PATH` / `CLAUDE_CODE_EXECUTABLE`; if those do not reach the child+ // the adapter silently runs its own bundled copy instead.+ let process = shell("printf %s \"$MACROD_TEST_CLI_PATH\" >&2; exit 17", "/").envs([(+ "MACROD_TEST_CLI_PATH".to_owned(),+ "/nix/store/probe-and-bridge-agree".to_owned(),+ )]);++ let error = tokio::time::timeout(Duration::from_secs(5), Client.builder().connect_to(process))+ .await+ .expect("connection should finish after the child exits")+ .expect_err("nonzero exit should be reported");++ assert!(+ error_detail(&error).contains("/nix/store/probe-and-bridge-agree"),+ "configured environment should reach the child: {error:?}"+ );+}++#[cfg(unix)]+#[tokio::test]+async fn configured_environment_adds_to_the_inherited_one() {+ // `envs` layers onto this process's environment rather than replacing it:+ // the adapters still need PATH, HOME and the rest to work.+ unsafe { std::env::set_var("MACROD_TEST_INHERITED", "inherited") };+ let process = shell(+ "printf %s \"$MACROD_TEST_INHERITED:$MACROD_TEST_ADDED\" >&2; exit 17",+ "/",+ )+ .envs([("MACROD_TEST_ADDED".to_owned(), "added".to_owned())]);++ let error = tokio::time::timeout(Duration::from_secs(5), Client.builder().connect_to(process))+ .await+ .expect("connection should finish after the child exits")+ .expect_err("nonzero exit should be reported");++ assert!(+ error_detail(&error).contains("inherited:added"),+ "configured environment should add to the inherited one: {error:?}"+ );+}++#[cfg(unix)]+#[tokio::test]+async fn child_runs_in_the_configured_directory() {+ let cwd = tempfile::tempdir().expect("temporary cwd");+ let expected = cwd.path().canonicalize().expect("canonical cwd");+ let process = shell("pwd -P >&2; exit 17", cwd.path());++ let error = tokio::time::timeout(Duration::from_secs(5), Client.builder().connect_to(process))+ .await+ .expect("connection should finish after the child exits")+ .expect_err("nonzero exit should be reported");++ assert!(+ error_detail(&error).contains(&*expected.to_string_lossy()),+ "child should run in the configured directory: {error:?}"+ );+}++#[cfg(unix)]+#[tokio::test]+async fn unspawnable_command_fails_without_touching_the_daemon_directory() {+ let before = std::env::current_dir().expect("daemon cwd");+ let process = shell("exit 0", "/definitely/not/a/directory");++ Client+ .builder()+ .connect_to(process)+ .await+ .expect_err("a missing working directory must fail the spawn");++ assert_eq!(std::env::current_dir().expect("daemon cwd"), before);+}++#[cfg(unix)]+#[tokio::test]+async fn large_unterminated_stderr_is_fully_drained() {+ let process = shell(+ r#"i=0; while [ "$i" -lt 4096 ]; do printf '%01024d' 0; i=$((i + 1)); done >&2; printf ACP_END >&2; exit 17"#,+ "/",+ );+ let SpawnedChild {+ stdin,+ stdout,+ stderr,+ mut guard,+ } = process.spawn().unwrap();+ drop(stdin);+ drop(stdout);++ let (drained, status) = tokio::time::timeout(Duration::from_secs(10), async {+ futures::join!(drain_stderr(stderr.compat(), None), guard.wait())+ })+ .await+ .expect("stderr drain should not block after its retained tail is full");++ assert_eq!(status.unwrap().code(), Some(17));+ assert!(drained.read_error.is_none());+ let (notice, tail) = drained.captured.split_once('\n').unwrap();+ assert_eq!(+ notice,+ format!("[stderr truncated; showing last {STDERR_CAPTURE_LIMIT} bytes]")+ );+ assert_eq!(tail.len(), STDERR_CAPTURE_LIMIT);+ assert!(tail.ends_with("ACP_END"));+}++#[cfg(unix)]+#[tokio::test]+async fn protocol_eof_still_reports_nonzero_child_exit() {+ let process = shell(+ "exec 1>&-; cat >/dev/null; printf ACP_TEST_FAILURE_AFTER_STDOUT_EOF >&2; exit 17",+ "/",+ );++ let error = tokio::time::timeout(Duration::from_secs(5), Client.builder().connect_to(process))+ .await+ .expect("connection should finish after the child exits")+ .expect_err("nonzero child exit after protocol EOF should be reported");+ let detail = error_detail(&error);++ assert!(+ detail.contains("exit status: 17"),+ "child exit status should be preserved: {error:?}"+ );+ assert!(+ detail.contains("ACP_TEST_FAILURE_AFTER_STDOUT_EOF"),+ "child stderr should be preserved: {error:?}"+ );+}++#[cfg(unix)]+#[tokio::test]+async fn successful_child_exit_does_not_cancel_active_foreground() {+ let process = shell("exit 0", "/");+ let (started_tx, started_rx) = futures::channel::oneshot::channel();+ let (closed_tx, closed_rx) = futures::channel::oneshot::channel();+ let (close_release_tx, close_release_rx) = futures::channel::oneshot::channel();+ let (release_tx, release_rx) = futures::channel::oneshot::channel();+ let connection = tokio::spawn(+ Client+ .builder()+ .on_close(async move |_context| {+ closed_tx+ .send(())+ .map_err(|()| Error::internal_error().data("close observer dropped"))?;+ close_release_rx+ .await+ .map_err(|_| Error::internal_error().data("close callback release dropped"))+ })+ .connect_with(process, async move |_context| {+ started_tx+ .send(())+ .map_err(|()| Error::internal_error().data("foreground observer dropped"))?;+ release_rx+ .await+ .map_err(|_| Error::internal_error().data("foreground release dropped"))+ }),+ );++ tokio::time::timeout(Duration::from_secs(5), started_rx)+ .await+ .expect("foreground should start")+ .expect("foreground should report that it started");++ tokio::time::timeout(Duration::from_secs(5), closed_rx)+ .await+ .expect("successful child exit should close the protocol transport")+ .expect("successful child exit should invoke close callbacks");++ tokio::time::sleep(SHUTDOWN_GRACE_PERIOD + Duration::from_millis(250)).await;+ assert!(+ !connection.is_finished(),+ "successful child exit canceled active cleanup"+ );++ close_release_tx+ .send(())+ .expect("clean child exit should preserve close callbacks");+ release_tx+ .send(())+ .expect("clean child exit should preserve the foreground");+ tokio::time::timeout(Duration::from_secs(5), connection)+ .await+ .expect("released foreground should finish")+ .expect("connection task should not panic")+ .expect("successful child exit should remain a clean EOF");+}++#[cfg(unix)]+struct KillOnDrop(Option<rustix::process::Pid>);++#[cfg(unix)]+impl KillOnDrop {+ fn disarm(&mut self) {+ self.0 = None;+ }+}++#[cfg(unix)]+impl Drop for KillOnDrop {+ fn drop(&mut self) {+ if let Some(pid) = self.0 {+ let _result = rustix::process::kill_process(pid, rustix::process::Signal::KILL);+ }+ }+}++/// A shell wrapper that reports a descendant pid over stderr, the way `npx`+/// fronts the real agent.+#[cfg(unix)]+fn wrapper_process(script: &str) -> (AcpProcess, tokio::sync::mpsc::UnboundedReceiver<String>) {+ let (pid_tx, pid_rx) = tokio::sync::mpsc::unbounded_channel();+ let process = shell(script, "/").with_debug(move |line, direction| {+ if direction == LineDirection::Stderr {+ drop(pid_tx.send(line.to_owned()));+ }+ });+ (process, pid_rx)+}++#[cfg(unix)]+fn process_is_running(pid: rustix::process::Pid) -> bool {+ if rustix::process::test_kill_process(pid).is_err() {+ return false;+ }+ !is_zombie(pid)+}++/// A killed orphan can remain a zombie under a container PID 1 that does not+/// reap promptly, and a zombie still answers `kill(pid, 0)`.+///+/// Read the state from procfs rather than shelling out to `ps`: CI's container+/// answers `ps -o stat= -p` differently from a developer machine, which made+/// live processes look exited.+#[cfg(all(unix, target_os = "linux"))]+fn is_zombie(pid: rustix::process::Pid) -> bool {+ let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {+ return false;+ };+ // `<pid> (<comm>) <state> ...`, where `comm` may itself contain spaces and+ // parentheses, so the state is the first field after the final `)`.+ stat.rsplit_once(')')+ .and_then(|(_, rest)| rest.split_whitespace().next())+ .is_some_and(|state| state == "Z")+}++#[cfg(all(unix, not(target_os = "linux")))]+fn is_zombie(_pid: rustix::process::Pid) -> bool {+ false+}++#[cfg(unix)]+async fn reported_descendant_pid(+ connection: &mut futures::future::BoxFuture<'static, Result<(), Error>>,+ pid_rx: &mut tokio::sync::mpsc::UnboundedReceiver<String>,+) -> rustix::process::Pid {+ tokio::time::timeout(Duration::from_secs(5), async {+ loop {+ tokio::select! {+ biased;+ line = pid_rx.recv() => {+ let line = line.expect("wrapper stderr should remain open");+ if let Some(pid) = line.strip_prefix("ACP_TEST_CHILD_PID=") {+ let pid = pid.parse::<i32>().expect("valid descendant PID");+ break rustix::process::Pid::from_raw(pid)+ .expect("nonzero descendant PID");+ }+ }+ result = &mut *connection => {+ panic!("agent connection exited before reporting descendant PID: {result:?}");+ }+ }+ }+ })+ .await+ .expect("wrapper should report descendant PID")+}++#[cfg(unix)]+async fn assert_process_exits(pid: rustix::process::Pid) {+ let exited = tokio::time::timeout(Duration::from_secs(5), async {+ while process_is_running(pid) {+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ })+ .await+ .is_ok();+ assert!(exited, "descendant process {pid} remained alive");+}++#[cfg(unix)]+#[tokio::test]+async fn protocol_eof_terminates_a_child_that_does_not_exit() {+ let (process, mut pid_rx) =+ wrapper_process("echo ACP_TEST_CHILD_PID=$$ >&2; exec 1>&-; while :; do sleep 30; done");+ let mut connection: futures::future::BoxFuture<'static, Result<(), Error>> =+ Box::pin(Client.builder().connect_to(process));+ let child_pid = reported_descendant_pid(&mut connection, &mut pid_rx).await;+ let mut cleanup = KillOnDrop(Some(child_pid));++ assert!(process_is_running(child_pid));+ tokio::time::timeout(Duration::from_secs(5), &mut connection)+ .await+ .expect("protocol shutdown should bound its child-exit wait")+ .expect("clean protocol shutdown should terminate a non-exiting child");+ assert_process_exits(child_pid).await;+ cleanup.disarm();+}++#[cfg(unix)]+#[tokio::test]+async fn protocol_eof_bounds_a_blocked_outgoing_drain() {+ let (process, mut pid_rx) = wrapper_process(+ "echo ACP_TEST_CHILD_PID=$$ >&2; exec 1>&-; sleep 30 & child=$!; wait \"$child\"",+ );+ let (channel, mut connection) = ConnectTo::<Client>::into_channel_and_future(process);+ let agent_client_protocol::Channel {+ rx: _incoming,+ tx: outgoing,+ } = channel;++ let response = agent_client_protocol::RawJsonRpcMessage::response(+ agent_client_protocol::schema::v1::RequestId::Number(1),+ Ok(serde_json::json!({ "payload": "x".repeat(4 * 1024 * 1024) })),+ );+ outgoing+ .unbounded_send(agent_client_protocol::TransportFrame::Single(response))+ .expect("response should be accepted before the connection starts");+ outgoing.close_channel();++ let child_pid = reported_descendant_pid(&mut connection, &mut pid_rx).await;+ let mut cleanup = KillOnDrop(Some(child_pid));++ let error = tokio::time::timeout(Duration::from_secs(5), &mut connection)+ .await+ .expect("stdout EOF should bound a blocked outgoing drain")+ .expect_err("an undelivered accepted response must not report success");+ assert!(+ error_detail(&error).contains("pending protocol output did not drain"),+ "the error should identify the blocked outgoing drain: {error:?}"+ );++ assert_process_exits(child_pid).await;+ cleanup.disarm();+}++#[cfg(unix)]+#[tokio::test]+async fn connection_drop_kills_wrapper_descendant() {+ let (process, mut pid_rx) =+ wrapper_process("sleep 30 & child=$!; echo ACP_TEST_CHILD_PID=$child >&2; wait \"$child\"");+ let (_channel, mut connection) = ConnectTo::<Client>::into_channel_and_future(process);+ let descendant_pid = reported_descendant_pid(&mut connection, &mut pid_rx).await;+ let mut cleanup = KillOnDrop(Some(descendant_pid));++ assert!(process_is_running(descendant_pid));+ drop(connection);+ assert_process_exits(descendant_pid).await;+ cleanup.disarm();+}++#[cfg(unix)]+#[tokio::test]+async fn launcher_exit_kills_descendant_before_stderr_wait() {+ let (process, mut pid_rx) = wrapper_process(+ "sh -c 'trap \"\" HUP; exec sleep 30' >/dev/null & child=$!; echo ACP_TEST_CHILD_PID=$child >&2; exit 17",+ );+ let (_channel, mut connection) = ConnectTo::<Client>::into_channel_and_future(process);+ let descendant_pid = reported_descendant_pid(&mut connection, &mut pid_rx).await;+ let mut cleanup = KillOnDrop(Some(descendant_pid));++ let result = tokio::time::timeout(Duration::from_secs(5), &mut connection)+ .await+ .expect("connection should observe the launcher exit");+ let error = result.expect_err("nonzero launcher exit should be an error");+ assert!(+ error_detail(&error).contains("ACP_TEST_CHILD_PID="),+ "launcher stderr should be preserved: {error:?}"+ );+ assert_process_exits(descendant_pid).await;+ cleanup.disarm();+}diff --git a/crates/coding_agent_worker/src/outbound/mod.rs b/crates/coding_agent_worker/src/outbound/mod.rsindex 1808351927..40ab3bb2e5 100644--- a/crates/coding_agent_worker/src/outbound/mod.rs+++ b/crates/coding_agent_worker/src/outbound/mod.rs@@ -7,6 +7,7 @@//! runtime surprise on someone's laptop.pub(crate) mod acp_probe;+pub(crate) mod acp_process;pub mod agent_session;pub mod link;pub mod pairing;diff --git a/crates/coding_agent_worker/src/runtime/test.rs b/crates/coding_agent_worker/src/runtime/test.rsindex 00c41906aa..80bd3f16ed 100644--- a/crates/coding_agent_worker/src/runtime/test.rs+++ b/crates/coding_agent_worker/src/runtime/test.rs@@ -20,12 +20,17 @@ fn start_runtime(listener: &TcpListener) -> Runtime {Harness {command: "cat".to_owned(),args: Vec::new(),+ env: Default::default(),},Path::new("/"),)}#[tokio::test]+#[expect(+ clippy::result_large_err,+ reason = "the handshake callback's error type is fixed by tungstenite's Callback trait"+)]async fn retries_transient_failure_and_closed_connection_without_triggers() {let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let runtime = start_runtime(&listener);@@ -68,6 +73,10 @@ async fn retries_transient_failure_and_closed_connection_without_triggers() {}#[tokio::test]+#[expect(+ clippy::result_large_err,+ reason = "the handshake callback's error type is fixed by tungstenite's Callback trait"+)]async fn refused_credentials_stop_reconnecting() {let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let runtime = start_runtime(&listener);diff --git a/crates/coding_agent_worker/src/tui/agent_catalog.rs b/crates/coding_agent_worker/src/tui/agent_catalog.rsindex 196b7454ca..ad78e82553 100644--- a/crates/coding_agent_worker/src/tui/agent_catalog.rs+++ b/crates/coding_agent_worker/src/tui/agent_catalog.rs@@ -3,13 +3,17 @@mod claude_code;mod codex;mod hermes;+mod npm_adapter;mod open_claw;mod open_code;+use std::collections::BTreeMap;use std::path::{Path, PathBuf};use crate::config::Harness;+pub use npm_adapter::AdapterInstall;+#[cfg(test)]mod test;@@ -17,6 +21,9 @@ mod environment {macro_env_var::maybe_env_var! {pub struct Path;}+ macro_env_var::maybe_env_var! {+ pub struct Home;+ }}static PRESETS: &[&dyn AgentPreset] = &[@@ -34,6 +41,8 @@ pub struct LaunchSpec {pub command: String,/// Arguments passed to the command.pub args: Vec<String>,+ /// Environment the agent needs on top of the daemon's own.+ pub env: BTreeMap<String, String>,}impl LaunchSpec {@@ -41,8 +50,15 @@ impl LaunchSpec {Self {command: command.to_owned(),args: args.into_iter().map(str::to_owned).collect(),+ env: BTreeMap::new(),}}++ fn with_env(mut self, name: &str, value: &Path) -> Self {+ self.env+ .insert(name.to_owned(), value.to_string_lossy().into_owned());+ self+ }}/// A supported agent whose complete launch requirements are installed.@@ -56,6 +72,17 @@ pub struct DetectedAgent {pub launch: LaunchSpec,/// Short explanation for adapter-backed launchers.pub note: Option<&'static str>,+ /// What must be installed before `launch` can run, when anything must.+ pub install: Option<AdapterInstall>,+}++impl DetectedAgent {+ /// The installation still to run before `launch` works, if any.+ pub fn pending_install(&self) -> Option<&AdapterInstall> {+ self.install+ .as_ref()+ .filter(|install| !install.is_installed())+ }}/// Agent identity after converting executable discovery into UI state.@@ -82,11 +109,14 @@ pub enum Availability {pub trait CommandLookup {/// Resolve an executable through the environment's command search path.fn resolve(&self, command: &str) -> Option<&Path>;+ /// Directory macrod installs npm ACP adapters under, when there is one.+ fn adapter_root(&self) -> Option<&Path>;}/// Commands discovered on the process's `PATH`.pub struct PathCommands {found: std::collections::HashMap<&'static str, PathBuf>,+ adapter_root: Option<PathBuf>,}impl PathCommands {@@ -103,7 +133,6 @@ impl PathCommands {"claude","codex","npm",- "npx","openclaw","opencode",] {@@ -111,7 +140,13 @@ impl PathCommands {found.insert(command, path);}}- Self { found }+ let adapter_root = environment::Home::new()+ .and_then(|home| home.value().map(PathBuf::from))+ .map(|home| home.join(".macrod").join("adapters"));+ Self {+ found,+ adapter_root,+ }}}@@ -149,6 +184,10 @@ impl CommandLookup for PathCommands {fn resolve(&self, command: &str) -> Option<&Path> {self.found.get(command).map(PathBuf::as_path)}++ fn adapter_root(&self) -> Option<&Path> {+ self.adapter_root.as_deref()+ }}/// One known way to expose an installed agent harness over ACP.@@ -179,27 +218,7 @@ fn direct(name: preset.name(),launch: LaunchSpec::new(command, args),note: None,- })-}--fn npm_adapter(- preset: &dyn AgentPreset,- commands: &dyn CommandLookup,- cli: &'static str,- package: &'static str,-) -> Availability {- let missing = [cli, "npm", "npx"]- .into_iter()- .filter(|command| commands.resolve(command).is_none())- .collect::<Vec<_>>();- if !missing.is_empty() {- return Availability::Unavailable { missing };- }- Availability::Available(DetectedAgent {- kind: preset.kind(),- name: preset.name(),- launch: LaunchSpec::new("npx", ["-y", package]),- note: Some("via npm ACP adapter"),+ install: None,})}@@ -223,12 +242,21 @@ pub fn discover(commands: &dyn CommandLookup) -> Vec<DetectedAgent> {.collect()}-/// Friendly name for an existing launch configuration.-pub fn name_for(harness: &Harness) -> Option<&'static str> {+fn preset_for(harness: &Harness) -> Option<&'static dyn AgentPreset> {PRESETS.iter()+ .copied().find(|preset| preset.recognizes(harness))- .map(|preset| preset.name())+}++/// Friendly name for an existing launch configuration.+pub fn name_for(harness: &Harness) -> Option<&'static str> {+ preset_for(harness).map(|preset| preset.name())+}++/// Preset identity of an existing launch configuration.+pub fn kind_for(harness: &Harness) -> Option<AgentKind> {+ preset_for(harness).map(|preset| preset.kind())}/// Parse a custom command line into an ACP launch specification.@@ -246,7 +274,9 @@ pub fn custom(command_line: &str) -> Result<DetectedAgent, String> {launch: LaunchSpec {command,args: parts.collect(),+ env: BTreeMap::new(),},note: None,+ install: None,})}diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/claude_code.rs b/crates/coding_agent_worker/src/tui/agent_catalog/claude_code.rsindex 02609198bd..d30d456522 100644--- a/crates/coding_agent_worker/src/tui/agent_catalog/claude_code.rs+++ b/crates/coding_agent_worker/src/tui/agent_catalog/claude_code.rs@@ -1,7 +1,13 @@-use super::{AgentKind, AgentPreset, Availability, CommandLookup, is_launch, npm_adapter};+use super::npm_adapter::NpmAdapter;+use super::{AgentKind, AgentPreset, Availability, CommandLookup};use crate::config::Harness;-const ADAPTER: &str = "@agentclientprotocol/[email protected]";+const ADAPTER: NpmAdapter = NpmAdapter {+ package: "@agentclientprotocol/[email protected]",+ bin: "claude-agent-acp",+ cli: "claude",+ cli_path_env: "CLAUDE_CODE_EXECUTABLE",+};pub(super) struct ClaudeCode;@@ -15,10 +21,10 @@ impl AgentPreset for ClaudeCode {}fn detect(&self, commands: &dyn CommandLookup) -> Availability {- npm_adapter(self, commands, "claude", ADAPTER)+ ADAPTER.detect(self, commands)}fn recognizes(&self, harness: &Harness) -> bool {- is_launch(harness, "npx", &["-y", ADAPTER])+ ADAPTER.recognizes(harness)}}diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/codex.rs b/crates/coding_agent_worker/src/tui/agent_catalog/codex.rsindex 0b54469ed9..714e8ca882 100644--- a/crates/coding_agent_worker/src/tui/agent_catalog/codex.rs+++ b/crates/coding_agent_worker/src/tui/agent_catalog/codex.rs@@ -1,7 +1,13 @@-use super::{AgentKind, AgentPreset, Availability, CommandLookup, is_launch, npm_adapter};+use super::npm_adapter::NpmAdapter;+use super::{AgentKind, AgentPreset, Availability, CommandLookup};use crate::config::Harness;-const ADAPTER: &str = "@agentclientprotocol/[email protected]";+const ADAPTER: NpmAdapter = NpmAdapter {+ package: "@agentclientprotocol/[email protected]",+ bin: "codex-acp",+ cli: "codex",+ cli_path_env: "CODEX_PATH",+};pub(super) struct Codex;@@ -15,10 +21,10 @@ impl AgentPreset for Codex {}fn detect(&self, commands: &dyn CommandLookup) -> Availability {- npm_adapter(self, commands, "codex", ADAPTER)+ ADAPTER.detect(self, commands)}fn recognizes(&self, harness: &Harness) -> bool {- is_launch(harness, "npx", &["-y", ADAPTER])+ ADAPTER.recognizes(harness)}}diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/npm_adapter.rs b/crates/coding_agent_worker/src/tui/agent_catalog/npm_adapter.rsnew file mode 100644index 0000000000..9d6bebdade--- /dev/null+++ b/crates/coding_agent_worker/src/tui/agent_catalog/npm_adapter.rs@@ -0,0 +1,132 @@+//! Agents reached through an ACP adapter distributed on npm.+//!+//! The adapter is installed once, into a directory named after its pinned+//! version under macrod's own adapter root, and launched from there directly.+//! `npx -y <package>@<version>` would install the same thing, but it does so+//! on every launch: an npm start-up plus a registry round trip before the+//! adapter even runs, on every bridge start and every model probe.++use std::path::{Path, PathBuf};+use std::process::Stdio;++use super::{AgentPreset, Availability, CommandLookup, DetectedAgent, LaunchSpec, is_launch};+use crate::config::Harness;++/// An npm-distributed ACP adapter pinned to one version.+pub(super) struct NpmAdapter {+ /// The exact package to install, `@scope/name@version`.+ pub(super) package: &'static str,+ /// The executable the package installs under `node_modules/.bin`.+ pub(super) bin: &'static str,+ /// The CLI the adapter wraps.+ pub(super) cli: &'static str,+ /// The variable the adapter reads for the CLI to run. The adapter bundles+ /// its own copy of `cli` and runs that one by default; the copy can be+ /// older than the one installed here, advertising a different model+ /// catalogue. The value must be absolute: a bare name is looked up on the+ /// adapter's `PATH`, where its own `node_modules/.bin` comes first.+ pub(super) cli_path_env: &'static str,+}++impl NpmAdapter {+ pub(super) fn detect(+ &self,+ preset: &dyn AgentPreset,+ commands: &dyn CommandLookup,+ ) -> Availability {+ let missing = [self.cli, "npm"]+ .into_iter()+ .filter(|command| commands.resolve(command).is_none())+ .collect::<Vec<_>>();+ if !missing.is_empty() {+ return Availability::Unavailable { missing };+ }+ let (Some(cli_path), Some(root)) = (commands.resolve(self.cli), commands.adapter_root())+ else {+ return Availability::Unavailable {+ missing: vec!["HOME"],+ };+ };+ let install = AdapterInstall {+ package: self.package,+ prefix: root.join(self.package),+ bin: root.join(self.bin_path()),+ };+ Availability::Available(DetectedAgent {+ kind: preset.kind(),+ name: preset.name(),+ launch: LaunchSpec::new(&install.bin.to_string_lossy(), [])+ .with_env(self.cli_path_env, cli_path),+ note: Some("via npm ACP adapter"),+ install: Some(install),+ })+ }++ /// Whether `harness` launches this adapter at this version, installed by+ /// macrod or through `npx` as earlier releases wrote it.+ pub(super) fn recognizes(&self, harness: &Harness) -> bool {+ is_launch(harness, "npx", &["-y", self.package])+ || (harness.args.is_empty() && Path::new(&harness.command).ends_with(self.bin_path()))+ }++ /// The executable relative to the adapter root. Carrying the package+ /// version in the path is what makes an existing installation trustworthy+ /// without inspecting it.+ fn bin_path(&self) -> PathBuf {+ Path::new(self.package)+ .join("node_modules")+ .join(".bin")+ .join(self.bin)+ }+}++/// A pinned npm package to install before its executable can be launched.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct AdapterInstall {+ /// The exact package, `@scope/name@version`.+ pub package: &'static str,+ /// The `npm --prefix` directory holding this one version.+ pub prefix: PathBuf,+ /// The executable the installation produces.+ pub bin: PathBuf,+}++impl AdapterInstall {+ /// Whether the executable is already in place.+ pub fn is_installed(&self) -> bool {+ self.bin.exists()+ }++ /// Install the package unless its executable is already in place.+ pub async fn run(&self) -> Result<(), String> {+ if self.is_installed() {+ return Ok(());+ }+ let output = tokio::process::Command::new("npm")+ .args(["install", "--no-audit", "--no-fund", "--loglevel=error"])+ .arg("--prefix")+ .arg(&self.prefix)+ .arg(self.package)+ .stdin(Stdio::null())+ .kill_on_drop(true)+ .output()+ .await+ .map_err(|error| format!("could not run npm to install {}: {error}", self.package))?;+ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ return Err(format!(+ "npm install {} failed: {}",+ self.package,+ stderr.trim().lines().last().unwrap_or("no output")+ ));+ }+ if !self.bin.exists() {+ return Err(format!(+ "npm install {} produced no {}",+ self.package,+ self.bin.display()+ ));+ }+ Ok(())+ }+}diff --git a/crates/coding_agent_worker/src/tui/agent_catalog/test.rs b/crates/coding_agent_worker/src/tui/agent_catalog/test.rsindex a591e54b0b..332d876f32 100644--- a/crates/coding_agent_worker/src/tui/agent_catalog/test.rs+++ b/crates/coding_agent_worker/src/tui/agent_catalog/test.rs@@ -1,8 +1,10 @@-use std::collections::HashMap;+use std::collections::{BTreeMap, HashMap};use std::path::{Path, PathBuf};use super::*;+const ADAPTER_ROOT: &str = "/home/test/.macrod/adapters";+struct Commands(HashMap<&'static str, PathBuf>);impl Commands {@@ -20,6 +22,18 @@ impl CommandLookup for Commands {fn resolve(&self, command: &str) -> Option<&Path> {self.0.get(command).map(PathBuf::as_path)}++ fn adapter_root(&self) -> Option<&Path> {+ Some(Path::new(ADAPTER_ROOT))+ }+}++fn harness(command: &str, args: &[&str]) -> Harness {+ Harness {+ command: command.to_owned(),+ args: args.iter().map(|arg| (*arg).to_owned()).collect(),+ env: BTreeMap::new(),+ }}#[test]@@ -31,6 +45,7 @@ fn direct_agents_need_only_their_command() {[AgentKind::Hermes, AgentKind::OpenClaw, AgentKind::OpenCode]);assert_eq!(agents[0].launch, LaunchSpec::new("hermes", ["acp"]));+ assert_eq!(agents[0].install, None);}#[test]@@ -42,31 +57,103 @@ fn hermes_acp_launcher_is_used_as_a_fallback() {}#[test]-fn adapter_agents_require_the_cli_and_npm_tooling() {- assert!(discover(&Commands::new(&["claude", "npm"])).is_empty());+fn adapter_agents_require_the_cli_and_npm() {+ assert!(discover(&Commands::new(&["claude"])).is_empty());+ assert!(discover(&Commands::new(&["npm"])).is_empty());- let agents = discover(&Commands::new(&["claude", "codex", "npm", "npx"]));+ let agents = discover(&Commands::new(&["claude", "codex", "npm"]));assert_eq!(agents.iter().map(|agent| agent.kind).collect::<Vec<_>>(),[AgentKind::ClaudeCode, AgentKind::Codex]);- assert_eq!(agents[0].launch.command, "npx");assert_eq!(agents[0].note, Some("via npm ACP adapter"));}+#[test]+fn adapter_agents_launch_the_pinned_install_directly() {+ let agents = discover(&Commands::new(&["codex", "npm"]));+ let codex = &agents[0];++ let prefix = format!("{ADAPTER_ROOT}/@agentclientprotocol/[email protected]");+ assert_eq!(+ codex.launch.command,+ format!("{prefix}/node_modules/.bin/codex-acp")+ );+ assert!(codex.launch.args.is_empty());+ let install = codex.install.as_ref().expect("adapter needs installing");+ assert_eq!(install.package, "@agentclientprotocol/[email protected]");+ assert_eq!(install.prefix, Path::new(&prefix));+ assert_eq!(install.bin, Path::new(&codex.launch.command));+}++#[test]+fn adapter_agents_point_the_adapter_at_the_installed_cli() {+ let agents = discover(&Commands::new(&["claude", "codex", "npm"]));++ assert_eq!(+ agents[0].launch.env,+ BTreeMap::from([(+ "CLAUDE_CODE_EXECUTABLE".to_owned(),+ "/bin/claude".to_owned()+ )])+ );+ assert_eq!(+ agents[1].launch.env,+ BTreeMap::from([("CODEX_PATH".to_owned(), "/bin/codex".to_owned())])+ );+}+#[test]fn existing_launch_specs_are_recognized() {- let harness = Harness {- command: "hermes".to_owned(),- args: vec!["acp".to_owned()],- };- assert_eq!(name_for(&harness), Some("Hermes Agent"));+ assert_eq!(name_for(&harness("hermes", &["acp"])), Some("Hermes Agent"));+ assert_eq!(name_for(&harness("my-agent", &[])), None);+ assert_eq!(kind_for(&harness("my-agent", &[])), None);+}++#[test]+fn adapter_configs_are_recognized_however_they_were_written() {+ // Written by releases that launched through npx.+ let legacy = harness("npx", &["-y", "@agentclientprotocol/[email protected]"]);+ assert_eq!(kind_for(&legacy), Some(AgentKind::Codex));++ let installed = harness(+ "/somewhere/else/@agentclientprotocol/[email protected]/node_modules/.bin/codex-acp",+ &[],+ );+ assert_eq!(name_for(&installed), Some("Codex CLI"));++ let other_version = harness(+ "/somewhere/else/@agentclientprotocol/[email protected]/node_modules/.bin/codex-acp",+ &[],+ );+ assert_eq!(name_for(&other_version), None);++ let with_arguments = harness(+ "/somewhere/else/@agentclientprotocol/[email protected]/node_modules/.bin/codex-acp",+ &["--verbose"],+ );+ assert_eq!(name_for(&with_arguments), None);+}- let custom = Harness {- command: "my-agent".to_owned(),- args: Vec::new(),+#[tokio::test]+async fn an_installed_adapter_is_not_installed_again() {+ let root = tempfile::tempdir().expect("temp dir");+ let bin = root.path().join("codex-acp");+ std::fs::write(&bin, "").expect("write stand-in executable");+ let install = AdapterInstall {+ package: "@agentclientprotocol/[email protected]",+ prefix: root.path().to_owned(),+ bin,};- assert_eq!(name_for(&custom), None);++ let agents = discover(&Commands::new(&["codex", "npm"]));+ let mut codex = agents[0].clone();+ codex.install = Some(install.clone());++ assert!(install.is_installed());+ assert_eq!(codex.pending_install(), None);+ // Nothing to fetch, so this returns without running npm at all.+ install.run().await.expect("present install is a no-op");}#[test]@@ -78,4 +165,6 @@ fn custom_commands_preserve_quoted_arguments() {agent.launch.args,["--mode", "acp", "--name", "Macro Agent"]);+ assert!(agent.launch.env.is_empty());+ assert_eq!(agent.install, None);}diff --git a/crates/coding_agent_worker/src/tui/app.rs b/crates/coding_agent_worker/src/tui/app.rsindex 4daf622c55..40d2108f79 100644--- a/crates/coding_agent_worker/src/tui/app.rs+++ b/crates/coding_agent_worker/src/tui/app.rs@@ -80,6 +80,11 @@ pub(crate) enum Mode {},/// Entering an arbitrary ACP command line.CustomAgent { buffer: Input },+ /// A chosen agent's adapter installing; applied when the install ends.+ InstallingAgent {+ agent: DetectedAgent,+ install: tokio::task::JoinHandle<Result<(), String>>,+ },/// Confirming harness removal.ConfirmDelete,/// A pairing in flight: code shown, waiting for approval.@@ -393,6 +398,56 @@ impl App {Mode::EditSetting { .. } => self.on_edit_key(key).await,Mode::AgentPicker { .. } => self.on_agent_picker_key(key).await,Mode::CustomAgent { .. } => self.on_custom_agent_key(key).await,+ Mode::InstallingAgent { .. } if key.code == KeyCode::Esc => {+ if let Mode::InstallingAgent { install, .. } =+ std::mem::replace(&mut self.mode, Mode::Normal)+ {+ install.abort();+ }+ self.ok("install abandoned; the agent was not changed");+ }+ Mode::InstallingAgent { .. } => {}+ }+ }++ /// Persist `agent` as the harness once its adapter is installed. A missing+ /// adapter installs in the background so the panel keeps drawing, and+ /// [`Self::poll_install`] applies the agent when that ends.+ async fn select_agent(&mut self, agent: DetectedAgent) {+ let Some(install) = agent.pending_install().cloned() else {+ return self.apply_agent(&agent).await;+ };+ self.ok(format!("installing {}", install.package));+ self.mode = Mode::InstallingAgent {+ agent,+ install: tokio::spawn(async move { install.run().await }),+ };+ }++ async fn apply_agent(&mut self, agent: &DetectedAgent) {+ self.form.apply_agent(agent);+ self.save_config(ApplyConfig::Now).await;+ }++ pub(crate) async fn poll_install(&mut self) {+ let Mode::InstallingAgent { install, .. } = &self.mode else {+ return;+ };+ if !install.is_finished() {+ return;+ }+ let Mode::InstallingAgent { agent, install } =+ std::mem::replace(&mut self.mode, Mode::Normal)+ else {+ return;+ };+ match install.await {+ Ok(Ok(())) => self.apply_agent(&agent).await,+ Ok(Err(error)) => self.fail(error),+ Err(error) => self.fail(format!(+ "installing {} was interrupted: {error}",+ agent.name+ )),}}@@ -454,8 +509,7 @@ impl App {let agent = self.agents.get(*selected).cloned();self.mode = Mode::Normal;if let Some(agent) = agent {- self.form.apply_agent(&agent);- self.save_config(ApplyConfig::Now).await;+ self.select_agent(agent).await;}}}@@ -476,8 +530,7 @@ impl App {KeyCode::Enter => match agent_catalog::custom(buffer.value()) {Ok(agent) => {self.mode = Mode::Normal;- self.form.apply_agent(&agent);- self.save_config(ApplyConfig::Now).await;+ self.apply_agent(&agent).await;}Err(error) => self.fail(error),},diff --git a/crates/coding_agent_worker/src/tui/config_form.rs b/crates/coding_agent_worker/src/tui/config_form.rsindex 157b6fcba3..ffb1e1c193 100644--- a/crates/coding_agent_worker/src/tui/config_form.rs+++ b/crates/coding_agent_worker/src/tui/config_form.rs@@ -195,6 +195,19 @@ impl ConfigForm {}let section = self.doc["harness"].or_insert(toml_edit::table());section["args"] = value(args);+ // Replaced, not merged: the previous agent's variables name its CLI,+ // not this one's.+ if agent.launch.env.is_empty() {+ if let Some(table) = section.as_table_like_mut() {+ table.remove("env");+ }+ } else {+ let mut env = toml_edit::InlineTable::new();+ for (name, path) in &agent.launch.env {+ env.insert(name, path.as_str().into());+ }+ section["env"] = value(env);+ }}/// Apply Quickstart values to this document without replacing other settings.diff --git a/crates/coding_agent_worker/src/tui/config_form/test.rs b/crates/coding_agent_worker/src/tui/config_form/test.rsindex ce93813fc0..070f4201b5 100644--- a/crates/coding_agent_worker/src/tui/config_form/test.rs+++ b/crates/coding_agent_worker/src/tui/config_form/test.rs@@ -1,8 +1,9 @@+use std::collections::BTreeMap;use std::fs;use super::*;use crate::config::{HarnessCredentials, HarnessScope};-use crate::tui::agent_catalog::{CommandLookup, discover};+use crate::tui::agent_catalog::{CommandLookup, discover, name_for};use harness_id::HarnessId;struct HermesOnly;@@ -11,6 +12,26 @@ impl CommandLookup for HermesOnly {fn resolve(&self, command: &str) -> Option<&Path> {(command == "hermes").then_some(Path::new("/bin/hermes"))}++ fn adapter_root(&self) -> Option<&Path> {+ None+ }+}++struct CodexOnly;++impl CommandLookup for CodexOnly {+ fn resolve(&self, command: &str) -> Option<&Path> {+ match command {+ "codex" => Some(Path::new("/nix/store/x/bin/codex")),+ "npm" => Some(Path::new("/bin/npm")),+ _ => None,+ }+ }++ fn adapter_root(&self) -> Option<&Path> {+ Some(Path::new("/home/test/.macrod/adapters"))+ }}#[test]@@ -158,6 +179,41 @@ fn quickstart_edits_preserve_existing_deployment_and_comments() {assert_private_mode(&path);}+#[test]+fn agent_environment_round_trips_and_is_replaced_with_the_agent() {+ let directory = tempfile::tempdir().expect("temp dir");+ let path = directory.path().join("macrod.toml");+ let hermes = discover(&HermesOnly).remove(0);+ ConfigForm::create_for_deployment(&path, &hermes, directory.path(), Deployment::Production)+ .expect("create config");+ let codex = discover(&CodexOnly).remove(0);++ let mut form = ConfigForm::load(&path).expect("load form");+ form.apply_agent(&codex);+ form.save().expect("save codex");++ let config = Config::load(&path).expect("load codex config");+ assert_eq!(config.harness.command, codex.launch.command);+ assert!(config.harness.args.is_empty());+ assert_eq!(+ config.harness.env,+ BTreeMap::from([("CODEX_PATH".to_owned(), "/nix/store/x/bin/codex".to_owned())])+ );+ assert_eq!(name_for(&config.harness), Some("Codex CLI"));++ form.apply_agent(&hermes);+ form.save().expect("save hermes");++ let config = Config::load(&path).expect("load hermes config");+ assert_eq!(config.harness.command, "hermes");+ assert!(config.harness.env.is_empty());+ assert!(+ !fs::read_to_string(&path)+ .expect("read config")+ .contains("env")+ );+}+#[test]fn rejects_a_missing_workspace_edit() {let directory = tempfile::tempdir().expect("temp dir");diff --git a/crates/coding_agent_worker/src/tui/quickstart.rs b/crates/coding_agent_worker/src/tui/quickstart.rsindex 4c9beece26..1433a9cc0d 100644--- a/crates/coding_agent_worker/src/tui/quickstart.rs+++ b/crates/coding_agent_worker/src/tui/quickstart.rs@@ -68,12 +68,12 @@ impl Quickstart {}fn from_config_with_agents(config: &Config, agents: Vec<DetectedAgent>) -> Self {+ // Matched by preset rather than by launch line, so a config written+ // by an earlier release keeps its agent preselected.+ let configured = agent_catalog::kind_for(&config.harness);let selected_agent = agents.iter()- .find(|agent| {- agent.launch.command == config.harness.command- && agent.launch.args == config.harness.args- })+ .find(|agent| Some(agent.kind) == configured).cloned().or_else(|| {Some(DetectedAgent {@@ -82,8 +82,10 @@ impl Quickstart {launch: super::agent_catalog::LaunchSpec {command: config.harness.command.clone(),args: config.harness.args.clone(),+ env: config.harness.env.clone(),},note: None,+ install: None,})});let focus = selected_agentdiff --git a/crates/coding_agent_worker/src/tui/quickstart/test.rs b/crates/coding_agent_worker/src/tui/quickstart/test.rsindex 0f2f271181..029b4b2197 100644--- a/crates/coding_agent_worker/src/tui/quickstart/test.rs+++ b/crates/coding_agent_worker/src/tui/quickstart/test.rs@@ -83,6 +83,7 @@ fn unpaired_config_prefills_recognized_agent_workspace_and_scope() {let config = config(Harness {command: "hermes".to_owned(),args: vec!["acp".to_owned()],+ env: Default::default(),});let agents = vec![DetectedAgent {kind: AgentKind::Hermes,@@ -90,8 +91,10 @@ fn unpaired_config_prefills_recognized_agent_workspace_and_scope() {launch: agent_catalog::LaunchSpec {command: "hermes".to_owned(),args: vec!["acp".to_owned()],+ env: Default::default(),},note: None,+ install: None,}];let quickstart = Quickstart::from_config_with_agents(&config, agents);@@ -107,6 +110,7 @@ fn unpaired_config_prefills_custom_command_with_all_arguments() {let config = config(Harness {command: "my-agent".to_owned(),args: vec!["--mode".to_owned(), "acp bridge".to_owned()],+ env: Default::default(),});let quickstart = Quickstart::from_config_with_agents(&config, Vec::new());@@ -141,6 +145,7 @@ fn permission_bypass_defaults_off_and_can_be_toggled() {&config(Harness {command: "hermes".to_owned(),args: vec!["acp".to_owned()],+ env: Default::default(),}),Vec::new(),);@@ -157,6 +162,7 @@ fn unpaired_config_prefills_permission_bypass_consent() {let mut config = config(Harness {command: "hermes".to_owned(),args: vec!["acp".to_owned()],+ env: Default::default(),});config.identity.allow_permission_bypass = true;let setup = Quickstart::from_config_with_agents(&config, Vec::new());@@ -170,6 +176,7 @@ fn quickstart_renders_permission_consent_and_warning() {&config(Harness {command: "hermes".to_owned(),args: vec!["acp".to_owned()],+ env: Default::default(),}),Vec::new(),);diff --git a/crates/coding_agent_worker/src/tui/runner.rs b/crates/coding_agent_worker/src/tui/runner.rsindex 640846155c..e6ac466c8a 100644--- a/crates/coding_agent_worker/src/tui/runner.rs+++ b/crates/coding_agent_worker/src/tui/runner.rs@@ -109,7 +109,7 @@ async fn run_quickstart(QuickstartAction::Continue => {}QuickstartAction::Quit => return Ok(false),QuickstartAction::Create => {- let Some(agent) = quickstart.selected_agent.as_ref() else {+ let Some(agent) = quickstart.selected_agent.clone() else {quickstart.status =Some(("Press Enter on Agent to choose one".to_owned(), true));continue;@@ -129,14 +129,26 @@ async fn run_quickstart());continue;}+ if let Some(install) = agent.pending_install() {+ // Drawn before the wait: nothing else repaints until npm+ // returns.+ quickstart.status = Some((format!("Installing {}...", install.package), false));+ terminal+ .draw(|frame| ui::render_quickstart(frame, &quickstart, config_path))+ .context("failed to draw Quickstart")?;+ if let Err(error) = install.run().await {+ quickstart.status = Some((error, true));+ continue;+ }+ }let saved = if existing_config.is_some() {ConfigForm::load(config_path).and_then(|mut form| {- form.apply_quickstart(agent, &workspace, quickstart.scope);+ form.apply_quickstart(&agent, &workspace, quickstart.scope);form.set_permission_bypass(quickstart.allow_permission_bypass);form.save()})} else {- ConfigForm::create(config_path, agent, &workspace).and_then(|()| {+ ConfigForm::create(config_path, &agent, &workspace).and_then(|()| {let mut form = ConfigForm::load(config_path)?;form.set_scope(quickstart.scope);form.set_permission_bypass(quickstart.allow_permission_bypass);@@ -195,6 +207,7 @@ async fn run_loop(_ = tick.tick() => {app.spinner = app.spinner.wrapping_add(1);app.poll_pairing().await;+ app.poll_install().await;if matches!(app.mode, Mode::Normal) {app.maybe_refresh().await;}diff --git a/crates/coding_agent_worker/src/tui/ui.rs b/crates/coding_agent_worker/src/tui/ui.rsindex 0d817f4767..00d24716e4 100644--- a/crates/coding_agent_worker/src/tui/ui.rs+++ b/crates/coding_agent_worker/src/tui/ui.rs@@ -38,6 +38,6 @@ pub(crate) fn render(frame: &mut Frame, app: &App) {modals::render_agent_picker(frame, &app.agents, *selected)}Mode::CustomAgent { buffer } => modals::render_custom_agent(frame, buffer),- Mode::Normal | Mode::EditSetting { .. } => {}+ Mode::Normal | Mode::EditSetting { .. } | Mode::InstallingAgent { .. } => {}}}