zeph-channels 0.16.0

Multi-channel I/O adapters (CLI, Telegram, Discord, Slack) for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::io::{self, BufRead, Read, Write, stdout};

use crossterm::{
    cursor,
    event::{self, Event, KeyCode, KeyModifiers},
    terminal::{self, ClearType},
};

pub enum ReadLineResult {
    Line(String),
    Interrupted,
    Eof,
}

struct RawModeGuard;

impl RawModeGuard {
    fn enter() -> io::Result<Self> {
        terminal::enable_raw_mode()?;
        Ok(Self)
    }
}

impl Drop for RawModeGuard {
    fn drop(&mut self) {
        let _ = terminal::disable_raw_mode();
    }
}

/// Maximum number of bytes read per line in piped mode to prevent OOM on unterminated input.
const MAX_LINE_LEN: u64 = 1 << 20; // 1 MiB

/// Read a single line from `reader` without raw mode (for piped/non-TTY stdin).
///
/// Reads at most [`MAX_LINE_LEN`] bytes. Input that exceeds this limit is silently truncated.
/// Returns `ReadLineResult::Eof` when the reader is exhausted (0 bytes read).
///
/// # Errors
///
/// Returns `io::Error` on underlying I/O failure.
pub fn read_line_piped<R: BufRead>(reader: &mut R) -> io::Result<ReadLineResult> {
    let mut buf = String::new();
    let n = reader.take(MAX_LINE_LEN).read_line(&mut buf)?;
    if n == 0 {
        return Ok(ReadLineResult::Eof);
    }
    // Strip trailing newline characters
    if buf.ends_with('\n') {
        buf.pop();
        if buf.ends_with('\r') {
            buf.pop();
        }
    }
    Ok(ReadLineResult::Line(buf))
}

pub fn read_line(prompt: &str, history: &[String]) -> io::Result<ReadLineResult> {
    let _guard = RawModeGuard::enter()?;

    let mut input = String::new();
    let mut cursor_pos: usize = 0;
    let mut history_index: Option<usize> = None;
    let mut draft = String::new();

    render(prompt, &input, cursor_pos)?;

    loop {
        let Event::Key(key) = event::read()? else {
            continue;
        };
        // Ignore release/repeat events on platforms that send them
        if key.kind != event::KeyEventKind::Press {
            continue;
        }

        match (key.modifiers, key.code) {
            (KeyModifiers::CONTROL, KeyCode::Char('c')) => {
                write!(stdout(), "\r\n")?;
                stdout().flush()?;
                return Ok(ReadLineResult::Interrupted);
            }
            (KeyModifiers::CONTROL, KeyCode::Char('d')) => {
                if input.is_empty() {
                    write!(stdout(), "\r\n")?;
                    stdout().flush()?;
                    return Ok(ReadLineResult::Eof);
                }
            }
            (_, KeyCode::Enter) => {
                write!(stdout(), "\r\n")?;
                stdout().flush()?;
                return Ok(ReadLineResult::Line(input));
            }
            (KeyModifiers::CONTROL, KeyCode::Char('a')) | (_, KeyCode::Home) => {
                cursor_pos = 0;
            }
            (KeyModifiers::CONTROL, KeyCode::Char('e')) | (_, KeyCode::End) => {
                cursor_pos = char_count(&input);
            }
            (KeyModifiers::CONTROL, KeyCode::Char('u')) => {
                input.clear();
                cursor_pos = 0;
            }
            (KeyModifiers::ALT, KeyCode::Backspace) => {
                let boundary = prev_word_boundary(&input, cursor_pos);
                let start = byte_offset(&input, boundary);
                let end = byte_offset(&input, cursor_pos);
                input.drain(start..end);
                cursor_pos = boundary;
            }
            (_, KeyCode::Backspace) => {
                if cursor_pos > 0 {
                    let off = byte_offset(&input, cursor_pos - 1);
                    input.remove(off);
                    cursor_pos -= 1;
                }
            }
            (_, KeyCode::Delete) => {
                if cursor_pos < char_count(&input) {
                    let off = byte_offset(&input, cursor_pos);
                    input.remove(off);
                }
            }
            (_, KeyCode::Left) => {
                cursor_pos = cursor_pos.saturating_sub(1);
            }
            (_, KeyCode::Right) => {
                if cursor_pos < char_count(&input) {
                    cursor_pos += 1;
                }
            }
            (_, KeyCode::Up) => {
                navigate_history_up(
                    history,
                    &mut input,
                    &mut cursor_pos,
                    &mut history_index,
                    &mut draft,
                );
            }
            (_, KeyCode::Down) => {
                navigate_history_down(
                    history,
                    &mut input,
                    &mut cursor_pos,
                    &mut history_index,
                    &mut draft,
                );
            }
            (_, KeyCode::Char(c)) => {
                let off = byte_offset(&input, cursor_pos);
                input.insert(off, c);
                cursor_pos += 1;
            }
            _ => {}
        }

        render(prompt, &input, cursor_pos)?;
    }
}

