synaps 0.1.2

Terminal-native AI agent runtime — parallel orchestration, reactive subagents, MCP, autonomous supervision
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
//! Output readiness detection — determines when a shell is waiting for input.
//!
//! Three strategies for detecting that a shell process has finished producing
//! output and is waiting for the next command:
//!
//! - **Timeout**: pure silence-based — if N ms pass with no output, we assume ready.
//! - **Prompt**: regex-based — scan the tail of output for known prompt patterns.
//! - **Hybrid**: try prompt detection first, fall back to silence timeout.
//!
//! The `check()` method is stateless and designed for polling loops — the caller
//! owns the timers, we just evaluate the current snapshot.

use std::time::Duration;

use regex::Regex;

use crate::tools::strip_ansi;

use super::config::ShellConfig;

// ---------------------------------------------------------------------------
// Strategy & result enums
// ---------------------------------------------------------------------------

/// The strategy for detecting when a shell is ready for input.
#[derive(Debug, Clone)]
pub enum ReadinessStrategy {
    /// Wait for N ms of output silence
    Timeout,
    /// Wait until output matches a prompt regex
    Prompt,
    /// Prompt detection with timeout fallback (default)
    Hybrid,
}

impl ReadinessStrategy {
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "timeout" => ReadinessStrategy::Timeout,
            "prompt" => ReadinessStrategy::Prompt,
            _ => ReadinessStrategy::Hybrid,
        }
    }
}

/// Result of a readiness check
#[derive(Debug, PartialEq)]
pub enum ReadinessResult {
    /// Output matched a prompt pattern — shell is waiting for input
    Ready,
    /// Still receiving output, keep waiting
    Waiting,
    /// Silence timeout expired — return what we have
    SilenceTimeout,
    /// Maximum total wait time exceeded
    MaxTimeout,
}

// ---------------------------------------------------------------------------
// Detector
// ---------------------------------------------------------------------------

/// Stateless readiness evaluator — called repeatedly in a polling loop.
pub struct ReadinessDetector {
    strategy: ReadinessStrategy,
    patterns: Vec<Regex>,
    silence_timeout: Duration,
    max_timeout: Duration,
}

/// How many chars from the tail of output to inspect for prompt matching.
const PROMPT_TAIL_LEN: usize = 200;

impl ReadinessDetector {
    /// Build a detector from raw parts.
    ///
    /// Invalid regex patterns are silently skipped (with a `tracing::warn`).
    /// If *no* patterns compile, the strategy is downgraded to `Timeout`.
    pub fn new(
        strategy: ReadinessStrategy,
        patterns_str: &[String],
        silence_timeout_ms: u64,
        max_timeout_ms: u64,
    ) -> Self {
        let patterns: Vec<Regex> = patterns_str
            .iter()
            .filter_map(|p| match Regex::new(p) {
                Ok(re) => Some(re),
                Err(e) => {
                    tracing::warn!(pattern = %p, error = %e, "skipping invalid prompt regex");
                    None
                }
            })
            .collect();

        // If we wanted prompt detection but have no usable patterns, fall back.
        let strategy = if patterns.is_empty() {
            match strategy {
                ReadinessStrategy::Prompt | ReadinessStrategy::Hybrid => {
                    tracing::warn!(
                        "no valid prompt patterns — falling back to Timeout strategy"
                    );
                    ReadinessStrategy::Timeout
                }
                other => other,
            }
        } else {
            strategy
        };

        Self {
            strategy,
            patterns,
            silence_timeout: Duration::from_millis(silence_timeout_ms),
            max_timeout: Duration::from_millis(max_timeout_ms),
        }
    }

    /// Build from the default `ShellConfig`.
    pub fn from_config(config: &ShellConfig) -> Self {
        let strategy = crate::tools::shell::readiness::ReadinessStrategy::from_str(&config.readiness_strategy);
        Self::new(
            strategy,
            &config.prompt_patterns,
            config.readiness_timeout_ms,
            config.max_readiness_timeout_ms,
        )
    }

    /// Evaluate the current output snapshot against the active strategy.
    ///
    /// Called in a tight poll loop — the caller tracks `silence_elapsed`
    /// (time since last new output byte) and `total_elapsed` (wall-clock since
    /// the command was sent).
    pub fn check(
        &self,
        output: &str,
        silence_elapsed: Duration,
        total_elapsed: Duration,
    ) -> ReadinessResult {
        // Hard ceiling — always wins.
        if total_elapsed >= self.max_timeout {
            return ReadinessResult::MaxTimeout;
        }

        match &self.strategy {
            ReadinessStrategy::Timeout => {
                if silence_elapsed >= self.silence_timeout {
                    ReadinessResult::SilenceTimeout
                } else {
                    ReadinessResult::Waiting
                }
            }
            ReadinessStrategy::Prompt => {
                if self.matches_prompt(output) {
                    ReadinessResult::Ready
                } else {
                    ReadinessResult::Waiting
                }
            }
            ReadinessStrategy::Hybrid => {
                if self.matches_prompt(output) {
                    ReadinessResult::Ready
                } else if silence_elapsed >= self.silence_timeout {
                    ReadinessResult::SilenceTimeout
                } else {
                    ReadinessResult::Waiting
                }
            }
        }
    }

