agentmux 0.1.0

Multi-agent coordination runtime with inter-agent messaging across CLI, MCP, tmux, and ACP.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use std::{
    io::{Read, Write},
    os::fd::AsRawFd,
    path::Path,
    process::{Child, ChildStdin, ChildStdout, Command, Stdio},
    thread,
    time::{Duration, Instant},
};

use serde_json::{Value, json};

use super::super::ACP_PROTOCOL_VERSION;

const ACP_CLIENT_NAME: &str = "agentmux-relay";
const ACP_CLIENT_VERSION: &str = env!("CARGO_PKG_VERSION");
const ACP_LOAD_POST_RESPONSE_DRAIN_TIMEOUT: Duration = Duration::from_millis(200);
// Prompt responses can arrive before follow-on `session/update` notifications.
// Keep a small post-response drain window so late updates are still observed
// and persisted for look snapshots across slower CI/runtime scheduling.
const ACP_PROMPT_POST_RESPONSE_DRAIN_TIMEOUT: Duration = Duration::from_millis(250);

type DispatchObserver<'a> = &'a mut dyn FnMut();
type SnapshotObserver<'a> = &'a mut dyn FnMut(&[String]) -> Result<(), String>;

struct RequestObservers<'a> {
    prompt_session_id: Option<String>,
    post_response_drain_timeout: Option<Duration>,
    on_dispatched: Option<DispatchObserver<'a>>,
    on_snapshot_lines: Option<SnapshotObserver<'a>>,
}

#[derive(Debug)]
pub(super) enum AcpRequestError {
    Failed(String),
    Timeout(Duration),
    ConnectionClosed {
        reason: String,
        first_activity_observed: bool,
    },
}

#[derive(Debug)]
pub(super) struct AcpPromptCompletion {
    pub stop_reason: String,
    pub first_activity_observed: bool,
}

#[derive(Debug)]
pub(super) struct AcpRequestResult {
    pub result: Value,
    pub first_activity_observed: bool,
}

pub(super) struct AcpStdioClient {
    child: Child,
    stdin: ChildStdin,
    stdout: ChildStdout,
    read_buffer: Vec<u8>,
    next_id: u64,
    snapshot_line_buffer: Vec<String>,
}

