rpi-tools 0.35.0

Built-in agent tools (read/write/edit/bash/powershell) + ExecutionEnv, Rust port of pi harness tools
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
//! Shared shell capture for Bash, PowerShell, and interactive commands.
//!
//! Native stdout and stderr feed a bounded channel. The consumer sanitizes
//! the combined stream and retains a rolling preview. If output exceeds
//! either preview limit, the complete sanitized stream is written to a temp
//! file in batches. A terminal result advertises its path after the last
//! captured bytes have been written.
//!
//! With `return_execution_errors`, the result carries the execution error
//! together with any captured output so the caller can render both.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

use crate::env::{ExecutionEnv, FileContent, ShellExecOptions};
use crate::error::{ExecutionError, ExecutionErrorCode};
use crate::truncate::{
    trim_to_last_utf8_bytes, truncate_tail, TruncationLimit, TruncationOptions, TruncationResult,
    DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES,
};

const MAX_TAIL_BYTES: usize = DEFAULT_MAX_BYTES * 2;
const SPILL_BATCH_BYTES: usize = 64 * 1024;
const NATIVE_OUTPUT_QUEUE: usize = 16;

/// Mirrors `ShellCaptureProgress`.
#[derive(Clone)]
pub struct ShellCaptureProgress {
    pub output: String,
    pub truncation: TruncationResult,
    pub full_output_path: Option<PathBuf>,
    pub last_line_bytes: usize,
}

/// Mirrors `ShellCaptureResult`.
#[derive(Clone)]
pub struct ShellCaptureResult {
    pub output: String,
    pub truncation: TruncationResult,
    pub full_output_path: Option<PathBuf>,
    pub last_line_bytes: usize,
    pub exit_code: Option<i32>,
    pub cancelled: bool,
    pub truncated: bool,
    pub execution_error: Option<ExecutionError>,
}

/// Mirrors `ShellCaptureOptions`.
pub struct ShellCaptureOptions<'a> {
    pub shell: Option<crate::env::ShellOverride>,
    pub cwd: Option<PathBuf>,
    pub env: Option<HashMap<String, String>>,
    pub inherit_env: bool,
    pub timeout: Option<f64>,
    pub cancel: Option<&'a CancellationToken>,
    pub on_chunk: Option<Box<dyn FnMut(&str, &dyn Fn() -> ShellCaptureProgress) + Send + 'a>>,
    pub return_execution_errors: bool,
}

impl<'a> Default for ShellCaptureOptions<'a> {
    fn default() -> Self {
        Self {
            shell: None,
            cwd: None,
            env: None,
            inherit_env: true,
            timeout: None,
            cancel: None,
            on_chunk: None,
            return_execution_errors: false,
        }
    }
}

#[derive(Default)]
struct CaptureState {
    tail_output: String,
    total_bytes: usize,
    completed_lines: usize,
    current_line_bytes: usize,
    last_completed_line_bytes: usize,
}

impl CaptureState {
    fn ingest_chunk(&mut self, text: &str) {
        self.total_bytes += text.len();
        self.completed_lines += text.matches('\n').count();
        if let Some((complete, tail)) = text.rsplit_once('\n') {
            self.last_completed_line_bytes = complete
                .rsplit_once('\n')
                .map_or(self.current_line_bytes + complete.len(), |(_, line)| {
                    line.len()
                });
            self.current_line_bytes = tail.len();
        } else {
            self.current_line_bytes += text.len();
        }
        if text.len() >= MAX_TAIL_BYTES {
            self.tail_output.clear();
            self.tail_output
                .push_str(trim_to_last_utf8_bytes(text, MAX_TAIL_BYTES));
        } else {
            self.tail_output.push_str(text);
            if self.tail_output.len() > MAX_TAIL_BYTES {
                // Drop extra history once so the next few reads can append
                // without shifting the same tail for every new chunk.
                let keep = trim_to_last_utf8_bytes(
                    &self.tail_output,
                    MAX_TAIL_BYTES - DEFAULT_MAX_BYTES / 2,
                )
                .len();
                self.tail_output.drain(..self.tail_output.len() - keep);
            }
        }
    }

    fn total_lines(&self) -> usize {
        self.completed_lines + usize::from(self.current_line_bytes > 0)
    }

    fn is_truncated(&self) -> bool {
        self.total_lines() > DEFAULT_MAX_LINES || self.total_bytes > DEFAULT_MAX_BYTES
    }

