openlatch-client 0.6.0

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
//! The rail's two-option question (`● Yes, share    ○ No thanks`).
//!
//! Two ways to ask, picked by the rail's mode:
//!
//! - **Keys** (`Live`, stdin a terminal): ← → / Tab move, `y` / `n` answer at
//!   once, Enter takes the highlighted option. Only the options line is redrawn.
//! - **Line** (everything else): `[Y/n] › ` with the cursor on the same line,
//!   answered by a typed line. Empty takes the default.
//!
//! Whatever happens, the caller learns *which* thing happened. "Nobody
//! answered" (end of input), "the answer could not be read" (an I/O error),
//! "nobody answered in time" and "the answer was not yes or no" are four
//! different stories, and the consent path used to tell all of them as the
//! first one.

use std::io;
use std::sync::mpsc;
use std::time::{Duration, Instant};

use console::Key;

/// A two-option question.
#[derive(Debug, Clone)]
pub struct Select<'a> {
    /// Stage title the block is drawn under (`Usage data`).
    pub title: &'a str,
    /// The question itself.
    pub question: &'a str,
    /// Dim lines between the question and the options.
    pub lines: &'a [&'a str],
    /// First option, answered by `y`.
    pub yes: &'a str,
    /// Second option, answered by `n`.
    pub no: &'a str,
    /// Which option Enter (or an empty line) takes.
    pub default_yes: bool,
    /// How long to wait for a typed line. The key path is not bounded: it runs
    /// only where a person is at the keyboard, and abandoning a raw-mode read
    /// would leave their terminal raw after the process exits.
    pub timeout: Option<Duration>,
}

/// How a question ended.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SelectOutcome {
    /// `true` for the first (`yes`) option.
    Answered(bool),
    /// Input closed before an answer (Ctrl+D, `</dev/null`, a closed pipe).
    Eof,
    /// Reading the answer failed.
    ReadError(ReadFailure),
    /// No answer within [`Select::timeout`].
    TimedOut,
    /// Three answers that were neither yes nor no.
    Unrecognized,
}

/// Why a read failed: the error kind and, when the OS reported one, its raw
/// code — enough for a transcript to name the cause.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReadFailure {
    pub kind: io::ErrorKind,
    pub os_code: Option<i32>,
}

impl From<&io::Error> for ReadFailure {
    fn from(e: &io::Error) -> Self {
        Self {
            kind: e.kind(),
            os_code: e.raw_os_error(),
        }
    }
}

/// How many unreadable line answers before giving up.
const MAX_LINE_ATTEMPTS: usize = 3;

/// What one line read produced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LineRead {
    Line(String),
    Eof,
    Error(ReadFailure),
    TimedOut,
}

/// A typed answer: empty takes the default, `y`/`yes`/`n`/`no` in any case;
/// anything else is `None`.
pub fn parse_answer(answer: &str, default_yes: bool) -> Option<bool> {
    match answer.trim().to_ascii_lowercase().as_str() {
        "" => Some(default_yes),
        "y" | "yes" => Some(true),
        "n" | "no" => Some(false),
        _ => None,
    }
}

/// Ask on the line path. `read` is called once per attempt with the time left;
/// `reprompt` redraws the prompt after an unrecognized answer.
pub fn ask_line(
    default_yes: bool,
    timeout: Option<Duration>,
    mut read: impl FnMut(Option<Duration>) -> LineRead,
    mut reprompt: impl FnMut(),
) -> SelectOutcome {
    let deadline = timeout.map(|t| Instant::now() + t);
    for attempt in 1..=MAX_LINE_ATTEMPTS {
        let left = deadline.map(|d| d.saturating_duration_since(Instant::now()));
        match read(left) {
            LineRead::Line(line) => {
                if let Some(yes) = parse_answer(&line, default_yes) {
                    return SelectOutcome::Answered(yes);
                }
                if attempt < MAX_LINE_ATTEMPTS {
                    reprompt();
                }
            }
            LineRead::Eof => return SelectOutcome::Eof,
            LineRead::Error(failure) => return SelectOutcome::ReadError(failure),
            LineRead::TimedOut => return SelectOutcome::TimedOut,
        }
    }
    SelectOutcome::Unrecognized
}

/// Run `read_line` on a helper thread and wait at most `timeout` for it.
///
/// `read_line` returns the raw `read_line` result: `Ok(0)` is end of input. On
/// a timeout the thread is left blocked in its read, which is harmless for a
/// line read (the terminal stays in its normal mode) and ends with the process.
pub fn read_line_within<F>(timeout: Option<Duration>, read_line: F) -> LineRead
where
    F: FnOnce() -> io::Result<(usize, String)> + Send + 'static,
{
    let (tx, rx) = mpsc::channel();
    std::thread::spawn(move || {
        let _ = tx.send(read_line());
    });
    let got = match timeout {
        Some(t) => rx.recv_timeout(t).map_err(|_| ()),
        None => rx.recv().map_err(|_| ()),
    };
    match got {
        Ok(Ok((0, _))) => LineRead::Eof,
        Ok(Ok((_, line))) => LineRead::Line(line),
        Ok(Err(e)) => LineRead::Error(ReadFailure::from(&e)),
        Err(()) => LineRead::TimedOut,
    }
}

