agentmux 0.6.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
use std::{
    path::Path,
    thread,
    time::{Duration, Instant},
};

use regex::Regex;
use serde_json::json;

use crate::configuration::PromptReadinessTemplate;
use crate::runtime::signals::shutdown_requested;

use super::super::tmux::{
    capture_pane_snapshot, emit_delivery_diagnostic, operator_interaction_active,
    resolve_active_pane_target, resolve_cursor_column, resolve_window_activity_marker,
    sanitize_diagnostic_text,
};

const QUIET_WINDOW_MS_DEFAULT: u64 = 750;
const QUIESCENCE_TIMEOUT_MS_DEFAULT: u64 = 30_000;
// TODO(refactor-acp-background-reader follow-up): drop this constant and the
// `acp_turn_timeout_ms` param plumbing entirely. The relay no longer
// enforces a turn timeout for ACP prompts (fire-and-forget; agent death
// detected via reader EOF). Kept for API back-compat until the MCP param
// surface is updated.
#[allow(dead_code)]
const ACP_TURN_TIMEOUT_MS_DEFAULT: u64 = 120_000;
const PROMPT_INSPECT_LINES_DEFAULT: usize = 3;
const PROMPT_INSPECT_LINES_MAX: usize = 40;

#[derive(Clone, Copy, Debug)]
pub(in crate::relay) struct QuiescenceOptions {
    pub quiet_window: Duration,
    pub quiescence_timeout: Option<Duration>,
    // TODO(refactor-acp-background-reader follow-up): field is now a no-op.
    // Drop it together with the `acp_turn_timeout_ms` MCP/CLI param.
    #[allow(dead_code)]
    pub acp_turn_timeout_override: Option<Duration>,
}

impl Default for QuiescenceOptions {
    fn default() -> Self {
        Self {
            quiet_window: Duration::from_millis(QUIET_WINDOW_MS_DEFAULT),
            quiescence_timeout: Some(Duration::from_millis(QUIESCENCE_TIMEOUT_MS_DEFAULT)),
            acp_turn_timeout_override: None,
        }
    }
}

impl QuiescenceOptions {
    pub(in crate::relay) fn for_sync(
        quiet_window_ms: Option<u64>,
        quiescence_timeout_ms: Option<u64>,
        acp_turn_timeout_ms: Option<u64>,
    ) -> Self {
        Self {
            quiet_window: Duration::from_millis(
                quiet_window_ms
                    .filter(|value| *value > 0)
                    .unwrap_or(QUIET_WINDOW_MS_DEFAULT),
            ),
            quiescence_timeout: Some(Duration::from_millis(
                quiescence_timeout_ms
                    .filter(|value| *value > 0)
                    .unwrap_or(QUIESCENCE_TIMEOUT_MS_DEFAULT),
            )),
            acp_turn_timeout_override: acp_turn_timeout_ms
                .filter(|value| *value > 0)
                .map(Duration::from_millis),
        }
    }

    pub(in crate::relay) fn for_async(
        quiet_window_ms: Option<u64>,
        quiescence_timeout_ms: Option<u64>,
        acp_turn_timeout_ms: Option<u64>,
    ) -> Self {
        Self {
            quiet_window: Duration::from_millis(
                quiet_window_ms
                    .filter(|value| *value > 0)
                    .unwrap_or(QUIET_WINDOW_MS_DEFAULT),
            ),
            quiescence_timeout: quiescence_timeout_ms
                .filter(|value| *value > 0)
                .map(Duration::from_millis),
            acp_turn_timeout_override: acp_turn_timeout_ms
                .filter(|value| *value > 0)
                .map(Duration::from_millis),
        }
    }

    // TODO(refactor-acp-background-reader follow-up): no callers remain.
    // Drop together with the `acp_turn_timeout_ms` MCP/CLI param.
    #[allow(dead_code)]
    pub(super) fn acp_turn_timeout(
        &self,
        acp: &crate::configuration::AcpTargetConfiguration,
    ) -> Duration {
        self.acp_turn_timeout_override
            .or_else(|| acp.turn_timeout_ms.map(Duration::from_millis))
            .unwrap_or_else(|| Duration::from_millis(ACP_TURN_TIMEOUT_MS_DEFAULT))
    }
}