    fn create_progress(&self, full_output_path: Option<PathBuf>) -> ShellCaptureProgress {
        let tail = truncate_tail(&self.tail_output, TruncationOptions::default());
        let truncated = self.is_truncated();
        let truncated_by = if truncated {
            tail.truncated_by
                .or(if self.total_bytes > DEFAULT_MAX_BYTES {
                    Some(TruncationLimit::Bytes)
                } else {
                    Some(TruncationLimit::Lines)
                })
        } else {
            None
        };
        let truncation = TruncationResult {
            truncated,
            truncated_by,
            total_lines: self.total_lines(),
            total_bytes: self.total_bytes,
            ..tail
        };
        ShellCaptureProgress {
            output: truncation.content.clone(),
            truncation,
            full_output_path,
            last_line_bytes: if self.current_line_bytes > 0 {
                self.current_line_bytes
            } else {
                self.last_completed_line_bytes
            },
        }
    }
}

struct OutputSpill {
    env: Arc<dyn ExecutionEnv>,
    path: Option<PathBuf>,
    pending: String,
    failed: bool,
}

impl OutputSpill {
    async fn record(&mut self, text: &str, truncated: bool) {
        if self.failed {
            return;
        }
        self.pending.push_str(text);
        if truncated && (self.path.is_none() || self.pending.len() >= SPILL_BATCH_BYTES) {
            self.flush().await;
        }
    }

    async fn flush(&mut self) {
        if self.pending.is_empty() {
            return;
        }
        // Flushing what has already arrived is part of settling the command.
        // It also preserves diagnostics after the execution token is cancelled.
        let result = async {
            let path = match &self.path {
                Some(path) => path,
                None => self
                    .path
                    .insert(self.env.create_temp_file("bash-", ".log", None).await?),
            };
            self.env
                .append_file(
                    &path.to_string_lossy(),
                    FileContent::Text(std::mem::take(&mut self.pending)),
                    None,
                )
                .await
        }
        .await;
        if let Err(error) = result {
            tracing::warn!("shell full-output file unavailable: {error}");
            self.failed = true;
            self.pending.clear();
            if let Some(path) = self.path.take() {
                let _ = self
                    .env
                    .remove(&path.to_string_lossy(), false, true, None)
                    .await;
            }
        }
    }

    async fn finish(mut self) -> Option<PathBuf> {
        if self.path.is_some() {
            self.flush().await;
        }
        self.path.take()
    }
}

impl Drop for OutputSpill {
    fn drop(&mut self) {
        if let (Some(path), Ok(runtime)) = (self.path.take(), tokio::runtime::Handle::try_current())
        {
            let env = self.env.clone();
            runtime.spawn(async move {
                let _ = env.remove(&path.to_string_lossy(), false, true, None).await;
            });
        }
    }
}

/// Sanitize a chunk: drop C0 controls (except TAB/LF/CR) and interlinear
/// annotation chars (U+FFF9..U+FFFB), then strip all CR. Mirrors
/// `sanitizeBinaryOutput` + the per-chunk `.replace(/\r/g, "")`.
///
/// ANSI escape sequences are consumed whole rather than having just their
/// leading ESC byte (a C0 control) dropped: dropping only ESC left the
/// sequence body behind, so colored output (e.g. `vite` build logs) surfaced
/// as literal `[36m`-style garbage in the tool response.
fn sanitize_and_strip_cr(chunk: &str) -> String {
    let mut out = String::with_capacity(chunk.len());
    let mut chars = chunk.chars().peekable();
    while let Some(c) = chars.next() {
        let u = c as u32;
        if c == '\x1b' {
            skip_escape_sequence(&mut chars);
        } else if u == 0x09 || u == 0x0a || u == 0x0d {
            out.push(c);
        } else if u <= 0x1f {
            // other C0 controls → drop
        } else if (0xfff9..=0xfffb).contains(&u) {
            // interlinear annotation → drop
        } else {
            out.push(c);
        }
    }
    out.replace('\r', "")
}

/// Consume one ANSI escape sequence, starting just after the ESC byte the
/// caller already read. Handles CSI (`ESC [ … final`), OSC (`ESC ] … BEL |
/// `ESC \`), and charset designators (`ESC ( X`); any other escape swallows a
/// single following char.
fn skip_escape_sequence(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) {
    match chars.peek() {
        Some('[') => {
            chars.next();
            // CSI: parameter/intermediate bytes, terminated by a final byte in
            // the 0x40..=0x7E range.
            while let Some(c) = chars.next() {
                if (0x40..=0x7e).contains(&(c as u32)) {
                    break;
                }
            }
        }
        Some(']') => {
            chars.next();
            // OSC: terminated by BEL (0x07) or ST (ESC \).
            while let Some(c) = chars.next() {
                if c == '\x07' {
                    break;
                }
                if c == '\x1b' {
                    if let Some('\\') = chars.peek() {
                        chars.next();
                    }
                    break;
                }
            }
        }
        Some('(') | Some(')') => {
            // Charset designator: ESC ( or ESC ) followed by one char.
            chars.next();
            chars.next();
        }
        Some(_) => {
            chars.next();
        }
        None => {}
    }
}