/// Read one line from stdin, bounded by `timeout`.
pub fn read_stdin_line(timeout: Option<Duration>) -> LineRead {
    read_line_within(timeout, || {
        let mut line = String::new();
        let n = io::stdin().read_line(&mut line)?;
        Ok((n, line))
    })
}

/// Drop whatever was typed before the question was asked, so a key pressed
/// while the user was elsewhere (an Enter during sign-in) cannot answer it.
/// Does nothing when stdin is not an interactive console or terminal.
pub fn discard_typeahead() {
    #[cfg(windows)]
    {
        use winapi::um::consoleapi::GetConsoleMode;
        use winapi::um::processenv::GetStdHandle;
        use winapi::um::winbase::STD_INPUT_HANDLE;
        use winapi::um::wincon::FlushConsoleInputBuffer;
        // SAFETY: plain Win32 calls on the process's own stdin handle; the
        // console-mode probe keeps the flush to a real console input buffer.
        unsafe {
            let handle = GetStdHandle(STD_INPUT_HANDLE);
            let mut mode = 0;
            if GetConsoleMode(handle, &mut mode) != 0 {
                FlushConsoleInputBuffer(handle);
            }
        }
    }
    #[cfg(unix)]
    {
        // SAFETY: `tcflush` on fd 0, only once `isatty` has confirmed a terminal.
        unsafe {
            if libc::isatty(libc::STDIN_FILENO) == 1 {
                libc::tcflush(libc::STDIN_FILENO, libc::TCIFLUSH);
            }
        }
    }
}

/// Highlight state of the key path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyState {
    /// The first (`yes`) option is highlighted.
    pub yes: bool,
}

/// What one key does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyStep {
    /// Highlight moved: redraw the options line.
    Moved,
    /// The question is answered.
    Answer(bool),
    /// Input ended (Ctrl+D).
    Eof,
    /// Nothing to do.
    Ignore,
}

impl KeyState {
    /// Apply one key.
    pub fn apply(&mut self, key: &Key) -> KeyStep {
        match key {
            Key::ArrowLeft | Key::ArrowRight | Key::Tab | Key::BackTab => {
                self.yes = !self.yes;
                KeyStep::Moved
            }
            Key::ArrowUp | Key::Home => self.go(true),
            Key::ArrowDown | Key::End => self.go(false),
            Key::Enter => KeyStep::Answer(self.yes),
            Key::Char('y' | 'Y') => KeyStep::Answer(true),
            Key::Char('n' | 'N') => KeyStep::Answer(false),
            Key::Char('\u{4}') => KeyStep::Eof,
            _ => KeyStep::Ignore,
        }
    }

    fn go(&mut self, yes: bool) -> KeyStep {
        if self.yes == yes {
            KeyStep::Ignore
        } else {
            self.yes = yes;
            KeyStep::Moved
        }
    }
}

/// Consecutive `Key::Unknown`s after which input is treated as closed. A real
/// terminal sends the odd unknown key; a stream of them means nothing is there.
const MAX_UNKNOWN_KEYS: usize = 64;