impl AcpStdioClient {
    pub(super) fn spawn(command_template: &str, working_directory: &Path) -> Result<Self, String> {
        let mut command = Command::new("sh");
        command
            .arg("-lc")
            .arg(command_template)
            .current_dir(working_directory)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null());
        let mut child = command
            .spawn()
            .map_err(|source| format!("spawn ACP stdio command failed: {source}"))?;
        let stdin = child
            .stdin
            .take()
            .ok_or_else(|| "ACP stdio child stdin unavailable".to_string())?;
        let stdout = child
            .stdout
            .take()
            .ok_or_else(|| "ACP stdio child stdout unavailable".to_string())?;
        set_nonblocking(stdout.as_raw_fd(), true)?;
        Ok(Self {
            child,
            stdin,
            stdout,
            read_buffer: Vec::new(),
            next_id: 1,
            snapshot_line_buffer: Vec::new(),
        })
    }

    pub(super) fn initialize(&mut self) -> Result<Value, String> {
        self.request(
            "initialize",
            json!({
                "protocolVersion": ACP_PROTOCOL_VERSION,
                "clientCapabilities": {
                    "fs": {
                        "readTextFile": false,
                        "writeTextFile": false,
                    },
                    "terminal": false,
                },
                "clientInfo": {
                    "name": ACP_CLIENT_NAME,
                    "version": ACP_CLIENT_VERSION,
                },
            }),
            None,
            RequestObservers {
                prompt_session_id: None,
                post_response_drain_timeout: None,
                on_dispatched: None,
                on_snapshot_lines: None,
            },
        )
        .map(|value| value.result)
        .map_err(|error| match error {
            AcpRequestError::Failed(reason) => reason,
            AcpRequestError::Timeout(timeout) => {
                format!("ACP initialize timed out after {}ms", timeout.as_millis())
            }
            AcpRequestError::ConnectionClosed { reason, .. } => reason,
        })
    }

    pub(super) fn new_session(&mut self, working_directory: &Path) -> Result<String, String> {
        let result = self
            .request(
                "session/new",
                json!({
                    "cwd": working_directory.display().to_string(),
                    "mcpServers": [],
                }),
                None,
                RequestObservers {
                    prompt_session_id: None,
                    post_response_drain_timeout: Some(ACP_LOAD_POST_RESPONSE_DRAIN_TIMEOUT),
                    on_dispatched: None,
                    on_snapshot_lines: None,
                },
            )
            .map(|value| value.result)
            .map_err(|error| match error {
                AcpRequestError::Failed(reason) => reason,
                AcpRequestError::Timeout(timeout) => {
                    format!("ACP session/new timed out after {}ms", timeout.as_millis())
                }
                AcpRequestError::ConnectionClosed { reason, .. } => reason,
            })?;
        result
            .get("sessionId")
            .and_then(Value::as_str)
            .map(ToString::to_string)
            .ok_or_else(|| "ACP session/new response missing result.sessionId".to_string())
    }

    pub(super) fn load_session(
        &mut self,
        session_id: &str,
        working_directory: &Path,
    ) -> Result<(), String> {
        let _ = self
            .request(
                "session/load",
                json!({
                    "sessionId": session_id,
                    "cwd": working_directory.display().to_string(),
                    "mcpServers": [],
                }),
                None,
                RequestObservers {
                    prompt_session_id: None,
                    post_response_drain_timeout: Some(ACP_LOAD_POST_RESPONSE_DRAIN_TIMEOUT),
                    on_dispatched: None,
                    on_snapshot_lines: None,
                },
            )
            .map(|value| value.result)
            .map_err(|error| match error {
                AcpRequestError::Failed(reason) => reason,
                AcpRequestError::Timeout(timeout) => {
                    format!("ACP session/load timed out after {}ms", timeout.as_millis())
                }
                AcpRequestError::ConnectionClosed { reason, .. } => reason,
            })?;
        Ok(())
    }

    pub(super) fn prompt<'a>(
        &mut self,
        session_id: &str,
        prompt: &str,
        timeout: Option<Duration>,
        on_dispatched: Option<DispatchObserver<'a>>,
        on_snapshot_lines: Option<SnapshotObserver<'a>>,
    ) -> Result<AcpPromptCompletion, AcpRequestError> {
        let result = self.request(
            "session/prompt",
            json!({
                "sessionId": session_id,
                "prompt": [
                    {
                        "type": "text",
                        "text": prompt,
                    }
                ],
            }),
            timeout,
            RequestObservers {
                prompt_session_id: Some(session_id.to_string()),
                post_response_drain_timeout: Some(ACP_PROMPT_POST_RESPONSE_DRAIN_TIMEOUT),
                on_dispatched,
                on_snapshot_lines,
            },
        )?;
        result
            .result
            .get("stopReason")
            .and_then(Value::as_str)
            .map(|stop_reason| AcpPromptCompletion {
                stop_reason: stop_reason.to_string(),
                first_activity_observed: result.first_activity_observed,
            })
            .ok_or_else(|| {
                AcpRequestError::Failed(
                    "ACP session/prompt response missing result.stopReason".to_string(),
                )
            })
    }

    pub(super) fn take_snapshot_lines(&mut self) -> Vec<String> {
        std::mem::take(&mut self.snapshot_line_buffer)
    }

    fn request(
        &mut self,
        method: &str,
        params: Value,
        timeout: Option<Duration>,
        mut observers: RequestObservers<'_>,
    ) -> Result<AcpRequestResult, AcpRequestError> {
        let request_id = self.next_id;
        self.next_id = self.next_id.saturating_add(1);
        let message = serde_json::to_string(&json!({
            "jsonrpc": "2.0",
            "id": request_id,
            "method": method,
            "params": params,
        }))
        .map_err(|source| {
            AcpRequestError::Failed(format!("serialize ACP request failed: {source}"))
        })?;
        self.stdin
            .write_all(message.as_bytes())
            .and_then(|_| self.stdin.write_all(b"\n"))
            .and_then(|_| self.stdin.flush())
            .map_err(|source| {
                AcpRequestError::Failed(format!("write ACP request failed: {source}"))
            })?;
        if let Some(callback) = observers.on_dispatched.as_mut() {
            callback();
        }

        let mut first_activity_observed = false;
        let mut read_timeout = timeout;
        loop {
            let line = match self.read_response_line(read_timeout) {
                Ok(line) => line,
                Err(AcpRequestError::Failed(reason)) => {
                    return Err(AcpRequestError::ConnectionClosed {
                        reason,
                        first_activity_observed,
                    });
                }
                Err(error) => return Err(error),
            };
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }
            let decoded = serde_json::from_str::<Value>(trimmed).map_err(|source| {
                AcpRequestError::Failed(format!("parse ACP response failed: {source}"))
            })?;
            if decoded.get("id") != Some(&json!(request_id)) {
                let observed_update = self.capture_update_snapshot_lines(
                    &decoded,
                    observers.prompt_session_id.as_deref(),
                    &mut observers.on_snapshot_lines,
                )?;
                if (observed_update
                    || self.observe_permission_request_activity(
                        &decoded,
                        observers.prompt_session_id.as_deref(),
                    ))
                    && !first_activity_observed
                {
                    first_activity_observed = true;
                    read_timeout = None;
                }
                continue;
            }
            if let Some(error) = decoded.get("error") {
                return Err(AcpRequestError::Failed(error.to_string()));
            }
            if observers.prompt_session_id.is_some() && !first_activity_observed {
                first_activity_observed = true;
            }
            if let Some(drain_timeout) = observers.post_response_drain_timeout
                && self.drain_post_response_notifications(
                    observers.prompt_session_id.as_deref(),
                    drain_timeout,
                    &mut observers.on_snapshot_lines,
                )?
            {
                first_activity_observed = true;
            }
            return Ok(AcpRequestResult {
                result: decoded.get("result").cloned().unwrap_or(Value::Null),
                first_activity_observed,
            });
        }
    }

    fn drain_post_response_notifications(
        &mut self,
        session_id: Option<&str>,
        timeout: Duration,
        on_snapshot_lines: &mut Option<SnapshotObserver<'_>>,
    ) -> Result<bool, AcpRequestError> {
        let mut observed = false;
        while let Ok(line) = self.read_response_line(Some(timeout)) {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }
            let decoded = match serde_json::from_str::<Value>(trimmed) {
                Ok(value) => value,
                Err(_) => continue,
            };
            if self.capture_update_snapshot_lines(&decoded, session_id, on_snapshot_lines)?
                || self.observe_permission_request_activity(&decoded, session_id)
            {
                observed = true;
            }
        }
        Ok(observed)
    }

    fn capture_update_snapshot_lines(
        &mut self,
        value: &Value,
        session_id: Option<&str>,
        on_snapshot_lines: &mut Option<SnapshotObserver<'_>>,
    ) -> Result<bool, AcpRequestError> {
        if value.get("method").and_then(Value::as_str) != Some("session/update") {
            return Ok(false);
        }
        let params = value.get("params").unwrap_or(&Value::Null);
        if let Some(expected_session_id) = session_id
            && let Some(observed_session_id) = params.get("sessionId").and_then(Value::as_str)
            && observed_session_id != expected_session_id
        {
            return Ok(false);
        }
        let mut captured_lines = Vec::new();
        collect_text_lines_from_value(params, &mut captured_lines);
        if captured_lines.is_empty() {
            return Ok(true);
        }
        self.snapshot_line_buffer
            .extend(captured_lines.iter().cloned());
        if let Some(callback) = on_snapshot_lines.as_mut() {
            callback(captured_lines.as_slice()).map_err(AcpRequestError::Failed)?;
        }
        Ok(true)
    }

    fn observe_permission_request_activity(&self, value: &Value, session_id: Option<&str>) -> bool {
        if value.get("method").and_then(Value::as_str) != Some("session/request_permission") {
            return false;
        }
        let params = value.get("params").unwrap_or(&Value::Null);
        if let Some(expected_session_id) = session_id
            && let Some(observed_session_id) = params.get("sessionId").and_then(Value::as_str)
            && observed_session_id != expected_session_id
        {
            return false;
        }
        true
    }

    fn read_response_line(&mut self, timeout: Option<Duration>) -> Result<String, AcpRequestError> {
        let deadline = timeout.map(|value| Instant::now() + value);
        let mut chunk = [0_u8; 4096];
        loop {
            if let Some(newline_index) = self.read_buffer.iter().position(|value| *value == b'\n') {
                let mut line = self.read_buffer.drain(..=newline_index).collect::<Vec<_>>();
                if matches!(line.last(), Some(b'\n')) {
                    line.pop();
                }
                if matches!(line.last(), Some(b'\r')) {
                    line.pop();
                }
                return String::from_utf8(line).map_err(|source| {
                    AcpRequestError::Failed(format!("decode ACP response failed: {source}"))
                });
            }

            match self.stdout.read(&mut chunk) {
                Ok(0) => {
                    let exit_code = self
                        .child
                        .try_wait()
                        .ok()
                        .flatten()
                        .and_then(|status| status.code());
                    return Err(AcpRequestError::Failed(format!(
                        "ACP peer closed stdout (exit_code={exit_code:?})"
                    )));
                }
                Ok(count) => self.read_buffer.extend_from_slice(&chunk[..count]),
                Err(source) if source.kind() == std::io::ErrorKind::WouldBlock => {
                    if let Some(limit) = deadline
                        && Instant::now() >= limit
                    {
                        return Err(AcpRequestError::Timeout(
                            timeout.unwrap_or(Duration::from_millis(0)),
                        ));
                    }
                    if let Ok(Some(status)) = self.child.try_wait() {
                        return Err(AcpRequestError::Failed(format!(
                            "ACP peer exited before response (exit_code={:?})",
                            status.code()
                        )));
                    }
                    thread::sleep(Duration::from_millis(10));
                }
                Err(source) if source.kind() == std::io::ErrorKind::Interrupted => continue,
                Err(source) => {
                    return Err(AcpRequestError::Failed(format!(
                        "read ACP response failed: {source}"
                    )));
                }
            }
        }
    }
}