/// Run the shell and consume its output while the process is running.
pub async fn execute_shell_with_capture(
    env: &Arc<dyn ExecutionEnv>,
    command: &str,
    options: ShellCaptureOptions<'_>,
) -> Result<ShellCaptureResult, ExecutionError> {
    let (sender, mut receiver) = mpsc::channel::<String>(NATIVE_OUTPUT_QUEUE);
    let exec = env.exec_streamed(
        command,
        ShellExecOptions {
            shell: options.shell,
            cwd: options.cwd,
            env: options.env,
            inherit_env: options.inherit_env,
            timeout: options.timeout,
            cancel: options.cancel,
            ..Default::default()
        },
        sender,
    );
    let collect = async {
        let mut state = CaptureState::default();
        let mut spill = OutputSpill {
            env: env.clone(),
            path: None,
            pending: String::new(),
            failed: false,
        };
        let mut on_chunk = options.on_chunk;
        while let Some(chunk) = receiver.recv().await {
            let text = sanitize_and_strip_cr(&chunk);
            state.ingest_chunk(&text);
            spill.record(&text, state.is_truncated()).await;
            if let Some(callback) = on_chunk.as_mut() {
                callback(&chunk, &|| state.create_progress(None));
            }
        }
        state.create_progress(spill.finish().await)
    };

    let (exec_result, progress) = tokio::join!(exec, collect);
    let cancelled = options.cancel.is_some_and(CancellationToken::is_cancelled)
        || exec_result
            .as_ref()
            .is_err_and(|error| error.code == ExecutionErrorCode::Aborted);
    let (exit_code, execution_error) = match exec_result {
        _ if cancelled => (None, None),
        Ok(code) => (Some(code), None),
        Err(error) if options.return_execution_errors => (None, Some(error)),
        Err(error) => {
            if let Some(path) = progress.full_output_path {
                let _ = env.remove(&path.to_string_lossy(), false, true, None).await;
            }
            return Err(error);
        }
    };
    Ok(ShellCaptureResult {
        output: progress.output,
        truncated: progress.truncation.truncated,
        truncation: progress.truncation,
        full_output_path: progress.full_output_path,
        last_line_bytes: progress.last_line_bytes,
        exit_code,
        cancelled,
        execution_error,
    })
}

/// Re-export `format_size` for the bash tool's truncation footer messages.
pub use crate::truncate::format_size;

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

    #[test]
    fn sanitize_strips_controls_keeps_tab_lf() {
        let s = "a\x01b\tc\nd\x0be";
        let out = sanitize_and_strip_cr(&s);
        assert_eq!(out, "ab\tc\nde");
    }

    #[test]
    fn sanitize_strips_cr() {
        let s = "a\r\nb\rc";
        let out = sanitize_and_strip_cr(&s);
        assert_eq!(out, "a\nbc");
    }

    #[test]
    fn sanitize_strips_interlinear_annotation() {
        let s = "a\u{fff9}b\u{fffb}c";
        let out = sanitize_and_strip_cr(&s);
        assert_eq!(out, "abc");
    }

    #[test]
    fn sanitize_strips_full_ansi_sequences() {
        // Regression: dropping only the ESC byte used to leave `[36m`-style
        // literal garbage in the captured/output text.
        let s = "\x1b[36mvite v6.4.3\x1b[39m \x1b[32m\u{2713}\x1b[39m built\n";
        assert_eq!(sanitize_and_strip_cr(s), "vite v6.4.3 \u{2713} built\n");
        let s = "a\x1b[1m\x1b[2mX\x1b[22m\x1b[22mb";
        assert_eq!(sanitize_and_strip_cr(s), "aXb");
    }

    #[test]
    fn sanitize_strips_osc_sequences() {
        assert_eq!(sanitize_and_strip_cr("a\x1b]0;title\x07b"), "ab");
        assert_eq!(sanitize_and_strip_cr("a\x1b]8;;http://x\x1b\\b"), "ab");
    }

    #[test]
    fn capture_state_ingest_and_progress() {
        let mut s = CaptureState::default();
        s.ingest_chunk("line1\nline2\n");
        s.ingest_chunk("line3");
        let p = s.create_progress(None);
        // 3 lines total (line1, line2, line3-open).
        assert_eq!(p.truncation.total_lines, 3);
        assert!(!p.truncation.truncated);
        assert_eq!(p.output, "line1\nline2\nline3");
    }
}