/// Ask on the key path. `read_key` reads one key; `redraw` redraws the options
/// line for the new highlight.
pub fn ask_keys(
    default_yes: bool,
    mut read_key: impl FnMut() -> io::Result<Key>,
    mut redraw: impl FnMut(KeyState),
) -> SelectOutcome {
    let mut state = KeyState { yes: default_yes };
    let mut unknown = 0;
    loop {
        let key = match read_key() {
            Ok(k) => k,
            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return SelectOutcome::Eof,
            Err(e) => return SelectOutcome::ReadError(ReadFailure::from(&e)),
        };
        if key == Key::Unknown {
            unknown += 1;
            if unknown >= MAX_UNKNOWN_KEYS {
                return SelectOutcome::Eof;
            }
            continue;
        }
        unknown = 0;
        match state.apply(&key) {
            KeyStep::Moved => redraw(state),
            KeyStep::Answer(yes) => return SelectOutcome::Answered(yes),
            KeyStep::Eof => return SelectOutcome::Eof,
            KeyStep::Ignore => {}
        }
    }
}

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

    fn failed(kind: io::ErrorKind) -> ReadFailure {
        ReadFailure::from(&io::Error::from(kind))
    }

    #[test]
    fn test_parse_answer() {
        assert_eq!(parse_answer("", true), Some(true));
        assert_eq!(parse_answer("\r\n", false), Some(false));
        assert_eq!(parse_answer("Y\r\n", false), Some(true));
        assert_eq!(parse_answer(" yes ", false), Some(true));
        assert_eq!(parse_answer("N", true), Some(false));
        assert_eq!(parse_answer("No\n", true), Some(false));
        assert_eq!(parse_answer("maybe", true), None);
    }

    fn scripted(reads: Vec<LineRead>) -> impl FnMut(Option<Duration>) -> LineRead {
        let mut reads = reads.into_iter();
        move |_| reads.next().expect("no more scripted reads")
    }

    #[test]
    fn test_line_classifier() {
        let ask = |reads| ask_line(false, None, scripted(reads), || {});
        assert_eq!(
            ask(vec![LineRead::Line("Y\r\n".into())]),
            SelectOutcome::Answered(true)
        );
        assert_eq!(ask(vec![LineRead::Eof]), SelectOutcome::Eof);
        assert_eq!(
            ask(vec![LineRead::Error(failed(io::ErrorKind::InvalidData))]),
            SelectOutcome::ReadError(failed(io::ErrorKind::InvalidData))
        );
        assert_eq!(ask(vec![LineRead::TimedOut]), SelectOutcome::TimedOut);
        assert_eq!(
            ask(vec![
                LineRead::Line("what".into()),
                LineRead::Line("n\n".into())
            ]),
            SelectOutcome::Answered(false)
        );
        assert_eq!(
            ask(vec![
                LineRead::Line("a".into()),
                LineRead::Line("b".into()),
                LineRead::Line("c".into())
            ]),
            SelectOutcome::Unrecognized
        );
    }

    #[test]
    fn test_line_reprompts_between_unrecognized_answers() {
        let mut reprompts = 0;
        let outcome = ask_line(
            true,
            None,
            scripted(vec![LineRead::Line("?".into()), LineRead::Line("".into())]),
            || reprompts += 1,
        );
        assert_eq!(outcome, SelectOutcome::Answered(true));
        assert_eq!(reprompts, 1);
    }

    #[test]
    fn test_read_line_within_distinguishes_all_four() {
        let t = Some(Duration::from_secs(5));
        assert_eq!(
            read_line_within(t, || Ok((2, "y\n".into()))),
            LineRead::Line("y\n".into())
        );
        assert_eq!(
            read_line_within(t, || Ok((0, String::new()))),
            LineRead::Eof
        );
        assert_eq!(
            read_line_within(t, || Err(io::Error::from(io::ErrorKind::InvalidData))),
            LineRead::Error(failed(io::ErrorKind::InvalidData))
        );
        assert_eq!(
            read_line_within(Some(Duration::from_millis(20)), || {
                std::thread::sleep(Duration::from_secs(2));
                Ok((2, "y\n".into()))
            }),
            LineRead::TimedOut
        );
    }

    fn keys(seq: Vec<io::Result<Key>>) -> impl FnMut() -> io::Result<Key> {
        let mut seq = seq.into_iter();
        move || seq.next().expect("no more scripted keys")
    }

    #[test]
    fn test_key_classifier() {
        let ask = |default, seq| ask_keys(default, keys(seq), |_| {});
        assert_eq!(
            ask(true, vec![Ok(Key::Enter)]),
            SelectOutcome::Answered(true)
        );
        assert_eq!(
            ask(true, vec![Ok(Key::ArrowRight), Ok(Key::Enter)]),
            SelectOutcome::Answered(false)
        );
        assert_eq!(
            ask(false, vec![Ok(Key::Tab), Ok(Key::Tab), Ok(Key::Enter)]),
            SelectOutcome::Answered(false)
        );
        assert_eq!(
            ask(false, vec![Ok(Key::Char('Y'))]),
            SelectOutcome::Answered(true)
        );
        assert_eq!(
            ask(true, vec![Ok(Key::Char('n'))]),
            SelectOutcome::Answered(false)
        );
        assert_eq!(ask(true, vec![Ok(Key::Char('\u{4}'))]), SelectOutcome::Eof);
        assert_eq!(
            ask(
                true,
                vec![Err(io::Error::from(io::ErrorKind::UnexpectedEof))]
            ),
            SelectOutcome::Eof
        );
        assert_eq!(
            ask(true, vec![Err(io::Error::from(io::ErrorKind::Other))]),
            SelectOutcome::ReadError(failed(io::ErrorKind::Other))
        );
        let unknowns = (0..MAX_UNKNOWN_KEYS).map(|_| Ok(Key::Unknown)).collect();
        assert_eq!(ask(true, unknowns), SelectOutcome::Eof);
    }

    /// The raw OS code survives into the outcome, so the transcript can name
    /// the cause (`ERROR_INVALID_HANDLE` is 6 on Windows).
    #[test]
    fn test_read_failure_keeps_the_os_code() {
        let failure = ReadFailure::from(&io::Error::from_raw_os_error(6));
        assert_eq!(failure.os_code, Some(6));
        assert_eq!(
            read_line_within(None, || Err(io::Error::from_raw_os_error(6))),
            LineRead::Error(failure)
        );
    }

    #[test]
    fn test_key_redraw_only_on_move() {
        let mut draws = Vec::new();
        let outcome = ask_keys(
            true,
            keys(vec![
                Ok(Key::ArrowUp),
                Ok(Key::Char('x')),
                Ok(Key::ArrowDown),
                Ok(Key::Enter),
            ]),
            |s| draws.push(s.yes),
        );
        assert_eq!(outcome, SelectOutcome::Answered(false));
        assert_eq!(draws, vec![false], "only ArrowDown moved the highlight");
    }
}