taria 0.2.0

Agent accessibility layer for terminal user interfaces. Lets TUI apps expose their widget tree, focus state, and available actions to AI agents, like ARIA does for the web.
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Textual key grammar for [`AgentInput::Key`](crate::AgentInput::Key).
//!
//! The wire carries a key as a plain string, so both peers must agree on what
//! that string means. This module is that agreement: the app side lowers a
//! [`KeyPress`] into its framework's key event, and the bridge parses the same
//! grammar to reject a malformed key before it costs a round trip. Keeping one
//! parser here is what makes the two verdicts identical.
//!
//! These types are deliberately not serde-serializable. The wire form of a key
//! is the string, and adding a second encoding would let the two drift.
//!
//! [`KeyPress`] implements [`FromStr`] and [`Display`](fmt::Display), and the
//! two round-trip: every press the parser can produce renders to a string that
//! parses back to the same press.

use std::error::Error;
use std::fmt;
use std::str::FromStr;

/// Human-readable summary of the key grammar, phrased to follow "expected".
///
/// Shared so the parser's error message and an agent-facing tool description
/// cannot describe different grammars.
pub const KEY_GRAMMAR: &str = "a single character (`a`, `Q`, `?`, `+`), or a named key (enter, \
     esc, tab, backtab, backspace, delete, up, down, left, right, home, end, pageup, pagedown, \
     space, f1 through f12, plus the aliases return, escape, del), optionally prefixed with \
     modifiers joined by `+` (ctrl, alt, shift; `control` is an alias for ctrl). Names and \
     modifiers are case-insensitive, a single character keeps its case. Examples: `q`, `Q`, \
     `ctrl+c`, `alt+enter`, `ctrl+shift+p`, `space`";

/// A key with no modifiers applied, the base of a [`KeyPress`].
///
/// `Char` holds the character verbatim, so case is meaningful: `Char('Q')` and
/// `Char('q')` are different presses.
///
/// `#[non_exhaustive]` because the grammar is expected to learn keys (insert,
/// the keypad, media keys) that terminals already deliver. A key added here is
/// additive on the wire, since it travels as a string every peer parses with
/// this module, but an adapter lowering keys into its framework matches on
/// this enum: without the attribute, one new key fails to compile every
/// adapter, which is the population taria exists to attract.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Key {
    /// A literal character, including `Char(' ')` for the space bar.
    Char(char),
    Enter,
    Esc,
    Tab,
    /// Backwards tab, what a terminal delivers for shift+tab.
    BackTab,
    Backspace,
    Delete,
    Up,
    Down,
    Left,
    Right,
    Home,
    End,
    PageUp,
    PageDown,
    /// Function key, `F(1)` through `F(12)`.
    F(u8),
}

/// Modifier keys held during a [`KeyPress`].
///
/// `#[non_exhaustive]` because terminals report modifiers this set does not
/// carry yet (super, hyper, meta), and adding a field is the cheapest way to
/// grow the grammar. Nothing outside this crate loses anything to it:
/// [`NONE`](Self::NONE) and [`new`](Self::new) are both const and together
/// reach every value a struct literal could build.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Modifiers {
    pub ctrl: bool,
    pub alt: bool,
    pub shift: bool,
}

impl Modifiers {
    /// No modifiers held.
    pub const NONE: Self = Self {
        ctrl: false,
        alt: false,
        shift: false,
    };

    /// Build a set of held modifiers, in the order the grammar spells them.
    ///
    /// Const so it can stand wherever [`NONE`](Self::NONE) does. It exists
    /// because the alternative is a struct literal naming all three fields,
    /// which is the one form of construction a type closed to outside
    /// construction cannot offer.
    pub const fn new(ctrl: bool, alt: bool, shift: bool) -> Self {
        Self { ctrl, alt, shift }
    }
}

/// One key press: a [`Key`] plus the [`Modifiers`] held with it.
///
/// `#[non_exhaustive]` for the reason both of its field types carry it. A press
/// is what an adapter takes by value ([`to_crossterm`] in `taria-ratatui` is
/// the reference one), so the population that builds and destructures this
/// struct is the same population a new field would break. The field this
/// grammar is most likely to grow is the press/repeat/release distinction the
/// Kitty protocol reports, which is additive on the wire because keys travel
/// as strings, and would otherwise fail to compile every third-party adapter.
/// [`new`](Self::new) is const and names both fields, so a peer keeps the one
/// thing the attribute takes away.
///
/// [`to_crossterm`]: https://docs.rs/taria-ratatui/latest/taria_ratatui/fn.to_crossterm.html
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct KeyPress {
    pub key: Key,
    pub modifiers: Modifiers,
}

