agentmux_srv_core/backend/blockcontroller/acp.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! AcpController: manages agent CLIs that speak the Agent Client Protocol (ACP).
5//!
6//! ACP is a JSON-RPC 2.0 protocol over stdin/stdout — the "LSP for AI agents."
7//! Instead of custom per-provider output parsing, ACP provides a standardized
8//! protocol for session management, prompting, and streaming events.
9//!
10//! Lifecycle:
11//! 1. Spawn the ACP agent process (e.g., `gemini --acp`, `openclaw acp`)
12//! 2. Send `initialize` request, receive capabilities
13//! 3. Send `initialized` notification
14//! 4. Create a session via `session/create`
15//! 5. For each user turn: send `session/prompt`, stream `session/update` notifications
16//! 6. On close: send `shutdown` + `exit`
17//!
18//! I/O model (similar to PersistentSubprocessController):
19//! - stdin_writer: sends JSON-RPC requests/notifications to agent
20//! - stdout_reader: reads JSON-RPC responses/notifications, persists + broadcasts
21//! - process_waiter: monitors process lifecycle
22//!
23//! See: https://github.com/agentclientprotocol/agent-client-protocol
24
25use crate::backend::message_origin::RecordOrigin;
26#[cfg(windows)]
27use agentmux_common::win32::NoWindow;
28use std::collections::{HashMap, HashSet};
29use std::sync::atomic::{AtomicU64, Ordering};
30use std::sync::{Arc, Mutex};
31
32use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
33use tokio::sync::mpsc;
34
35use super::{
36 agent_runtime_status, BlockControllerRuntimeStatus, BlockInputUnion, Controller, SendOutcome, STATUS_DONE,
37 STATUS_INIT, STATUS_RUNNING,
38};
39use super::core;
40use super::meta_string_map;
41use super::health::TurnActivityTracker;
42use crate::backend::eventbus::EventBus;
43use crate::backend::storage::filestore::FileStore;
44use crate::backend::storage::store::Store;
45use crate::backend::mps;
46
47/// MPS file subject name for ACP output.
48pub const ACP_OUTPUT_SUBJECT: &str = "output";
49
50pub const BLOCK_CONTROLLER_ACP: &str = "acp";
51
52/// Written to the output after an error that ended the turn (no prompt left
53/// running, or the session couldn't open). The translator ends a turn on a
54/// `stopReason`; it can't tell from an error alone, which may answer only a
55/// mid-turn steering prompt while the first one still runs.
56const TURN_ENDED_BY_ERROR: &str = r#"{"jsonrpc":"2.0","result":{"stopReason":"error"}}"#;
57
58// ---- ACP v1 messages (SPEC_ACP_CLIENT_CONFORMANCE_2026_10_07.md) ----
59// Checked against @agentclientprotocol/sdk 0.26.0 (`PROTOCOL_VERSION = 1`).
60
61/// `initialize`: the protocol version and what this client can do. AgentMux
62/// offers no file system or terminal to the agent; it runs its own tools.
63fn initialize_params() -> serde_json::Value {
64 serde_json::json!({
65 "protocolVersion": 1,
66 "clientCapabilities": {
67 "fs": { "readTextFile": false, "writeTextFile": false },
68 "terminal": false,
69 },
70 "clientInfo": { "name": "AgentMux", "version": env!("CARGO_PKG_VERSION") },
71 })
72}
73
74/// How an agent takes an earlier session back, from its `initialize` answer.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub(super) enum SessionRestore {
77 /// Neither: every start is a new session.
78 No,
79 /// `session/load` (`agentCapabilities.loadSession`): the agent replays the conversation first.
80 Load,
81 /// `session/resume` (`agentCapabilities.sessionCapabilities.resume`, dsh): the conversation comes back
82 /// with no replay.
83 Resume,
84}
85
86impl SessionRestore {
87 /// The way an agent that said `can_load` and/or `can_resume` takes a session back. A replay is
88 /// preferred when both are offered, as before `session/resume` was supported.
89 pub(super) fn of(can_load: bool, can_resume: bool) -> Self {
90 if can_load {
91 Self::Load
92 } else if can_resume {
93 Self::Resume
94 } else {
95 Self::No
96 }
97 }
98}
99
100/// `session/new`, or `session/load` / `session/resume` of `resume` when the agent can take one back,
101/// with the agent's MCP servers (`acp_mcp`).
102fn session_request(
103 resume: Option<&str>,
104 restore: SessionRestore,
105 cwd: &str,
106 mcp_servers: &[serde_json::Value],
107) -> (&'static str, serde_json::Value) {
108 let method = match restore {
109 SessionRestore::Load => "session/load",
110 SessionRestore::Resume => "session/resume",
111 SessionRestore::No => "session/new",
112 };
113 match resume.filter(|_| restore != SessionRestore::No) {
114 Some(sid) => (method, serde_json::json!({ "sessionId": sid, "cwd": cwd, "mcpServers": mcp_servers })),
115 None => ("session/new", serde_json::json!({ "cwd": cwd, "mcpServers": mcp_servers })),
116 }
117}
118
119/// Whether a line from the agent is part of a `session/load` replay: the
120/// agent streams the earlier conversation as `session/update`s before it
121/// answers the load, and the load's own answer is not one of them.
122fn is_session_replay(loading: bool, is_session_response: bool) -> bool {
123 loading && !is_session_response
124}
125
126/// The absolute directory ACP's `session/new` and `session/load` take as
127/// `cwd`: the pane's working directory (`~` expanded; a relative one resolved
128/// against the server's, as `Command::current_dir` resolves it), else the
129/// directory the agent process itself starts in.
130pub(super) fn session_cwd(working_dir: &str) -> String {
131 let here = std::env::current_dir().unwrap_or_default();
132 let dir = if working_dir.is_empty() {
133 here.clone()
134 } else {
135 let expanded = std::path::PathBuf::from(super::core::expand_home_dir(working_dir));
136 if expanded.is_absolute() { expanded } else { here.join(expanded) }
137 };
138 dir.to_string_lossy().into_owned()
139}
140
141/// `session/prompt` params: the prompt is an array of content blocks.
142fn prompt_params(session_id: &str, text: &str) -> serde_json::Value {
143 serde_json::json!({
144 "sessionId": session_id,
145 "prompt": [{ "type": "text", "text": text }],
146 })
147}
148
149/// The reply to a request the agent sends us, if `json` is one (it has both
150/// `method` and `id`). AgentMux approves tool use by default, as it does for
151/// every harness: the first `allow_always` option, else `allow_once`, else
152/// cancelled. Anything else (`fs/*`, `terminal/*`, which this client does not
153/// offer) gets "method not found", so the agent never waits on us.
154fn reply_to_agent_request(json: &serde_json::Value) -> Option<serde_json::Value> {
155 let method = json.get("method")?.as_str()?;
156 // A request carries an `id`, which ACP lets be null and requires us to
157 // echo; a notification has none.
158 let id = json.get("id")?.clone();
159 if method == "session/request_permission" {
160 let options = json
161 .pointer("/params/options")
162 .and_then(|o| o.as_array())
163 .cloned()
164 .unwrap_or_default();
165 let pick = |kind: &str| {
166 options
167 .iter()
168 .find(|o| o.get("kind").and_then(|k| k.as_str()) == Some(kind))
169 .and_then(|o| o.get("optionId").cloned())
170 };
171 let outcome = match pick("allow_always").or_else(|| pick("allow_once")) {
172 Some(option_id) => serde_json::json!({ "outcome": "selected", "optionId": option_id }),
173 None => serde_json::json!({ "outcome": "cancelled" }),
174 };
175 return Some(serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": { "outcome": outcome } }));
176 }
177 Some(serde_json::json!({
178 "jsonrpc": "2.0",
179 "id": id,
180 "error": { "code": -32601, "message": format!("AgentMux does not offer {method}") },
181 }))
182}
183
184/// Remove `resolved_id` from the set of outstanding (sent, not yet
185/// resolved) prompts and report whether the set is now EMPTY — i.e.
186/// whether every prompt sent so far has now been resolved, by either a
187/// real `stopReason` completion or a JSON-RPC `error` rejection, meaning
188/// the turn has genuinely ended. Extracted as a pure function over a
189/// plain `HashSet` so this exact logic is directly unit-testable; call
190/// sites wrap it with the shared mutex around the real
191/// `outstanding_prompt_ids`.
192///
193/// Tracking every outstanding prompt — not just "the latest" — is what
194/// makes response ORDERING irrelevant: "is the turn over" only ever asks
195/// "is anything still outstanding," never "was this the most recent
196/// one." codex P2 on PR #2338 (thirtieth re-review) — superseded the
197/// twenty-seventh through twenty-ninth re-reviews' single latest/
198/// previous-id tracking (`is_latest_prompt_completion` +
199/// `rollback_latest_prompt_id_if_unchanged`, both removed), which could
200/// permanently strand `turn_active` at `true`: a steering prompt's
201/// rejection arriving AFTER the earlier prompt's completion had already
202/// been consumed (and discarded as "not the latest") rolled
203/// `latest_prompt_id` back to a prompt whose own completion would never
204/// arrive again — nothing left to ever satisfy the match.
205fn resolve_prompt_and_check_idle(outstanding: &mut HashSet<u64>, resolved_id: u64) -> bool {
206 outstanding.remove(&resolved_id);
207 outstanding.is_empty()
208}
209
210/// Inner state protected by mutex.
211struct AcpInner {
212 proc_status: String,
213 proc_exit_code: i32,
214 status_version: i32,
215 session_id: Option<String>,
216 current_pid: Option<u32>,
217 stdin_tx: Option<mpsc::Sender<String>>,
218 kill_tx: Option<tokio::sync::oneshot::Sender<bool>>,
219 /// First user prompt, deferred until session/create completes.
220 pending_prompt: Option<String>,
221 /// The commands the agent announced after `session/new` (`available_commands_update`), by name; `None` until it has.
222 /// An agent offers compaction when `compact` is among them.
223 announced_commands: Option<Vec<AnnouncedCommand>>,
224 /// ACP v1 handshake: the `initialize` request, whose result decides
225 /// between `session/new` and `session/load`.
226 init_request_id: Option<u64>,
227 /// The `session/new` or `session/load` request in flight.
228 session_request_id: Option<u64>,
229 /// The session being loaded: its result carries no id of its own.
230 loading_session: Option<String>,
231 /// `session/new` was refused (pi: "Authentication required"): no session
232 /// will open until the agent restarts.
233 session_failed: bool,
234 /// Counts spawns. A process's waiter cleans up the shared state only
235 /// while its generation is current, so one that finishes after a restart
236 /// can't disconnect the new process.
237 generation: u64,
238 /// The pane's previous session (`agent:sessionid`), offered to
239 /// `session/load` when the agent supports it.
240 resume_session_id: Option<String>,
241 /// The session's working directory.
242 session_cwd: String,
243 /// The `.mcp.json` the launch wrote in that directory, read at start.
244 mcp_json: Option<String>,
245 /// Its servers in ACP's shape, for what `initialize` said the agent takes.
246 mcp_servers: Vec<serde_json::Value>,
247 /// The agent's `cmd:env`, which `.mcp.json`'s `${VAR}` placeholders expand from
248 /// (then srv's own environment, which the agent inherits).
249 mcp_env: HashMap<String, String>,
250}
251
252/// What `submit_input` says to a slash command that arrives while a turn is running: a harness takes `/compact` only
253/// between turns, and queued behind other text it would no longer be a command. The caller waits for the turn's end.
254pub const TURN_RUNNING: &str = "a turn is running";
255
256/// Whether `text` is AgentMux's own `/compact` (with or without a focus).
257fn is_compact_command(text: &str) -> bool {
258 text.trim() == "/compact" || text.starts_with("/compact ")
259}
260
261/// A command the agent announced (`available_commands_update`): its name without a leading slash, and whether it takes
262/// text after it (the announcement carries an `input` hint).
263#[derive(Debug, Clone, PartialEq, Eq)]
264pub(super) struct AnnouncedCommand {
265 pub(super) name: String,
266 pub(super) takes_input: bool,
267}
268
269impl AcpInner {
270 /// `message` waits in the queue (`pending_prompt`) behind what is already there.
271 fn queue(&mut self, message: String) {
272 self.pending_prompt = Some(self.joined_with_queue(message));
273 }
274
275 /// The queue, if any, followed by `message`, taken as one text.
276 fn joined_with_queue(&mut self, message: String) -> String {
277 match self.pending_prompt.take() {
278 Some(earlier) => format!("{earlier}\n\n{message}"),
279 None => message,
280 }
281 }
282}
283
284/// AcpController manages an ACP-speaking agent process.
285pub struct AcpController {
286 #[allow(dead_code)]
287 tab_id: String,
288 block_id: String,
289 inner: Arc<Mutex<AcpInner>>,
290 broker: Option<Arc<mps::Broker>>,
291 event_bus: Option<Arc<EventBus>>,
292 mstore: Option<Arc<Store>>,
293 filestore: Option<Arc<FileStore>>,
294 health_monitor: Arc<TurnActivityTracker>,
295 /// Monotonically increasing JSON-RPC request ID.
296 next_rpc_id: Arc<AtomicU64>,
297 /// Every `session/prompt` request id that has been SENT but not yet
298 /// RESOLVED (by either a real `stopReason` completion or a JSON-RPC
299 /// `error` rejection). The turn is genuinely over only once this set
300 /// is empty — see `resolve_prompt_and_check_idle`'s doc comment for
301 /// why tracking the full set (not just "the latest" id) is necessary:
302 /// steering can leave multiple prompts outstanding at once, and
303 /// responses/rejections can arrive in any order relative to each
304 /// other and relative to new sends (independent stdin-writer and
305 /// stdout-reader tasks, no ordering guarantee between them). codex P2
306 /// on PR #2338 (twenty-seventh through thirtieth re-reviews).
307 outstanding_prompt_ids: Arc<Mutex<HashSet<u64>>>,
308 /// Serializes `ensure_started`, so two deliveries that find the agent
309 /// stopped can't both start it.
310 start_lock: Mutex<()>,
311 /// srv's auth key, for the agent's `agentmux-mcp` (`with_auth_key`):
312 /// srv removes it from its own environment at startup, so nothing else
313 /// would pass it on. Empty in tests.
314 auth_key: String,
315}
316
317impl AcpController {
318 /// The server auth key `agentmux-mcp` needs to reach srv (the same key
319 /// `build_persistent_spawn_env` gives Claude's).
320 pub fn with_auth_key(mut self, auth_key: String) -> Self {
321 self.auth_key = auth_key;
322 self
323 }
324
325 pub fn new(
326 tab_id: String,
327 block_id: String,
328 broker: Option<Arc<mps::Broker>>,
329 event_bus: Option<Arc<EventBus>>,
330 mstore: Option<Arc<Store>>,
331 filestore: Option<Arc<FileStore>>,
332 ) -> Self {
333 let health_monitor = Arc::new(TurnActivityTracker::for_block(block_id.clone(), broker.as_ref()));
334 Self {
335 tab_id,
336 block_id,
337 inner: Arc::new(Mutex::new(AcpInner {
338 proc_status: STATUS_INIT.to_string(),
339 proc_exit_code: 0,
340 status_version: 0,
341 session_id: None,
342 current_pid: None,
343 stdin_tx: None,
344 kill_tx: None,
345 pending_prompt: None,
346 announced_commands: None,
347 init_request_id: None,
348 session_request_id: None,
349 loading_session: None,
350 session_failed: false,
351 generation: 0,
352 resume_session_id: None,
353 session_cwd: String::new(),
354 mcp_json: None,
355 mcp_servers: Vec::new(),
356 mcp_env: HashMap::new(),
357 })),
358 broker,
359 event_bus,
360 mstore,
361 filestore,
362 health_monitor,
363 next_rpc_id: Arc::new(AtomicU64::new(1)),
364 outstanding_prompt_ids: Arc::new(Mutex::new(HashSet::new())),
365 start_lock: Mutex::new(()),
366 auth_key: String::new(),
367 }
368 }
369
370 fn next_id(&self) -> u64 {
371 self.next_rpc_id.fetch_add(1, Ordering::Relaxed)
372 }
373
374 fn set_status(inner: &mut AcpInner, status: &str) {
375 inner.proc_status = status.to_string();
376 inner.status_version += 1;
377 }
378
379 fn get_status_snapshot(&self) -> BlockControllerRuntimeStatus {
380 let inner = self.inner.lock().unwrap();
381 agent_runtime_status(
382 &self.block_id,
383 inner.status_version,
384 &inner.proc_status,
385 inner.proc_exit_code,
386 self.health_monitor.is_active_turn(),
387 )
388 .spawned_at(self.health_monitor.spawned_at_ms())
389 }
390
391 fn publish_status(&self) {
392 if let Some(ref broker) = self.broker {
393 let status = self.get_status_snapshot();
394 super::publish_controller_status(broker, &status);
395 }
396 }
397
398 pub(crate) fn is_running(&self) -> bool {
399 let inner = self.inner.lock().unwrap();
400 inner.stdin_tx.is_some()
401 }
402
403 /// Ends the agent's session so the next message opens a new one (`Agents fresh`): the process is stopped and the
404 /// pane's saved session id forgotten, so the launch that follows sends `session/new` and not `session/resume`.
405 /// Only between turns. Returns the old session id.
406 pub fn start_fresh_session(&self) -> Result<Option<String>, &'static str> {
407 let old = {
408 let mut inner = self.inner.lock().unwrap();
409 if self.health_monitor.is_active_turn() {
410 return Err("a turn is running");
411 }
412 inner.resume_session_id = None;
413 inner.session_id.take()
414 };
415 core::persist_session_id(&self.block_id, "", &self.mstore, &self.event_bus);
416 self.stop(true, STATUS_DONE).map_err(|_| "the agent's process could not be stopped")?;
417 Ok(old)
418 }
419
420 /// Build a JSON-RPC 2.0 request.
421 fn make_request(&self, method: &str, params: serde_json::Value) -> String {
422 let id = self.next_id();
423 serde_json::json!({
424 "jsonrpc": "2.0",
425 "id": id,
426 "method": method,
427 "params": params,
428 }).to_string()
429 }
430
431 /// Build a JSON-RPC 2.0 notification (no id field).
432 fn make_notification(&self, method: &str, params: serde_json::Value) -> String {
433 serde_json::json!({
434 "jsonrpc": "2.0",
435 "method": method,
436 "params": params,
437 }).to_string()
438 }
439
440 /// Spawn the ACP agent process and perform the initialize handshake.
441 fn spawn_process(&self, cli_command: String, cli_args: Vec<String>, working_dir: String, env_vars: HashMap<String, String>) -> Result<(), String> {
442 let (mut child, pid) = self.launch_child(&cli_command, &cli_args, &working_dir, &env_vars)?;
443
444 let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<bool>();
445 let stdin = child.stdin.take()
446 .ok_or_else(|| format!("[acp] stdin not captured for block {}", self.block_id))?;
447 let stdout = child.stdout.take()
448 .ok_or_else(|| format!("[acp] stdout not captured for block {}", self.block_id))?;
449 let stderr = child.stderr.take();
450
451 if let Some(stderr_pipe) = stderr {
452 self.spawn_stderr_drain(stderr_pipe);
453 }
454 let msg_rx = self.register_running(pid, kill_tx);
455 self.spawn_stdin_writer(stdin, msg_rx);
456 self.spawn_stdout_reader(stdout);
457 self.spawn_process_waiter(child, kill_rx);
458 self.send_initialize(&working_dir);
459
460 Ok(())
461 }
462}
463
464/// A meta value that is a string array, or a JSON string encoding one.
465pub(super) fn meta_string_list(meta: &super::super::obj::MetaMapType, key: &str) -> Vec<String> {
466 match meta.get(key) {
467 Some(serde_json::Value::Array(values)) => values
468 .iter()
469 .filter_map(|v| v.as_str().map(str::to_string))
470 .collect(),
471 Some(serde_json::Value::String(s)) => serde_json::from_str(s).unwrap_or_default(),
472 _ => Vec::new(),
473 }
474}
475
476
477impl AcpController {
478 /// A new process takes over the controller: the generation moves on, and
479 /// the prompts the previous process never answered are forgotten. Its
480 /// waiter, which sees the new generation, no longer clears them; left
481 /// there they would keep the turn active for good.
482 fn begin_process(&self) -> u64 {
483 self.outstanding_prompt_ids.lock().unwrap().clear();
484 self.health_monitor.set_active_turn(false);
485 let mut inner = self.inner.lock().unwrap();
486 inner.generation += 1;
487 inner.generation
488 }
489
490 /// Start the agent again if its process has exited, from the pane's
491 /// meta; a no-op when it is running. One start at a time: a second
492 /// delivery waits here and then finds it running.
493 pub fn ensure_started(&self, block_meta: super::super::obj::MetaMapType) -> Result<(), String> {
494 let _one_at_a_time = self.start_lock.lock().unwrap();
495 if self.is_running() {
496 return Ok(());
497 }
498 Controller::start(self, block_meta, None, false)
499 }
500
501 /// A user message from `agentinput` / `agent.send` (`run_agent_turn`):
502 /// sent as `session/prompt`, then acknowledged the way the other
503 /// controllers acknowledge theirs, so the pane stops showing it as pending.
504 pub fn send_message(&self, message: String, message_id: Option<&str>) -> Result<SendOutcome, String> {
505 self.send_message_from(message, message_id, None)
506 }
507
508 /// [`send_message`](Self::send_message), saying where the message came from. ACP puts the user's
509 /// words in no frame of its own, so srv stores them as a user record with that origin
510 /// (`prompt_record`) once the agent has them; with no `record` nothing is stored.
511 pub fn send_message_from(&self, message: String, message_id: Option<&str>, record: Option<&RecordOrigin>) -> Result<SendOutcome, String> {
512 let words = record.map(|_| message.clone());
513 let outcome = self.submit_input(BlockInputUnion::data(message.into_bytes()))?;
514 if let (Some(id), Some(broker)) = (message_id, self.broker.as_ref()) {
515 super::publish_message_accepted(broker, &self.block_id, id);
516 }
517 if let Some(words) = words {
518 let records = super::prompt_record::PromptRecords { broker: self.broker.clone(), filestore: self.filestore.clone(), mstore: self.mstore.clone() };
519 records.write(&self.block_id, &words, message_id.is_some(), record);
520 }
521 Ok(outcome)
522 }
523
524 /// [`Controller::send_input`], saying whether the agent has the message or it waits: for the pane to
525 /// start (`Deferred`: no session yet) or for the turn in flight to end.
526 fn submit_input(&self, input: BlockInputUnion) -> Result<SendOutcome, String> {
527 if let Some(data) = input.input_data {
528 // Raw input from the frontend — treat as a user message.
529 // The frontend sends the user prompt as UTF-8 bytes.
530 let message = String::from_utf8_lossy(&data).to_string();
531 if message.trim().is_empty() {
532 return Ok(SendOutcome::Sent);
533 }
534
535 if !self.is_running() {
536 // Process not running — stash as pending so start() picks it up.
537 let mut inner = self.inner.lock().unwrap();
538 inner.queue(message);
539 return Err("ACP process not running — message queued for next start()".to_string());
540 }
541
542 // The turn is reserved in the same lock hold that reads the session id, so `start_fresh_session`, which
543 // checks for an idle turn under this lock, either sees the turn as active and refuses, or runs first and
544 // leaves no session here, so the message below waits for the next launch (#47458).
545 let (session_id, prompt_id, message) = {
546 let mut inner = self.inner.lock().unwrap();
547 match inner.session_id.clone() {
548 Some(sid) => {
549 // A turn is in flight: an ACP agent takes one prompt at a time (dsh refuses a second with
550 // "a prompt is already in flight", and the message is lost), so the message waits for the
551 // turn's end (`flush_queued_prompt`). Checked with the outstanding set locked, so the turn
552 // cannot end between this check and the queueing and strand the message.
553 {
554 let outstanding = self.outstanding_prompt_ids.lock().unwrap();
555 if !outstanding.is_empty() {
556 if is_compact_command(&message) {
557 return Err(TURN_RUNNING.to_string());
558 }
559 inner.queue(message);
560 return Ok(SendOutcome::Deferred);
561 }
562 }
563 // Not built via make_request: the id must be captured so it can be tracked as outstanding
564 // (see outstanding_prompt_ids's doc comment). Inserted before the turn is marked active
565 // and before the enqueue below, so the prompt's answer always finds both.
566 let prompt_id = self.next_id();
567 self.outstanding_prompt_ids.lock().unwrap().insert(prompt_id);
568 // Atomic read-and-write (as persistent/input.rs's guard), and before the stdin enqueue: a fast
569 // agent can have the reader publish its `stopReason` before this thread would reach the mark (#2338).
570 self.health_monitor.mark_turn_active_returning_was_active();
571 // What waited for a turn that has since ended goes ahead of this message, in the one prompt:
572 // sent apart, the queued text would be a second prompt while this one is in flight.
573 // `/compact` goes alone, as a command: what waited goes after it, at the turn's end.
574 let message = if is_compact_command(&message) { self.carries_compaction(prompt_id); message } else { inner.joined_with_queue(message) };
575 (sid, prompt_id, message)
576 }
577 None if inner.session_failed => {
578 return Err("The agent couldn't open a session (see the error above). Fix that, then restart the agent.".to_string());
579 }
580 None if is_compact_command(&message) => {
581 return Err("the agent's session is not open yet".to_string());
582 }
583 None => {
584 // The handshake hasn't opened the session yet (the
585 // startup message is sent right after launch): queue
586 // it; the stdout reader sends it once the session
587 // exists. Sent with no session id, the agent would
588 // reject it and the message would be lost.
589 inner.queue(message);
590 return Ok(SendOutcome::Deferred);
591 }
592 }
593 };
594 let req = serde_json::json!({
595 "jsonrpc": "2.0",
596 "id": prompt_id,
597 "method": "session/prompt",
598 "params": prompt_params(&session_id, &message),
599 }).to_string();
600 // Publish the turn_active flip, mirroring persistent/queue.rs's
601 // send_message and persistent/input.rs's send_user_message
602 // (which both call self.publish_status() right after the same
603 // atomic turn-active mark). Without this,
604 // wasTurnActive === false left over from an EARLIER turn's
605 // end-of-turn publish (or the initial spawn publish) is
606 // indistinguishable from genuine current idleness — a `/login`
607 // that defers a controller refresh during THIS turn, followed
608 // by a premature frontend Done transition, would see
609 // isBackendTurnConfirmedIdle() read true from that stale
610 // signal and force-restart the controller, killing the
611 // actually-active turn (#2338).
612 self.publish_status();
613
614 self.write_prompt(prompt_id, req)?;
615 }
616
617 if let Some(sig) = input.sig_name {
618 if sig == "SIGTERM" || sig == "SIGINT" {
619 return self.stop(true, STATUS_DONE).map(|()| SendOutcome::Sent);
620 }
621 }
622
623 Ok(SendOutcome::Sent)
624 }
625
626 /// The `/compact` written as prompt `prompt_id` is the one a compaction in progress waits for.
627 fn carries_compaction(&self, prompt_id: u64) {
628 crate::backend::context_reading::acp_compaction_carried_by(&self.block_id, prompt_id);
629 }
630
631 /// Write the prompt `prompt_id` to the agent's stdin. When that fails, the prompt is taken out of the
632 /// outstanding set again and the turn is over unless another prompt is still in flight.
633 fn write_prompt(&self, prompt_id: u64, req: String) -> Result<(), String> {
634 let send_result = {
635 let inner = self.inner.lock().unwrap();
636 if let Some(ref tx) = inner.stdin_tx {
637 tx.try_send(req)
638 .map_err(|e| format!("ACP stdin send failed: {e}"))
639 } else {
640 // stdin_tx can vanish between the is_running() check
641 // above and this re-lock — e.g. a concurrent stop() or
642 // controller resync clearing it in between. Treating
643 // this as success (the old behavior) silently lost the
644 // message (never actually enqueued anywhere) while
645 // still marking the turn active and leaving prompt_id
646 // permanently outstanding — nothing will ever resolve
647 // it. Handling it identically to a try_send failure
648 // reuses the existing rollback below. codex P1 on
649 // PR #2338 (thirty-fourth re-review).
650 Err("ACP process not running — stdin sender vanished after the initial check".to_string())
651 }
652 };
653 if let Err(e) = send_result {
654 // try_send can fail (channel full, or the stdin writer task
655 // already exited because the process died) — no turn
656 // actually starts for THIS prompt. Remove it from the
657 // outstanding set (it was never really sent) and only
658 // declare the turn over if NOTHING else is left outstanding
659 // — a turn ALREADY active from an earlier successful send
660 // (mid-turn steering) must not be clobbered by this failed
661 // one. This single emptiness check replaces what used to be
662 // two separate, easy-to-desync mechanisms: a `was_active`-
663 // conditioned rollback, and a latest/previous-id
664 // compare-and-swap that could still strand turn_active
665 // under out-of-order responses (codex P2 on PR #2338,
666 // twenty-seventh through thirtieth re-reviews).
667 let now_empty = {
668 let mut outstanding = self.outstanding_prompt_ids.lock().unwrap();
669 outstanding.remove(&prompt_id);
670 outstanding.is_empty()
671 };
672 if now_empty {
673 self.health_monitor.set_active_turn(false);
674 self.publish_status();
675 }
676 return Err(e);
677 }
678 Ok(())
679 }
680
681 /// Whether `Agents compact` can compact this agent: the harness announced a `compact` command, and `Ok(takes_input)` says
682 /// whether the command takes a focus. The refusal says what to do instead.
683 pub fn compaction_request(&self) -> Result<bool, &'static str> {
684 let inner = self.inner.lock().unwrap();
685 let found = inner.announced_commands.as_ref().and_then(|cmds| cmds.iter().find(|c| c.name == "compact"));
686 found.map(|c| c.takes_input).ok_or("unsupported: this harness announced no compaction command; call Agents fresh with a handoff to start a new session instead")
687 }
688
689 /// Whether this agent offers compaction: it announced a `compact` command.
690 pub fn offers_compaction(&self) -> bool {
691 self.compaction_request().is_ok()
692 }
693
694 /// A running agent with an open session, for tests of the paths above it.
695 #[cfg(test)]
696 pub(super) fn set_session_for_test(&self, stdin: mpsc::Sender<String>, session_id: &str) {
697 let mut inner = self.inner.lock().unwrap();
698 inner.stdin_tx = Some(stdin);
699 inner.session_id = Some(session_id.to_string());
700 }
701
702 /// The env this block's ACP process is spawned with: `cmd:env` (either
703 /// shape), with the block's row UID + token carried onto it — identity
704 /// M4b-2. agentmux-mcp, which ACP agents get in `session/new`
705 /// (`acp_mcp`), runs as the agent's child and so carries it.
706 fn spawn_env(&self, block_meta: &super::super::obj::MetaMapType) -> HashMap<String, String> {
707 session_agent_env(block_meta, &self.block_id, &self.mstore, &self.auth_key)
708 }
709}
710
711/// The env a session agent's process (ACP or MSP) is spawned with: see
712/// `AcpController::spawn_env`.
713pub(super) fn session_agent_env(
714 block_meta: &super::super::obj::MetaMapType,
715 block_id: &str,
716 mstore: &Option<Arc<Store>>,
717 auth_key: &str,
718) -> HashMap<String, String> {
719 let mut env_vars = meta_string_map(block_meta, super::META_KEY_CMD_ENV);
720 if let Some(mstore) = mstore {
721 crate::backend::spawn_env::block_identity::carry_block_identity_env(mstore, block_id, &mut env_vars);
722 }
723 // The workspace the "Your workspace" Operator Config entry points at.
724 crate::backend::spawn_env::block_identity::carry_agent_workdir_env(&mut env_vars, block_meta);
725 // The agent's `agentmux-mcp` reaches srv with these, as on the
726 // persistent path: reserved values, so they replace any in `cmd:env`.
727 if auth_key.is_empty() {
728 env_vars.remove("AGENTMUX_AUTH_KEY");
729 } else {
730 env_vars.insert("AGENTMUX_AUTH_KEY".to_string(), auth_key.to_string());
731 }
732 env_vars.insert("AGENTMUX_BLOCKID".to_string(), block_id.to_string());
733 crate::backend::spawn_env::workspaces::record_launch_workspace(block_id, &env_vars);
734 // The tool dirs ahead of the system PATH, as on the persistent path: the build-slot shims
735 // live there, and an ACP agent's `cargo test` must reach them.
736 crate::backend::tool_store::prepend_agent_tools_path(&mut env_vars);
737 crate::backend::gh_guard::apply_gh_guard(&mut env_vars);
738 crate::backend::git_program_settings::apply_for_spawn(&mut env_vars, block_meta);
739 crate::backend::account_login_guard::strip_account_login(&mut env_vars);
740 env_vars
741}
742
743impl Controller for AcpController {
744 fn start(
745 &self,
746 block_meta: super::super::obj::MetaMapType,
747 _rt_opts: Option<serde_json::Value>,
748 _force: bool,
749 ) -> Result<(), String> {
750 crate::backend::mcp_folder_rule::not_refused(&block_meta)?;
751 // Extract spawn config from block metadata
752 let cmd = super::super::obj::meta_get_string(&block_meta, super::META_KEY_CMD, "");
753 let cwd = super::super::obj::meta_get_string(&block_meta, super::META_KEY_CMD_CWD, "");
754 if cmd.is_empty() {
755 return Err("ACP controller: no cmd specified in block meta".to_string());
756 }
757
758 // `cmd:args` / `cmd:env` as `agent.open` stores them (an array and an
759 // object) or as a JSON string — before M4b-2 only the string form was
760 // read, so an `agent.open` launch lost both (spec §6.5.8).
761 let args = meta_string_list(&block_meta, super::META_KEY_CMD_ARGS);
762 let resume = super::super::obj::meta_get_string(&block_meta, super::core::META_SESSION_ID, "");
763 {
764 // A restart (the agent exited) starts a new handshake: a prompt
765 // must wait for the new session, never go to the old one.
766 let mut inner = self.inner.lock().unwrap();
767 inner.resume_session_id = Some(resume).filter(|s| !s.is_empty());
768 inner.session_id = None;
769 inner.init_request_id = None;
770 inner.session_request_id = None;
771 inner.loading_session = None;
772 inner.session_failed = false;
773 inner.announced_commands = None;
774 }
775 // AgentMux's MCP servers: the config the launch wrote for this agent, which is
776 // outside the working directory when that is the user's own project (#3680).
777 // None when there is none.
778 let mcp_json = crate::backend::mcp_config_file::read_for_turn(&session_cwd(&cwd));
779 let mut env_vars = self.spawn_env(&block_meta);
780 if let Some(pi) = crate::backend::providers::pi_beside_pi_acp(&cmd) {
781 env_vars.entry("PI_ACP_PI_COMMAND".to_string()).or_insert(pi);
782 }
783 let provider = super::super::obj::meta_get_string(&block_meta, "agentProvider", "");
784 super::acp_prelaunch::prepare_env(&provider, &mut env_vars);
785 super::acp_prelaunch::prepare(&provider, &env_vars, &session_cwd(&cwd));
786 super::acp_prelaunch::check_runtime(&provider, &env_vars)?;
787 {
788 let mut inner = self.inner.lock().unwrap();
789 inner.mcp_json = mcp_json;
790 inner.mcp_env = env_vars.clone();
791 }
792
793 self.spawn_process(cmd, args, cwd, env_vars)
794 }
795
796 fn stop(&self, _graceful: bool, _new_status: &str) -> Result<(), String> {
797 // Send shutdown request before killing
798 {
799 let inner = self.inner.lock().unwrap();
800 if let Some(ref tx) = inner.stdin_tx {
801 let shutdown = self.make_request("shutdown", serde_json::json!({}));
802 let exit = self.make_notification("exit", serde_json::json!({}));
803 for (label, msg) in [("shutdown", shutdown), ("exit", exit)] {
804 if tx.try_send(msg).is_err() {
805 tracing::debug!(block_id = %self.block_id, method = label, "[acp] shutdown message dropped — process likely already gone");
806 }
807 }
808 }
809 }
810
811 // Kill the process
812 let kill_tx = {
813 let mut inner = self.inner.lock().unwrap();
814 inner.stdin_tx = None;
815 inner.kill_tx.take()
816 };
817 if let Some(tx) = kill_tx {
818 let _ = tx.send(true);
819 }
820
821 {
822 let mut inner = self.inner.lock().unwrap();
823 Self::set_status(&mut inner, STATUS_DONE);
824 }
825 self.publish_status();
826 Ok(())
827 }
828
829 fn get_runtime_status(&self) -> BlockControllerRuntimeStatus {
830 self.get_status_snapshot()
831 }
832
833 fn send_input(&self, input: BlockInputUnion, _seq: Option<u64>) -> Result<(), String> {
834 self.submit_input(input).map(|_| ())
835 }
836
837 fn turn_tracker(&self) -> Option<Arc<TurnActivityTracker>> {
838 Some(Arc::clone(&self.health_monitor))
839 }
840
841 fn controller_type(&self) -> &str {
842 BLOCK_CONTROLLER_ACP
843 }
844
845 fn block_id(&self) -> &str {
846 &self.block_id
847 }
848
849 fn as_any(&self) -> &dyn std::any::Any {
850 self
851 }
852}
853
854#[path = "acp_spawn.rs"]
855pub mod spawn_steps;
856
857#[cfg(test)]
858#[path = "acp_tests.rs"]
859mod tests;