    /// Check the tail of `output` for a known prompt pattern.
    ///
    /// Only inspects the last ~200 chars (prompts live at the end), and strips
    /// ANSI escapes before matching.  The match runs against the last non-empty
    /// line.
    pub fn matches_prompt(&self, output: &str) -> bool {
        if output.is_empty() || self.patterns.is_empty() {
            return false;
        }

        // Grab the tail to avoid scanning megabytes of scrollback.
        // Walk backward to the previous UTF-8 char boundary to avoid panicking
        // when multi-byte glyphs (●, ❯, box-drawing, emoji) straddle the cut.
        // Walking backward (floor) instead of forward (ceil) ensures the tail
        // is never empty when the cut lands inside the final multi-byte glyph.
        let tail = if output.len() > PROMPT_TAIL_LEN {
            let mut start = output.len() - PROMPT_TAIL_LEN;
            while start > 0 && !output.is_char_boundary(start) {
                start -= 1;
            }
            &output[start..]
        } else {
            output
        };

        let clean = strip_ansi(tail);

        // Last non-empty line is where the prompt sits.
        let last_line = clean
            .lines()
            .rev()
            .find(|l| !l.trim().is_empty())
            .unwrap_or("");

        if last_line.is_empty() {
            return false;
        }

        self.patterns.iter().any(|re| re.is_match(last_line))
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    /// Helper: build a Timeout detector with sensible defaults.
    fn timeout_detector(silence_ms: u64) -> ReadinessDetector {
        ReadinessDetector::new(ReadinessStrategy::Timeout, &[], silence_ms, 10_000)
    }

    /// Helper: build a Prompt detector with the default pattern set.
    fn prompt_detector() -> ReadinessDetector {
        let config = ShellConfig::default();
        ReadinessDetector::new(
            ReadinessStrategy::Prompt,
            &config.prompt_patterns,
            config.readiness_timeout_ms,
            config.max_readiness_timeout_ms,
        )
    }

    /// Helper: build a Hybrid detector with the default pattern set.
    fn hybrid_detector() -> ReadinessDetector {
        ReadinessDetector::from_config(&ShellConfig::default())
    }

    // 1. Timeout: silence exceeds threshold → SilenceTimeout
    #[test]
    fn timeout_strategy_silence_triggers() {
        let det = timeout_detector(300);
        let result = det.check(
            "some output\n",
            Duration::from_millis(301),
            Duration::from_millis(500),
        );
        assert_eq!(result, ReadinessResult::SilenceTimeout);
    }

    // 1b. Timeout: silence below threshold → Waiting
    #[test]
    fn timeout_strategy_still_waiting() {
        let det = timeout_detector(300);
        let result = det.check(
            "some output\n",
            Duration::from_millis(100),
            Duration::from_millis(200),
        );
        assert_eq!(result, ReadinessResult::Waiting);
    }

    // 2. Prompt: output ending with `$ ` → Ready
    #[test]
    fn prompt_strategy_dollar_ready() {
        let det = prompt_detector();
        let result = det.check(
            "user@host:~$ ",
            Duration::from_millis(0),
            Duration::from_millis(50),
        );
        assert_eq!(result, ReadinessResult::Ready);
    }

    // 3. Prompt: output ending with `>>> ` (Python) → Ready
    #[test]
    fn prompt_strategy_python_ready() {
        let det = prompt_detector();
        let result = det.check(
            "Python 3.11.0\n>>> ",
            Duration::from_millis(0),
            Duration::from_millis(50),
        );
        assert_eq!(result, ReadinessResult::Ready);
    }

    // 4. Prompt: output NOT ending with prompt → still waiting (no silence fallback)
    #[test]
    fn prompt_strategy_no_match_silence_fallback() {
        let det = prompt_detector();
        // No prompt at the end, silence exceeded - but prompt strategy doesn't use silence
        let result = det.check(
            "compiling crate...\n",
            Duration::from_millis(500),
            Duration::from_millis(1000),
        );
        assert_eq!(result, ReadinessResult::Waiting);
    }

    // 4b. Prompt: no match, silence not exceeded → Waiting
    #[test]
    fn prompt_strategy_no_match_waiting() {
        let det = prompt_detector();
        let result = det.check(
            "compiling crate...\n",
            Duration::from_millis(100),
            Duration::from_millis(200),
        );
        assert_eq!(result, ReadinessResult::Waiting);
    }

    // 5. Hybrid: prompt match → Ready (before silence would trigger)
    #[test]
    fn hybrid_prompt_match_before_silence() {
        let det = hybrid_detector();
        let result = det.check(
            "welcome\nuser@host:~$ ",
            Duration::from_millis(10), // well below silence threshold
            Duration::from_millis(50),
        );
        assert_eq!(result, ReadinessResult::Ready);
    }

    // 6. Hybrid: no prompt match, silence elapsed → SilenceTimeout
    #[test]
    fn hybrid_silence_fallback() {
        let det = hybrid_detector();
        let result = det.check(
            "running long task...\n",
            Duration::from_millis(500),
            Duration::from_millis(1000),
        );
        assert_eq!(result, ReadinessResult::SilenceTimeout);
    }

    // 7. MaxTimeout always wins regardless of strategy
    #[test]
    fn max_timeout_always_wins() {
        for det in [timeout_detector(300), prompt_detector(), hybrid_detector()] {
            let result = det.check(
                "user@host:~$ ",
                Duration::from_millis(0),
                Duration::from_millis(10_001),
            );
            assert_eq!(result, ReadinessResult::MaxTimeout);
        }
    }

    // 8. matches_prompt against common prompts
    #[test]
    fn matches_prompt_common_patterns() {
        let det = hybrid_detector();
        let prompts = [
            "user@host:~$ ",
            "root@server:/var# ",
            ">>> ",
            "(gdb) ",
            "Password: ",
        ];
        for prompt in &prompts {
            assert!(
                det.matches_prompt(prompt),
                "expected match for prompt: {:?}",
                prompt,
            );
        }
    }

    // 9. Invalid regex patterns are skipped — no panic
    #[test]
    fn invalid_regex_skipped_no_panic() {
        let patterns = vec![
            "[invalid(".into(), // broken regex
            r"[$#] $".into(),   // valid
        ];
        let det = ReadinessDetector::new(
            ReadinessStrategy::Hybrid,
            &patterns,
            300,
            10_000,
        );
        // Should still work — the valid pattern compiled.
        assert!(det.matches_prompt("user@host:~$ "));
    }

    // 9b. ALL patterns invalid → falls back to Timeout
    #[test]
    fn all_invalid_patterns_fallback_to_timeout() {
        let patterns = vec!["[broken(".into(), "(also[bad".into()];
        let det = ReadinessDetector::new(
            ReadinessStrategy::Hybrid,
            &patterns,
            300,
            10_000,
        );
        // Strategy downgraded — prompt won't match, silence drives the result.
        assert!(!det.matches_prompt("user@host:~$ "));
        let result = det.check(
            "user@host:~$ ",
            Duration::from_millis(301),
            Duration::from_millis(500),
        );
        assert_eq!(result, ReadinessResult::SilenceTimeout);
    }

    // 10. Empty output never matches
    #[test]
    fn empty_output_no_match() {
        let det = hybrid_detector();
        assert!(!det.matches_prompt(""));
    }

    // Bonus: ANSI-laden prompt still matches after stripping
    #[test]
    fn ansi_stripped_before_matching() {
        let det = hybrid_detector();
        // Prompt with color codes wrapping it
        let ansi_prompt = "\x1b[32muser@host\x1b[0m:\x1b[34m~\x1b[0m$ ";
        assert!(det.matches_prompt(ansi_prompt));
    }

    // Bonus: only last line matters
    #[test]
    fn only_last_line_checked() {
        let det = hybrid_detector();
        // Prompt-like text in the middle, non-prompt at the end
        assert!(!det.matches_prompt("user@host:~$ \nstill running..."));
        // Prompt at the end
        assert!(det.matches_prompt("still running...\nuser@host:~$ "));
    }

    // Regression: multi-byte UTF-8 glyphs at the tail boundary must not panic.
    // See BUG_REPORT_synaps_ssh_crash.md — starship/powerline prompts with
    // ●/❯/box-drawing glyphs caused SIGABRT when the byte-offset slice landed
    // inside a multi-byte sequence.
    #[test]
    fn matches_prompt_handles_multibyte_glyph_at_tail_boundary() {
        let det = hybrid_detector();

        // Build output where a 3-byte char straddles the tail-window cut.
        // prefix_len puts the start of '●' (3 bytes) exactly 1 byte before
        // the PROMPT_TAIL_LEN boundary, so a naive slice would land inside it.
        let prefix_len = PROMPT_TAIL_LEN - 1;
        let mut output = "x".repeat(prefix_len);
        output.push(''); // 3-byte: E2 97 8F
        output.push_str("\n~/repo on  main\nuser@host:~$ ");

        // Must not panic, and should still detect the prompt.
        assert!(det.matches_prompt(&output));
    }

    #[test]
    fn matches_prompt_handles_4byte_emoji_at_tail_boundary() {
        let det = hybrid_detector();

        // 4-byte emoji right at the boundary edge
        for offset in 0..4 {
            let prefix_len = PROMPT_TAIL_LEN - offset;
            let mut output = "a".repeat(prefix_len);
            output.push('🔥'); // 4-byte: F0 9F 94 A5
            output.push_str("\nuser@host:~$ ");
            assert!(det.matches_prompt(&output), "panicked at offset {}", offset);
        }
    }
}