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