impl KeyPress {
    /// Build a press from its parts.
    pub const fn new(key: Key, modifiers: Modifiers) -> Self {
        Self { key, modifiers }
    }
}

/// A key string that does not match the grammar.
///
/// Keeps the rejected input so the message can name it: an agent that guessed
/// a key name needs to see which guess failed to correct itself.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyParseError {
    input: String,
}

impl KeyParseError {
    /// The input that was rejected, verbatim.
    pub fn input(&self) -> &str {
        &self.input
    }
}

impl fmt::Display for KeyParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unrecognized key `{}`; expected {KEY_GRAMMAR}",
            self.input
        )
    }
}

impl Error for KeyParseError {}

impl FromStr for KeyPress {
    type Err = KeyParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parse(s).ok_or_else(|| KeyParseError {
            input: s.to_string(),
        })
    }
}

/// Parse the grammar, or `None` if the input does not match it.
///
/// Split out so [`FromStr`] owns the one place that builds the error, and so
/// every failure path is an early `None` rather than a panic.
fn parse(s: &str) -> Option<KeyPress> {
    // A lone space is a legitimate key and would be destroyed by trimming, so
    // it has to be answered before the trim below.
    if s == " " {
        return Some(KeyPress::new(Key::Char(' '), Modifiers::NONE));
    }
    let trimmed = s.trim();

    // Peel off modifier prefixes: everything before a `+` that names a
    // modifier. A `+` that opens or closes the remainder is the base key
    // rather than a separator, which is what lets `"ctrl++"` mean ctrl plus
    // the `+` character while `"+a"` and `"ctrl+"` stay errors.
    let mut modifiers = Modifiers::NONE;
    let mut rest = trimmed;
    while let Some(pos) = rest.find('+') {
        if pos == 0 || pos + 1 >= rest.len() {
            break;
        }
        // `find` reports a char boundary, so both slices always exist; `get`
        // keeps this function free of indexing that could panic.
        let (name, tail) = (rest.get(..pos)?, rest.get(pos + 1..)?);
        match name.to_ascii_lowercase().as_str() {
            "ctrl" | "control" => modifiers.ctrl = true,
            "alt" => modifiers.alt = true,
            "shift" => modifiers.shift = true,
            _ => break,
        }
        rest = tail;
    }

    // A single-character base is taken literally, case preserved.
    let mut chars = rest.chars();
    if let (Some(c), None) = (chars.next(), chars.next()) {
        return Some(KeyPress::new(Key::Char(c), modifiers));
    }

    let key = match rest.to_ascii_lowercase().as_str() {
        "enter" | "return" => Key::Enter,
        "esc" | "escape" => Key::Esc,
        // Terminals deliver shift+tab as a distinct backwards tab, so the two
        // spellings have to land on the same press.
        "tab" => {
            if modifiers.shift {
                Key::BackTab
            } else {
                Key::Tab
            }
        }
        "backtab" => {
            modifiers.shift = true;
            Key::BackTab
        }
        "backspace" => Key::Backspace,
        "delete" | "del" => Key::Delete,
        "up" => Key::Up,
        "down" => Key::Down,
        "left" => Key::Left,
        "right" => Key::Right,
        "home" => Key::Home,
        "end" => Key::End,
        "pageup" => Key::PageUp,
        "pagedown" => Key::PageDown,
        "space" => Key::Char(' '),
        other => {
            // Spelled out rather than handed to `parse`, whose integer grammar
            // is wider than this one: it accepts a leading `+` and leading
            // zeros, so `f+1`, `f01` and `f0000001` all reached `F(1)` while
            // the grammar advertises `f1` through `f12` and nothing else. Each
            // of them renders back as `f1`, leaving an agent comparing its
            // request to the canonical form with a mismatch it cannot explain.
            let digits = other.strip_prefix('f')?;
            if digits.is_empty()
                || digits.len() > 2
                || !digits.bytes().all(|b| b.is_ascii_digit())
                || digits.starts_with('0')
            {
                return None;
            }
            let n: u8 = digits.parse().ok()?;
            if (1..=12).contains(&n) {
                Key::F(n)
            } else {
                return None;
            }
        }
    };
    Some(KeyPress::new(key, modifiers))
}