#[derive(Debug)]
pub(in crate::relay) enum DeliveryWaitError {
    Timeout {
        timeout: Duration,
        readiness_mismatch: bool,
        mismatch_reason: Option<String>,
    },
    Failed {
        reason: String,
    },
    Shutdown,
}

#[derive(Debug)]
struct PromptReadinessMatcher {
    prompt_regex: Regex,
    inspect_lines: usize,
    input_idle_cursor_column: Option<usize>,
}

#[derive(Debug, Default)]
struct PromptReadinessEvaluation {
    ready: bool,
    mismatch_reason: Option<String>,
    inspected_block: Option<String>,
    regex_matched: Option<bool>,
    expected_cursor_column: Option<usize>,
    observed_cursor_column: Option<usize>,
}

/// Signature of a non-ready evaluation used to dedup `delivery_prompt_mismatch`
/// log lines emitted from the quiescence wait. When the pane is stuck on the
/// same non-matching state (for example a Claude Code tool-approval dialog
/// that the readiness regex does not match), repeated identical evaluations
/// across poll ticks collapse to a single inscription. The dialog is still
/// treated as non-quiescent and delivery still blocks until the state clears.
#[derive(Debug, PartialEq, Eq)]
struct PromptMismatchSignature {
    mismatch_reason: Option<String>,
    inspected_block: Option<String>,
    regex_matched: Option<bool>,
    expected_cursor_column: Option<usize>,
    observed_cursor_column: Option<usize>,
}

impl PromptMismatchSignature {
    fn from_evaluation(evaluation: &PromptReadinessEvaluation) -> Self {
        Self {
            mismatch_reason: evaluation.mismatch_reason.clone(),
            inspected_block: evaluation.inspected_block.clone(),
            regex_matched: evaluation.regex_matched,
            expected_cursor_column: evaluation.expected_cursor_column,
            observed_cursor_column: evaluation.observed_cursor_column,
        }
    }
}

/// Returns whether a mismatch evaluation should emit a fresh diagnostic. The
/// first call after entering the wait, and every call whose evaluation
/// signature differs from the last emitted one, returns `true` and updates
/// `last`. Repeated identical signatures return `false`.
fn should_emit_prompt_mismatch(
    last: &mut Option<PromptMismatchSignature>,
    evaluation: &PromptReadinessEvaluation,
) -> bool {
    let signature = PromptMismatchSignature::from_evaluation(evaluation);
    if last.as_ref() == Some(&signature) {
        false
    } else {
        *last = Some(signature);
        true
    }
}