fn navigate_history_up(
    history: &[String],
    input: &mut String,
    cursor_pos: &mut usize,
    history_index: &mut Option<usize>,
    draft: &mut String,
) {
    match *history_index {
        None => {
            if history.is_empty() {
                return;
            }
            draft.clone_from(input);
            let prefix = &*draft;
            let found = history
                .iter()
                .rposition(|e| prefix.is_empty() || e.starts_with(prefix));
            let Some(idx) = found else { return };
            *history_index = Some(idx);
            input.clone_from(&history[idx]);
        }
        Some(i) => {
            let prefix = &*draft;
            let found = history[..i]
                .iter()
                .rposition(|e| prefix.is_empty() || e.starts_with(prefix));
            let Some(idx) = found else { return };
            *history_index = Some(idx);
            input.clone_from(&history[idx]);
        }
    }
    *cursor_pos = char_count(input);
}

fn navigate_history_down(
    history: &[String],
    input: &mut String,
    cursor_pos: &mut usize,
    history_index: &mut Option<usize>,
    draft: &mut String,
) {
    let Some(i) = *history_index else { return };
    let prefix = &*draft;
    let found = history[i + 1..]
        .iter()
        .position(|e| prefix.is_empty() || e.starts_with(prefix))
        .map(|offset| i + 1 + offset);
    if let Some(idx) = found {
        *history_index = Some(idx);
        input.clone_from(&history[idx]);
    } else {
        *history_index = None;
        *input = std::mem::take(draft);
    }
    *cursor_pos = char_count(input);
}

fn render(prompt: &str, input: &str, cursor_pos: usize) -> io::Result<()> {
    let mut out = stdout();
    let prefix: String = input.chars().take(cursor_pos).collect();
    let cursor_col = prompt.len() + unicode_display_width(&prefix);
    write!(
        out,
        "\r{}{}{}{}",
        terminal::Clear(ClearType::CurrentLine),
        prompt,
        input,
        cursor::MoveToColumn(u16::try_from(cursor_col).unwrap_or(u16::MAX)),
    )?;
    out.flush()
}

fn char_count(s: &str) -> usize {
    s.chars().count()
}

fn byte_offset(s: &str, char_idx: usize) -> usize {
    s.char_indices().nth(char_idx).map_or(s.len(), |(i, _)| i)
}

fn prev_word_boundary(s: &str, cursor: usize) -> usize {
    let chars: Vec<char> = s.chars().collect();
    let mut i = cursor;
    while i > 0 && !chars[i - 1].is_alphanumeric() {
        i -= 1;
    }
    while i > 0 && chars[i - 1].is_alphanumeric() {
        i -= 1;
    }
    i
}