fn collect_text_lines_from_value(value: &Value, output: &mut Vec<String>) {
    match value {
        Value::Array(values) => {
            for value in values {
                collect_text_lines_from_value(value, output);
            }
        }
        Value::Object(values) => {
            if let Some(text) = values.get("text").and_then(Value::as_str) {
                append_text_lines(text, output);
            }
            for value in values.values() {
                collect_text_lines_from_value(value, output);
            }
        }
        _ => {}
    }
}

fn append_text_lines(text: &str, output: &mut Vec<String>) {
    for line in text.split('\n') {
        let normalized = line.trim_end_matches('\r');
        if !normalized.is_empty() {
            output.push(normalized.to_string());
        }
    }
}

fn set_nonblocking(file_descriptor: i32, enable: bool) -> Result<(), String> {
    // SAFETY: `fcntl` is called with a live file descriptor owned by this
    // process. The command and arguments follow libc contract.
    let flags = unsafe { libc::fcntl(file_descriptor, libc::F_GETFL) };
    if flags < 0 {
        return Err(std::io::Error::last_os_error().to_string());
    }
    let updated_flags = if enable {
        flags | libc::O_NONBLOCK
    } else {
        flags & !libc::O_NONBLOCK
    };
    // SAFETY: `fcntl` receives the same valid descriptor and bitflag payload.
    let result = unsafe { libc::fcntl(file_descriptor, libc::F_SETFL, updated_flags) };
    if result < 0 {
        return Err(std::io::Error::last_os_error().to_string());
    }
    Ok(())
}