agentmux_bashwrap/mps_client.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Thin HTTP client for publishing MPS events to the AgentMux sidecar.
5//!
6//! Reads `AGENTMUX_LOCAL_URL` and `AGENTMUX_AUTH_KEY` from the
7//! process environment (inherited from the agentmux-srv → claude →
8//! bash subprocess chain). Attaches `X-AuthKey` per PR #801 to
9//! authenticate against the auth_middleware-gated publish endpoint.
10//!
11//! Designed to silently degrade: if env vars are absent or the
12//! sidecar is unreachable, publishes fail-fast and the caller emits
13//! a `kind: "system"` chunk that surfaces the degradation to the
14//! user without aborting the command itself.
15
16use agentmux_common::AUTH_KEY_HEADER;
17use agentmux_common::api_types::WpsPublishRequest;
18use agentmux_common::client_events::{CompactionStarted, ToolChunk};
19use anyhow::Result;
20use serde::Serialize;
21use std::sync::Arc;
22
23const PUBLISH_PATH: &str = "/agentmux/wps/publish";
24
25/// Where a container agent's output goes: srv takes only its own pane's `tool_chunk` there, and
26/// refuses its token on the generic relay above.
27const CONTAINER_TOOL_CHUNK_PATH: &str = "/api/v1/agent/tool-chunk";
28
29/// Where a container agent's `PreCompact` hook reports that it is compacting: srv takes only its
30/// own pane's `compaction_started` there, and refuses its token on the generic relay above.
31const CONTAINER_COMPACTION_STARTED_PATH: &str = "/api/v1/agent/compaction-started";
32
33/// Where `event` is published from here, or `None` when srv takes it from nobody here: a
34/// container's other events are refused on every route.
35fn publish_path(event: &str, in_container: bool) -> Option<&'static str> {
36 match (in_container, event) {
37 (false, _) => Some(PUBLISH_PATH),
38 (true, TOOL_CHUNK_EVENT) => Some(CONTAINER_TOOL_CHUNK_PATH),
39 (true, COMPACTION_STARTED_EVENT) => Some(CONTAINER_COMPACTION_STARTED_PATH),
40 (true, _) => None,
41 }
42}
43
44/// Set by srv for a turn in a container, as a hint for this client (`container_exec_env`).
45fn in_container() -> bool {
46 std::env::var("AGENTMUX_IN_CONTAINER").is_ok_and(|v| v == "1")
47}
48
49/// Per-launch sidecar config + reusable HTTP client. Cheap to clone
50/// (the inner `reqwest::Client` uses Arc internally).
51#[derive(Clone)]
52pub struct WpsClient {
53 inner: Arc<reqwest::Client>,
54 endpoint: String,
55 auth_key: String,
56}
57
58/// How many `tool_chunk` events the broker keeps per `block:<id>`
59/// scope. Sized for npm-install class output (~1000 lines is typical;
60/// 1024 covers all but heavy CI builds). Each event is ~200–500 bytes,
61/// so the steady-state ceiling is ~512 KB per actively-streaming block.
62const TOOL_CHUNK_PERSIST: usize = 1024;
63
64/// Event name for streaming bash chunks. Held constant across every
65/// publish so the frontend can subscribe once per block on mount.
66const TOOL_CHUNK_EVENT: &str = "tool_chunk";
67
68/// Event name for the `PreCompact`-hook-sourced "compaction started"
69/// signal. See `docs/specs/SPEC_COMPACTION_DETECTION_AND_HANDLING_2026_07_31.md`
70/// §4.2 / Tier 1.
71const COMPACTION_STARTED_EVENT: &str = "compaction_started";
72
73/// `persist: 0` — never retained/replayed. A late/reconnecting
74/// subscriber must NOT see a past "compaction started" ping: there
75/// is no matching completion tombstone (`compact_boundary` arrives
76/// over the separate NDJSON stream, not MPS), so replaying a
77/// retained start indistinguishably resurrects "Compacting…" for a
78/// compaction that may have finished seconds after the ping — a
79/// timestamp-age guard alone can't tell "recently finished" apart
80/// from "still running" (Codex P1, PR #2378 round 2). Only a
81/// currently-live subscriber should ever see this event; a
82/// disconnected pane already clears its own `compacting` flag on
83/// `StreamUnsubscribe` (reducer.ts), so there is nothing worth
84/// replaying on reconnect regardless.
85const COMPACTION_STARTED_PERSIST: usize = 0;
86
87/// Fail-fast timeout for `publish_compaction_started` specifically —
88/// much shorter than the 5s client-wide default used for `tool_chunk`
89/// streaming (`from_env`). That default is fine for `exec`'s own async
90/// runtime, but `precompact` is invoked as Claude Code's SYNCHRONOUS
91/// `PreCompact` hook: the CLI blocks compaction on this process's exit,
92/// so inheriting the 5s default means a wedged (but TCP-accepting)
93/// backend delays the user's actual compaction by up to 5 real seconds —
94/// directly contradicting this hook's own "never block/delay the
95/// operation for observability" contract (see `precompact.rs`'s module
96/// doc comment). Codex P2, PR #2378 round 4. 500ms comfortably covers a
97/// normal same-host round trip while keeping the worst case imperceptible.
98const COMPACTION_STARTED_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500);
99
100impl WpsClient {
101 /// Build a client from the env. Returns `None` when the required
102 /// env vars are missing — the caller surfaces a system chunk
103 /// rather than crashing.
104 pub fn from_env() -> Option<Self> {
105 let endpoint = std::env::var("AGENTMUX_LOCAL_URL").ok()?;
106 let auth_key = std::env::var("AGENTMUX_AUTH_KEY").ok()?;
107 if endpoint.is_empty() || auth_key.is_empty() {
108 return None;
109 }
110 let inner = agentmux_common::local_http::builder()
111 // Snappy publish — chunks should land within a frame of
112 // emission. Long timeouts here cause back-pressure that
113 // stalls the PTY reader.
114 .timeout(std::time::Duration::from_secs(5))
115 .build()
116 .ok()?;
117 Some(Self {
118 inner: Arc::new(inner),
119 endpoint: endpoint.trim_end_matches('/').to_string(),
120 auth_key,
121 })
122 }
123
124 /// Publish a `tool_chunk` event. The tool_use_id lives in the
125 /// payload (not on this method's signature) so a single per-block
126 /// subscription receives chunks for every tool in that block.
127 /// Persists with `TOOL_CHUNK_PERSIST` so late subscribers (the
128 /// frontend, which learns about the tool_use only after Claude
129 /// buffers the stream) get the full history on subscribe.
130 pub async fn publish_chunk(
131 &self,
132 block_id: Option<&str>,
133 payload: &ToolChunk,
134 ) -> Result<()> {
135 self.publish(TOOL_CHUNK_EVENT, TOOL_CHUNK_PERSIST, block_id, payload, None)
136 .await
137 }
138
139 /// Publish a `compaction_started` event — the `PreCompact`-hook
140 /// signal that fires the instant Claude Code begins compacting.
141 /// `persist = 0`: live subscribers only, never replayed — see
142 /// `COMPACTION_STARTED_PERSIST`'s doc comment. Uses
143 /// `COMPACTION_STARTED_TIMEOUT` (much shorter than the client-wide
144 /// default) since this call sits on a synchronous hook Claude Code
145 /// blocks compaction on — see that constant's doc comment.
146 pub async fn publish_compaction_started(
147 &self,
148 block_id: Option<&str>,
149 payload: &CompactionStarted,
150 ) -> Result<()> {
151 self.publish(
152 COMPACTION_STARTED_EVENT,
153 COMPACTION_STARTED_PERSIST,
154 block_id,
155 payload,
156 Some(COMPACTION_STARTED_TIMEOUT),
157 )
158 .await
159 }
160
161 /// POST `body` as JSON to `path` on the sidecar and return its JSON
162 /// reply. `agent_token` goes out as `X-Agent-Token`, so the sidecar
163 /// knows which agent is asking (an agent's own env carries it as
164 /// `AGENTMUX_AGENT_TOKEN`). `timeout` replaces the client-wide default:
165 /// callers on a synchronous hook must not wait long.
166 pub async fn post_json(
167 &self,
168 path: &str,
169 agent_token: Option<&str>,
170 body: &impl Serialize,
171 timeout: std::time::Duration,
172 ) -> Result<serde_json::Value> {
173 let url = format!("{}{}", self.endpoint, path);
174 let mut req = self
175 .inner
176 .post(&url)
177 .header(AUTH_KEY_HEADER, &self.auth_key)
178 .header("Content-Type", "application/json")
179 .timeout(timeout)
180 .json(body);
181 if let Some(token) = agent_token.filter(|t| !t.is_empty()) {
182 req = req.header("X-Agent-Token", token);
183 }
184 let resp = req.send().await?;
185 let status = resp.status();
186 if !status.is_success() {
187 anyhow::bail!("{path}: HTTP {status}");
188 }
189 Ok(resp.json().await?)
190 }
191
192 /// [`Self::post_json`], keeping a refusal's status and body: the caller shows the person what srv
193 /// said, not just that it said no.
194 pub async fn post_json_status(
195 &self,
196 path: &str,
197 agent_token: Option<&str>,
198 body: &impl Serialize,
199 timeout: std::time::Duration,
200 ) -> Result<(u16, serde_json::Value)> {
201 let url = format!("{}{}", self.endpoint, path);
202 let mut req = self
203 .inner
204 .post(&url)
205 .header(AUTH_KEY_HEADER, &self.auth_key)
206 .header("Content-Type", "application/json")
207 .timeout(timeout)
208 .json(body);
209 if let Some(token) = agent_token.filter(|t| !t.is_empty()) {
210 req = req.header("X-Agent-Token", token);
211 }
212 let resp = req.send().await?;
213 let status = resp.status().as_u16();
214 let text = resp.text().await.unwrap_or_default();
215 Ok((status, serde_json::from_str(&text).unwrap_or(serde_json::Value::Null)))
216 }
217
218 /// Shared publish path for every MPS event this crate emits.
219 /// `event`/`persist` vary per call site; the scoping (`block:<id>`)
220 /// and auth/error-handling are identical across all of them.
221 /// `timeout_override` replaces the client-wide default
222 /// (`reqwest::RequestBuilder::timeout` overrides per-request) when
223 /// `Some` — used by call sites sitting on a synchronous caller that
224 /// must not inherit `from_env`'s more generous streaming timeout.
225 async fn publish(
226 &self,
227 event: &str,
228 persist: usize,
229 block_id: Option<&str>,
230 payload: &impl Serialize,
231 timeout_override: Option<std::time::Duration>,
232 ) -> Result<()> {
233 let Some(path) = publish_path(event, in_container()) else { return Ok(()) };
234 let body = WpsPublishRequest {
235 event: event.to_string(),
236 scopes: block_id.map(|b| vec![format!("block:{b}")]).unwrap_or_default(),
237 persist,
238 data: serde_json::to_value(payload)?,
239 };
240 let url = format!("{}{}", self.endpoint, path);
241 let mut req = self
242 .inner
243 .post(&url)
244 .header(AUTH_KEY_HEADER, &self.auth_key)
245 .header("Content-Type", "application/json")
246 .json(&body);
247 if let Some(d) = timeout_override {
248 req = req.timeout(d);
249 }
250 let resp = req
251 .send()
252 .await?;
253 if !resp.status().is_success() {
254 let status = resp.status();
255 let text = resp.text().await.unwrap_or_default();
256 anyhow::bail!("publish failed: HTTP {} — {}", status, text);
257 }
258 Ok(())
259 }
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265 use crate::test_env_lock::ENV_LOCK;
266
267 // `std::env::set_var` / `remove_var` mutate process-global state;
268 // cargo test runs tests in parallel by default, so without a
269 // serial lock these races between threads (codex P1 on PR #804).
270 // Shared with `precompact.rs`'s test module, which mutates the SAME
271 // env vars — a private per-module lock doesn't actually synchronize
272 // cross-module (Codex P2, PR #2378 round 6).
273 fn clear_env() {
274 std::env::remove_var("AGENTMUX_LOCAL_URL");
275 std::env::remove_var("AGENTMUX_AUTH_KEY");
276 }
277
278 #[test]
279 fn a_container_reports_to_its_own_routes_and_sends_nothing_else() {
280 assert_eq!(publish_path("tool_chunk", false), Some("/agentmux/wps/publish"));
281 assert_eq!(publish_path("compaction_started", false), Some("/agentmux/wps/publish"));
282 assert_eq!(publish_path("tool_chunk", true), Some("/api/v1/agent/tool-chunk"));
283 assert_eq!(publish_path("compaction_started", true), Some("/api/v1/agent/compaction-started"));
284 assert_eq!(publish_path("custom:thing", true), None);
285 }
286
287 #[test]
288 fn from_env_returns_none_without_endpoint() {
289 let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
290 clear_env();
291 assert!(WpsClient::from_env().is_none());
292 }
293
294 #[test]
295 fn from_env_returns_none_when_only_endpoint_set() {
296 let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
297 clear_env();
298 std::env::set_var("AGENTMUX_LOCAL_URL", "http://127.0.0.1:1");
299 assert!(WpsClient::from_env().is_none());
300 clear_env();
301 }
302
303 #[test]
304 fn from_env_strips_trailing_slash() {
305 let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
306 clear_env();
307 std::env::set_var("AGENTMUX_LOCAL_URL", "http://127.0.0.1:9999/");
308 std::env::set_var("AGENTMUX_AUTH_KEY", "x");
309 let c = WpsClient::from_env().expect("client");
310 assert_eq!(c.endpoint, "http://127.0.0.1:9999");
311 clear_env();
312 }
313
314 // ── event/persist constants (refactor of `publish` into a shared
315 // helper — SPEC_COMPACTION_DETECTION_AND_HANDLING_2026_07_31.md §4.2) ──
316
317 #[test]
318 fn compaction_started_event_name_and_persist() {
319 assert_eq!(COMPACTION_STARTED_EVENT, "compaction_started");
320 // Never retained/replayed (Codex P1, PR #2378 round 2) — a
321 // reconnecting subscriber must not resurrect a past ping for
322 // a compaction that has since finished; see the constant's
323 // doc comment for why an age-based guard alone can't fix
324 // this on the receiving end.
325 assert_eq!(COMPACTION_STARTED_PERSIST, 0);
326 }
327
328 #[test]
329 fn compaction_started_uses_a_short_fail_fast_timeout() {
330 // Codex P2, PR #2378 round 4: this publish sits on Claude Code's
331 // SYNCHRONOUS PreCompact hook -- the CLI blocks compaction on this
332 // process's exit, so it must not inherit the 5s client-wide
333 // default used for tool_chunk streaming (from_env), or a wedged
334 // backend delays the user's actual compaction by up to 5 real
335 // seconds. Comfortably shorter than the client default, long
336 // enough for a normal same-host round trip.
337 assert!(COMPACTION_STARTED_TIMEOUT < std::time::Duration::from_secs(5));
338 assert_eq!(COMPACTION_STARTED_TIMEOUT, std::time::Duration::from_millis(500));
339 }
340
341 #[test]
342 fn tool_chunk_event_name_and_persist_unchanged_by_refactor() {
343 // The `publish` extraction must not change `publish_chunk`'s
344 // existing wire behavior.
345 assert_eq!(TOOL_CHUNK_EVENT, "tool_chunk");
346 assert_eq!(TOOL_CHUNK_PERSIST, 1024);
347 }
348}