pub(super) fn wait_for_quiescent_pane(
    tmux_socket: &Path,
    target_session: &str,
    options: QuiescenceOptions,
    prompt_readiness: Option<&PromptReadinessTemplate>,
) -> Result<String, DeliveryWaitError> {
    let readiness = build_prompt_readiness_matcher(prompt_readiness)
        .map_err(|reason| DeliveryWaitError::Failed { reason })?;
    let deadline = options
        .quiescence_timeout
        .map(|timeout| Instant::now() + timeout);
    let mut readiness_mismatch = false;
    let mut mismatch_reason = None::<String>;
    let mut last_mismatch_signature: Option<PromptMismatchSignature> = None;
    loop {
        if shutdown_requested() {
            return Err(DeliveryWaitError::Shutdown);
        }
        let pane_before = resolve_active_pane_target(tmux_socket, target_session)
            .map_err(|reason| DeliveryWaitError::Failed { reason })?;
        let snapshot_before = capture_pane_snapshot(tmux_socket, &pane_before)
            .map_err(|reason| DeliveryWaitError::Failed { reason })?;
        let activity_before = resolve_window_activity_marker(tmux_socket, &pane_before)
            .map_err(|reason| DeliveryWaitError::Failed { reason })?;

        thread::sleep(options.quiet_window);
        if shutdown_requested() {
            return Err(DeliveryWaitError::Shutdown);
        }

        let pane_after = resolve_active_pane_target(tmux_socket, target_session)
            .map_err(|reason| DeliveryWaitError::Failed { reason })?;
        let snapshot_after = capture_pane_snapshot(tmux_socket, &pane_after)
            .map_err(|reason| DeliveryWaitError::Failed { reason })?;
        let activity_after = resolve_window_activity_marker(tmux_socket, &pane_after)
            .map_err(|reason| DeliveryWaitError::Failed { reason })?;
        let pane_is_quiescent = pane_before == pane_after
            && snapshot_before == snapshot_after
            && match (activity_before.as_ref(), activity_after.as_ref()) {
                (Some(before), Some(after)) => before == after,
                _ => true,
            };
        if pane_is_quiescent {
            if let Some(reason) =
                operator_interaction_active(tmux_socket, target_session, pane_after.as_str())
                    .map_err(|reason| DeliveryWaitError::Failed { reason })?
            {
                emit_delivery_diagnostic(
                    "delivery_operator_interaction",
                    &json!({
                        "target_session": target_session,
                        "pane_target": pane_after,
                        "reason": reason,
                    }),
                );
                continue;
            }
            let evaluation = match prompt_readiness_matches(
                tmux_socket,
                pane_after.as_str(),
                snapshot_after.as_str(),
                readiness.as_ref(),
            ) {
                Ok(evaluation) => evaluation,
                Err(reason) => return Err(DeliveryWaitError::Failed { reason }),
            };
            if evaluation.ready {
                emit_delivery_diagnostic(
                    "delivery_ready",
                    &json!({
                        "target_session": target_session,
                        "pane_target": pane_after,
                    }),
                );
                return Ok(pane_after);
            }
            readiness_mismatch = true;
            mismatch_reason = evaluation.mismatch_reason.clone();
            if should_emit_prompt_mismatch(&mut last_mismatch_signature, &evaluation) {
                emit_delivery_diagnostic(
                    "delivery_prompt_mismatch",
                    &json!({
                        "target_session": target_session,
                        "pane_target": pane_after,
                        "mismatch_reason": evaluation.mismatch_reason,
                        "regex_matched": evaluation.regex_matched,
                        "inspected_block": evaluation.inspected_block,
                        "expected_cursor_column": evaluation.expected_cursor_column,
                        "observed_cursor_column": evaluation.observed_cursor_column,
                    }),
                );
            }
        }

        if deadline.is_some_and(|value| Instant::now() >= value) {
            let timeout = options.quiescence_timeout.unwrap_or_default();
            emit_delivery_diagnostic(
                "quiescence_timeout",
                &json!({
                    "target_session": target_session,
                    "quiescence_timeout_ms": timeout.as_millis(),
                    "readiness_mismatch": readiness_mismatch,
                    "mismatch_reason": mismatch_reason,
                }),
            );
            return Err(DeliveryWaitError::Timeout {
                timeout,
                readiness_mismatch,
                mismatch_reason,
            });
        }
    }
}

fn build_prompt_readiness_matcher(
    template: Option<&PromptReadinessTemplate>,
) -> Result<Option<PromptReadinessMatcher>, String> {
    let Some(template) = template else {
        return Ok(None);
    };

    let prompt_regex = Regex::new(template.prompt_regex.as_str())
        .map_err(|source| format!("invalid prompt_readiness.prompt_regex: {source}"))?;
    let inspect_lines = template
        .inspect_lines
        .unwrap_or(PROMPT_INSPECT_LINES_DEFAULT)
        .clamp(1, PROMPT_INSPECT_LINES_MAX);

    Ok(Some(PromptReadinessMatcher {
        prompt_regex,
        inspect_lines,
        input_idle_cursor_column: template.input_idle_cursor_column,
    }))
}

