Skip to main content

rigspark_cli/
terminal.rs

1use rigspark_runtime::harness::HarnessMessage;
2use std::io::{self, BufRead, Write};
3use tokio::sync::mpsc;
4use tokio_util::sync::CancellationToken;
5use unicode_segmentation::UnicodeSegmentation;
6
7const MAX_LINE_BYTES: usize = 32 * 1024;
8const MAX_DRAFT_GRAPHEMES: usize = 8192;
9const MAX_RESPONSE_BYTES: usize = 1024 * 1024;
10
11pub(crate) fn validate_draft(draft: &str) -> io::Result<()> {
12    if draft.len() > MAX_LINE_BYTES {
13        return Err(io::Error::other(format!(
14            "Draft exceeds {MAX_LINE_BYTES} byte limit ({} bytes)",
15            draft.len()
16        )));
17    }
18    for (actual, limit, unit, plural) in [
19        (
20            draft.graphemes(true).count(),
21            MAX_DRAFT_GRAPHEMES,
22            "grapheme",
23            "graphemes",
24        ),
25        (draft.split('\n').count(), 256, "line", "lines"),
26    ] {
27        if actual > limit {
28            return Err(io::Error::other(format!(
29                "Draft exceeds {limit} {unit} limit ({actual} {plural})"
30            )));
31        }
32    }
33    Ok(())
34}
35
36#[derive(Clone, Copy, PartialEq, Eq)]
37pub enum Mode {
38    Plain,
39    Accessible,
40}
41pub struct ChatReply {
42    pub content: String,
43    pub memory_warning: bool,
44}
45pub trait ChatEngine {
46    fn reply(
47        &self,
48        messages: &[HarnessMessage],
49        cancel: &CancellationToken,
50    ) -> impl std::future::Future<Output = Result<ChatReply, String>>;
51
52    /// Like `reply`, also forwarding partial output as it arrives; the final reply stays authoritative.
53    fn reply_streaming(
54        &self,
55        messages: &[HarnessMessage],
56        cancel: &CancellationToken,
57        deltas: mpsc::UnboundedSender<String>,
58    ) -> impl std::future::Future<Output = Result<ChatReply, String>> {
59        drop(deltas);
60        self.reply(messages, cancel)
61    }
62}
63#[derive(Default)]
64pub struct ChatSummary {
65    pub turns: usize,
66    pub memory_warnings: usize,
67    pub failed_turns: usize,
68    pub cancelled: bool,
69}
70
71pub fn read_turn(input: &mut impl BufRead) -> io::Result<Option<String>> {
72    let mut bytes = Vec::new();
73    loop {
74        let available = input.fill_buf()?;
75        if available.is_empty() {
76            if bytes.is_empty() {
77                return Ok(None);
78            }
79            break;
80        }
81        let newline = available.iter().position(|byte| *byte == b'\n');
82        let count = newline.map_or(available.len(), |index| index + 1);
83        if bytes.len() + count > MAX_LINE_BYTES + 2 {
84            return Err(io::Error::new(
85                io::ErrorKind::InvalidInput,
86                "chat line exceeds 32 KiB",
87            ));
88        }
89        bytes.extend_from_slice(&available[..count]);
90        input.consume(count);
91        if newline.is_some() {
92            break;
93        }
94    }
95    if bytes.last() == Some(&b'\n') {
96        bytes.pop();
97    }
98    if bytes.last() == Some(&b'\r') {
99        bytes.pop();
100    }
101    if bytes.len() > MAX_LINE_BYTES {
102        return Err(io::Error::new(
103            io::ErrorKind::InvalidInput,
104            "chat line exceeds 32 KiB",
105        ));
106    }
107    String::from_utf8(bytes)
108        .map(Some)
109        .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "chat input must be UTF-8"))
110}
111
112pub fn stdin_turns() -> mpsc::Receiver<io::Result<String>> {
113    let (sender, receiver) = mpsc::channel(1);
114    std::thread::spawn(move || {
115        let mut input = io::stdin().lock();
116        loop {
117            match read_turn(&mut input) {
118                Ok(Some(line)) => {
119                    if sender.blocking_send(Ok(line)).is_err() {
120                        break;
121                    }
122                }
123                Ok(None) => break,
124                Err(error) => {
125                    let _ = sender.blocking_send(Err(error));
126                    break;
127                }
128            }
129        }
130    });
131    receiver
132}
133
134pub async fn run_chat(
135    mut input: mpsc::Receiver<io::Result<String>>,
136    engine: &impl ChatEngine,
137    mode: Mode,
138    cancel: &CancellationToken,
139    output: &mut impl Write,
140    diagnostic: &mut impl Write,
141) -> io::Result<ChatSummary> {
142    let mut summary = ChatSummary::default();
143    let mut history = Vec::new();
144    loop {
145        let turn = tokio::select! {
146            biased;
147            _ = cancel.cancelled() => { summary.cancelled = true; break; },
148            turn = input.recv() => match turn { Some(turn) => turn?, None => break },
149        };
150        if turn.trim().is_empty() {
151            continue;
152        }
153        if let Err(error) = validate_draft(&turn) {
154            summary.failed_turns += 1;
155            writeln!(diagnostic, "chat: {error}")?;
156            continue;
157        }
158        let mut context = history.clone();
159        context.push(HarnessMessage {
160            role: "user".into(),
161            content: turn.clone(),
162        });
163        if context.len() > 20 {
164            context.drain(..context.len() - 20);
165        }
166        if mode == Mode::Accessible {
167            writeln!(diagnostic, "Waiting for response...")?;
168            diagnostic.flush()?;
169        }
170        let reply = tokio::select! {
171            biased;
172            _ = cancel.cancelled() => { summary.cancelled = true; break; },
173            reply = engine.reply(&context, cancel) => reply,
174        };
175        let reply = match reply {
176            Ok(reply) => reply,
177            Err(error) => {
178                summary.failed_turns += 1;
179                writeln!(
180                    diagnostic,
181                    "chat: {}",
182                    rigspark_core::reports::strip_control(&error)
183                )?;
184                continue;
185            }
186        };
187        if cancel.is_cancelled() {
188            summary.cancelled = true;
189            break;
190        }
191        if reply.content.len() > MAX_RESPONSE_BYTES {
192            summary.failed_turns += 1;
193            writeln!(diagnostic, "chat: response exceeds 1 MiB limit")?;
194            continue;
195        }
196        let visible = rigspark_runtime::sessions::gui_text(&reply.content);
197        if mode == Mode::Plain {
198            writeln!(output, "{visible}")?;
199            output.flush()?;
200        } else {
201            writeln!(diagnostic, "{visible}")?;
202            diagnostic.flush()?;
203        }
204        history.push(HarnessMessage {
205            role: "user".into(),
206            content: turn,
207        });
208        history.push(HarnessMessage {
209            role: "assistant".into(),
210            content: reply.content,
211        });
212        if history.len() > 20 {
213            history.drain(..history.len() - 20);
214        }
215        summary.turns += 1;
216        if reply.memory_warning {
217            summary.memory_warnings += 1;
218            writeln!(diagnostic, "chat: failed to record memory")?;
219        }
220    }
221    if mode == Mode::Accessible {
222        writeln!(
223            output,
224            "Chat session ended: {} turn{}, {} memory warning{}.",
225            summary.turns,
226            if summary.turns == 1 { "" } else { "s" },
227            summary.memory_warnings,
228            if summary.memory_warnings == 1 {
229                ""
230            } else {
231                "s"
232            }
233        )?;
234    }
235    Ok(summary)
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn draft_validation_matches_legacy_inclusive_limits_and_diagnostics() {
244        assert_eq!(MAX_LINE_BYTES, 32768);
245        assert_eq!(MAX_DRAFT_GRAPHEMES, 8192);
246        assert_eq!(MAX_RESPONSE_BYTES, 1048576);
247        let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}";
248        assert_eq!(family.graphemes(true).count(), 1);
249        for draft in [
250            String::new(),
251            "Hello, world!".into(),
252            "a".repeat(8192),
253            "\u{1f600}".repeat(8192),
254            family.repeat(100),
255            "x\n".repeat(255),
256        ] {
257            validate_draft(&draft).unwrap();
258        }
259        for (draft, error) in [
260            (
261                "a".repeat(40000),
262                "Draft exceeds 32768 byte limit (40000 bytes)",
263            ),
264            (
265                "\u{1f600}".repeat(8193),
266                "Draft exceeds 32768 byte limit (32772 bytes)",
267            ),
268            (
269                "a".repeat(32768),
270                "Draft exceeds 8192 grapheme limit (32768 graphemes)",
271            ),
272            (
273                "a".repeat(9000),
274                "Draft exceeds 8192 grapheme limit (9000 graphemes)",
275            ),
276            (
277                "\n".repeat(9000),
278                "Draft exceeds 8192 grapheme limit (9000 graphemes)",
279            ),
280            (
281                "x\n".repeat(299),
282                "Draft exceeds 256 line limit (300 lines)",
283            ),
284        ] {
285            assert_eq!(validate_draft(&draft).unwrap_err().to_string(), error);
286        }
287    }
288}