impl fmt::Display for Key {
    /// Write the base key without modifiers.
    ///
    /// `Char(' ')` renders as `space`, never a literal space, so that a
    /// modified press such as `ctrl+space` stays parseable. `BackTab` renders
    /// as `backtab`, which parses back with shift already set.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Key::Char(' ') => f.write_str("space"),
            Key::Char(c) => write!(f, "{c}"),
            Key::Enter => f.write_str("enter"),
            Key::Esc => f.write_str("esc"),
            Key::Tab => f.write_str("tab"),
            Key::BackTab => f.write_str("backtab"),
            Key::Backspace => f.write_str("backspace"),
            Key::Delete => f.write_str("delete"),
            Key::Up => f.write_str("up"),
            Key::Down => f.write_str("down"),
            Key::Left => f.write_str("left"),
            Key::Right => f.write_str("right"),
            Key::Home => f.write_str("home"),
            Key::End => f.write_str("end"),
            Key::PageUp => f.write_str("pageup"),
            Key::PageDown => f.write_str("pagedown"),
            Key::F(n) => write!(f, "f{n}"),
        }
    }
}

impl fmt::Display for KeyPress {
    /// Write the canonical form: modifiers in ctrl, alt, shift order, then the
    /// base key.
    ///
    /// `BackTab` already implies shift on the way back in, so no `shift+`
    /// prefix is emitted for it. Every press the parser can produce round-trips
    /// through this form; a hand-built `BackTab` with `shift: false` cannot,
    /// because the parser never produces one.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.modifiers.ctrl {
            f.write_str("ctrl+")?;
        }
        if self.modifiers.alt {
            f.write_str("alt+")?;
        }
        if self.modifiers.shift && self.key != Key::BackTab {
            f.write_str("shift+")?;
        }
        write!(f, "{}", self.key)
    }
}

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

    const NONE: Modifiers = Modifiers::NONE;
    const CTRL: Modifiers = Modifiers {
        ctrl: true,
        alt: false,
        shift: false,
    };
    const ALT: Modifiers = Modifiers {
        ctrl: false,
        alt: true,
        shift: false,
    };
    const SHIFT: Modifiers = Modifiers {
        ctrl: false,
        alt: false,
        shift: true,
    };
    const CTRL_ALT: Modifiers = Modifiers {
        ctrl: true,
        alt: true,
        shift: false,
    };
    const CTRL_SHIFT: Modifiers = Modifiers {
        ctrl: true,
        alt: false,
        shift: true,
    };

    fn press(input: &str) -> Option<KeyPress> {
        input.parse::<KeyPress>().ok()
    }

    /// Three bools in a row is exactly the shape a transposition hides in, so
    /// the constructor is pinned against the literals rather than assumed.
    #[test]
    fn modifiers_new_takes_its_arguments_in_field_order() {
        assert_eq!(Modifiers::new(false, false, false), Modifiers::NONE);
        assert_eq!(Modifiers::new(true, false, false), CTRL);
        assert_eq!(Modifiers::new(false, true, false), ALT);
        assert_eq!(Modifiers::new(false, false, true), SHIFT);
        assert_eq!(Modifiers::new(true, true, false), CTRL_ALT);
        assert_eq!(Modifiers::new(true, false, true), CTRL_SHIFT);
    }

    #[test]
    fn single_characters_parse_literally() {
        let cases = [
            ("a", 'a'),
            ("Q", 'Q'),
            ("?", '?'),
            ("+", '+'),
            ("/", '/'),
            (" ", ' '),
            ("é", 'é'),
        ];
        for (input, expected) in cases {
            assert_eq!(
                press(input),
                Some(KeyPress::new(Key::Char(expected), NONE)),
                "input: {input:?}"
            );
        }
    }

    #[test]
    fn named_keys_parse_case_insensitively() {
        let cases = [
            ("enter", Key::Enter),
            ("Enter", Key::Enter),
            ("RETURN", Key::Enter),
            ("esc", Key::Esc),
            ("escape", Key::Esc),
            ("tab", Key::Tab),
            ("backspace", Key::Backspace),
            ("delete", Key::Delete),
            ("del", Key::Delete),
            ("up", Key::Up),
            ("down", Key::Down),
            ("left", Key::Left),
            ("right", Key::Right),
            ("home", Key::Home),
            ("end", Key::End),
            ("pageup", Key::PageUp),
            ("PageDown", Key::PageDown),
            ("space", Key::Char(' ')),
            ("f1", Key::F(1)),
            ("F12", Key::F(12)),
        ];
        for (input, key) in cases {
            assert_eq!(
                press(input),
                Some(KeyPress::new(key, NONE)),
                "input: {input:?}"
            );
        }
    }

    #[test]
    fn modifiers_combine() {
        let cases = [
            ("ctrl+c", Key::Char('c'), CTRL),
            ("CTRL+c", Key::Char('c'), CTRL),
            ("control+c", Key::Char('c'), CTRL),
            ("alt+enter", Key::Enter, ALT),
            ("shift+f5", Key::F(5), SHIFT),
            ("ctrl+alt+delete", Key::Delete, CTRL_ALT),
            ("ctrl+shift+p", Key::Char('p'), CTRL_SHIFT),
            ("ctrl++", Key::Char('+'), CTRL),
        ];
        for (input, key, modifiers) in cases {
            assert_eq!(
                press(input),
                Some(KeyPress::new(key, modifiers)),
                "input: {input:?}"
            );
        }
    }

    #[test]
    fn shift_tab_and_backtab_are_backtab_with_shift() {
        assert_eq!(press("shift+tab"), Some(KeyPress::new(Key::BackTab, SHIFT)));
        assert_eq!(press("backtab"), Some(KeyPress::new(Key::BackTab, SHIFT)));
    }

    #[test]
    fn invalid_inputs_are_rejected() {
        let rejects = [
            "",
            "nope",
            "f0",
            "f13",
            "f99",
            "ctrl",
            "ctrl+",
            "+a",
            "meta+x",
            "enterx",
            "ab",
            "ctrl+nope",
            // Spellings Rust's integer parser would take for `f1`. The
            // grammar advertises `f1` through `f12`, and all of these render
            // back as `f1`, so accepting them hands an agent a canonical form
            // it cannot derive from what it sent.
            "f+1",
            "f01",
            "f0000001",
            "ctrl+f+1",
            "f 1",
            "f1",
        ];
        for input in rejects {
            assert_eq!(press(input), None, "input: {input:?}");
        }
    }

    #[test]
    fn display_roundtrips_through_from_str() {
        // Every variant of `Key`, both spellings of space, the `+` base key,
        // and both spellings of backtab.
        let inputs = [
            "a",
            "Q",
            "?",
            " ",
            "space",
            "é",
            "ctrl++",
            "ctrl+space",
            "enter",
            "esc",
            "tab",
            "backtab",
            "shift+tab",
            "ctrl+backtab",
            "backspace",
            "delete",
            "up",
            "down",
            "left",
            "right",
            "home",
            "end",
            "pageup",
            "pagedown",
            "f1",
            "f12",
            "shift+f5",
            "ctrl+alt+shift+enter",
        ];
        for input in inputs {
            let parsed = press(input).unwrap_or_else(|| panic!("input: {input:?}"));
            let rendered = parsed.to_string();
            assert!(
                !rendered.contains(' ') || rendered == "space",
                "canonical form of {input:?} has a literal space: {rendered:?}"
            );
            assert_eq!(
                press(&rendered),
                Some(parsed),
                "input {input:?} rendered as {rendered:?}"
            );
        }
    }

    #[test]
    fn canonical_form_normalizes_spelling_and_order() {
        let cases = [
            (" ", "space"),
            ("space", "space"),
            ("Q", "Q"),
            ("ctrl++", "ctrl++"),
            ("CTRL+c", "ctrl+c"),
            ("control+c", "ctrl+c"),
            ("backtab", "backtab"),
            ("shift+tab", "backtab"),
            ("ctrl+backtab", "ctrl+backtab"),
            ("shift+alt+ctrl+enter", "ctrl+alt+shift+enter"),
            ("F12", "f12"),
        ];
        for (input, expected) in cases {
            let parsed = press(input).unwrap_or_else(|| panic!("input: {input:?}"));
            assert_eq!(parsed.to_string(), expected, "input: {input:?}");
        }
    }

    #[test]
    fn error_names_the_offending_input() {
        let err = "ctrl+nope".parse::<KeyPress>().unwrap_err();
        assert_eq!(err.input(), "ctrl+nope");
        let message = err.to_string();
        assert!(message.contains("ctrl+nope"), "message: {message}");
        assert!(message.contains("pagedown"), "message: {message}");
    }
}