fn prompt_readiness_matches(
    tmux_socket: &Path,
    pane_target: &str,
    snapshot: &str,
    matcher: Option<&PromptReadinessMatcher>,
) -> Result<PromptReadinessEvaluation, String> {
    let Some(matcher) = matcher else {
        return Ok(PromptReadinessEvaluation {
            ready: true,
            ..PromptReadinessEvaluation::default()
        });
    };

    let inspected = snapshot
        .lines()
        .rev()
        .skip_while(|line| line.trim().is_empty())
        .take(matcher.inspect_lines)
        .collect::<Vec<_>>();
    if inspected.is_empty() {
        return Ok(PromptReadinessEvaluation {
            mismatch_reason: Some(
                "inspected pane tail was empty after trimming trailing blank lines".to_string(),
            ),
            regex_matched: Some(false),
            expected_cursor_column: matcher.input_idle_cursor_column,
            ..PromptReadinessEvaluation::default()
        });
    }
    let mut ordered = inspected;
    ordered.reverse();
    let block = ordered.join("\n");
    if !matcher.prompt_regex.is_match(block.as_str()) {
        return Ok(PromptReadinessEvaluation {
            mismatch_reason: Some("prompt regex did not match inspected pane tail".to_string()),
            inspected_block: Some(sanitize_diagnostic_text(&block)),
            regex_matched: Some(false),
            expected_cursor_column: matcher.input_idle_cursor_column,
            ..PromptReadinessEvaluation::default()
        });
    }

    let Some(expected_cursor_column) = matcher.input_idle_cursor_column else {
        return Ok(PromptReadinessEvaluation {
            ready: true,
            inspected_block: Some(sanitize_diagnostic_text(&block)),
            regex_matched: Some(true),
            ..PromptReadinessEvaluation::default()
        });
    };
    let cursor_column = resolve_cursor_column(tmux_socket, pane_target)?;
    if cursor_column != expected_cursor_column {
        return Ok(PromptReadinessEvaluation {
            mismatch_reason: Some(format!(
                "cursor column {} did not match required {}",
                cursor_column, expected_cursor_column
            )),
            inspected_block: Some(sanitize_diagnostic_text(&block)),
            regex_matched: Some(true),
            expected_cursor_column: Some(expected_cursor_column),
            observed_cursor_column: Some(cursor_column),
            ..PromptReadinessEvaluation::default()
        });
    }

    Ok(PromptReadinessEvaluation {
        ready: true,
        inspected_block: Some(sanitize_diagnostic_text(&block)),
        regex_matched: Some(true),
        expected_cursor_column: Some(expected_cursor_column),
        observed_cursor_column: Some(cursor_column),
        ..PromptReadinessEvaluation::default()
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    // Dedup is a private detail of `wait_for_quiescent_pane`: the loop owns
    // the signature state and emits via a crate-private helper. Driving it
    // from an external test would require either widening visibility on the
    // helper / signature struct or spinning up tmux to drive the loop. One
    // inline unit covers the three transitions that matter: first emit,
    // identical repeat suppressed, and signature change re-emits.
    #[test]
    fn dedup_emits_only_on_signature_transitions() {
        let stuck = PromptReadinessEvaluation {
            mismatch_reason: Some("prompt regex did not match inspected pane tail".to_string()),
            inspected_block: Some("Do you want to proceed?".to_string()),
            regex_matched: Some(false),
            expected_cursor_column: Some(4),
            observed_cursor_column: None,
            ..PromptReadinessEvaluation::default()
        };
        let cursor_only = PromptReadinessEvaluation {
            mismatch_reason: Some("cursor column 0 did not match required 4".to_string()),
            inspected_block: Some("> ".to_string()),
            regex_matched: Some(true),
            expected_cursor_column: Some(4),
            observed_cursor_column: Some(0),
            ..PromptReadinessEvaluation::default()
        };

        let mut last = None;
        assert!(
            should_emit_prompt_mismatch(&mut last, &stuck),
            "first mismatch must emit",
        );
        assert!(
            !should_emit_prompt_mismatch(&mut last, &stuck),
            "identical follow-up must suppress",
        );
        assert!(
            !should_emit_prompt_mismatch(&mut last, &stuck),
            "second identical follow-up must suppress",
        );
        assert!(
            should_emit_prompt_mismatch(&mut last, &cursor_only),
            "signature change must re-emit",
        );
        assert!(
            !should_emit_prompt_mismatch(&mut last, &cursor_only),
            "post-change identical follow-up must suppress",
        );
    }
}