fn unicode_display_width(s: &str) -> usize {
    use unicode_width::UnicodeWidthStr;
    UnicodeWidthStr::width(s)
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::*;

    #[test]
    fn read_line_piped_returns_line() {
        let mut reader = Cursor::new(b"hello world\n");
        let result = read_line_piped(&mut reader).unwrap();
        assert!(matches!(result, ReadLineResult::Line(l) if l == "hello world"));
    }

    #[test]
    fn read_line_piped_strips_crlf() {
        let mut reader = Cursor::new(b"hello\r\n");
        let result = read_line_piped(&mut reader).unwrap();
        assert!(matches!(result, ReadLineResult::Line(l) if l == "hello"));
    }

    #[test]
    fn read_line_piped_returns_eof_on_empty() {
        let mut reader = Cursor::new(b"");
        let result = read_line_piped(&mut reader).unwrap();
        assert!(matches!(result, ReadLineResult::Eof));
    }

    #[test]
    fn read_line_piped_no_newline_at_eof() {
        let mut reader = Cursor::new(b"no newline");
        let result = read_line_piped(&mut reader).unwrap();
        assert!(matches!(result, ReadLineResult::Line(l) if l == "no newline"));
    }

    #[test]
    fn read_line_piped_multi_line_sequence() {
        let mut reader = Cursor::new(b"line1\nline2\n");
        let r1 = read_line_piped(&mut reader).unwrap();
        assert!(matches!(r1, ReadLineResult::Line(l) if l == "line1"));
        let r2 = read_line_piped(&mut reader).unwrap();
        assert!(matches!(r2, ReadLineResult::Line(l) if l == "line2"));
        let r3 = read_line_piped(&mut reader).unwrap();
        assert!(matches!(r3, ReadLineResult::Eof));
    }

    #[test]
    fn char_count_ascii() {
        assert_eq!(char_count("hello"), 5);
        assert_eq!(char_count(""), 0);
    }

    #[test]
    fn char_count_unicode() {
        assert_eq!(char_count("héllo"), 5);
        assert_eq!(char_count("日本語"), 3);
    }

    #[test]
    fn byte_offset_start() {
        assert_eq!(byte_offset("hello", 0), 0);
    }

    #[test]
    fn byte_offset_end() {
        assert_eq!(byte_offset("hello", 5), 5);
    }

    #[test]
    fn byte_offset_beyond() {
        assert_eq!(byte_offset("hello", 100), 5);
    }

    #[test]
    fn byte_offset_unicode() {
        // "é" is 2 bytes, so char index 1 = byte offset 2
        let s = "éllo";
        assert_eq!(byte_offset(s, 1), 2);
    }

    #[test]
    fn prev_word_boundary_from_end() {
        // "hello world" cursor at 11 (end), boundary should be at start of "world"=6
        assert_eq!(prev_word_boundary("hello world", 11), 6);
    }

    #[test]
    fn prev_word_boundary_at_start() {
        assert_eq!(prev_word_boundary("hello", 0), 0);
    }

    #[test]
    fn prev_word_boundary_skips_spaces() {
        // "hello   world" cursor after spaces at 8, boundary = after "hello" at 5? no, past spaces
        // spaces are non-alphanumeric, then alphanumeric of "hello"
        assert_eq!(prev_word_boundary("hello   world", 8), 0);
    }

    #[test]
    fn navigate_history_up_empty_history_no_op() {
        let history: Vec<String> = vec![];
        let mut input = String::from("test");
        let mut cursor = 4;
        let mut idx = None;
        let mut draft = String::new();
        navigate_history_up(&history, &mut input, &mut cursor, &mut idx, &mut draft);
        assert_eq!(input, "test");
        assert!(idx.is_none());
    }

    #[test]
    fn navigate_history_up_selects_last_entry() {
        let history = vec!["cmd1".to_string(), "cmd2".to_string()];
        let mut input = String::new();
        let mut cursor = 0;
        let mut idx = None;
        let mut draft = String::new();
        navigate_history_up(&history, &mut input, &mut cursor, &mut idx, &mut draft);
        assert_eq!(input, "cmd2");
        assert_eq!(idx, Some(1));
        assert_eq!(cursor, 4);
    }

    #[test]
    fn navigate_history_up_twice_goes_further_back() {
        let history = vec!["cmd1".to_string(), "cmd2".to_string()];
        let mut input = String::new();
        let mut cursor = 0;
        let mut idx = None;
        let mut draft = String::new();
        navigate_history_up(&history, &mut input, &mut cursor, &mut idx, &mut draft);
        navigate_history_up(&history, &mut input, &mut cursor, &mut idx, &mut draft);
        assert_eq!(input, "cmd1");
        assert_eq!(idx, Some(0));
    }

    #[test]
    fn navigate_history_down_restores_draft() {
        let history = vec!["cmd1".to_string()];
        // Simulate having gone up: idx is Some(0), input is the history entry
        let mut input = String::from("cmd1");
        let mut cursor = 4;
        let mut idx = Some(0);
        // Draft preserves what the user typed before navigating up
        let mut draft = String::from("draft");
        // Now go back down — should restore draft
        navigate_history_down(&history, &mut input, &mut cursor, &mut idx, &mut draft);
        assert_eq!(input, "draft");
        assert!(idx.is_none());
    }

    #[test]
    fn navigate_history_down_no_op_when_no_index() {
        let history = vec!["cmd1".to_string()];
        let mut input = String::from("unchanged");
        let mut cursor = 9;
        let mut idx = None;
        let mut draft = String::new();
        navigate_history_down(&history, &mut input, &mut cursor, &mut idx, &mut draft);
        assert_eq!(input, "unchanged");
    }
}