Skip to main content

robonix_executor/
output_view.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2//! Saved copies of long capability output.
3//!
4//! A result longer than the inline limit is kept whole in a file under the
5//! system temporary directory, and the model receives the file's path, size,
6//! line count and a preview, which it searches with the `run_command` builtin.
7//! Nothing here limits or deletes saved files: they live as long as the
8//! temporary directory keeps them. Verification always uses the original result.
9use crate::pb::pilot::CapabilityCallResult;
10use std::fs;
11use std::io::{self, BufRead, Write};
12use std::path::{Path, PathBuf};
13use std::sync::Mutex;
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::time::{SystemTime, UNIX_EPOCH};
16
17/// Characters of a saved file shown to the model next to its path.
18const PREVIEW_CHARS: usize = 512;
19
20/// How the model should use a saved file instead of repeating the call.
21pub(crate) const SEARCH_NOTE: &str = "Preview only. Search the saved file with run_command \
22    (rg -n, or grep -n -F), then read the matching lines with sed -n. It holds this call's \
23    output at observed_unix, not current state; do not repeat the call to recover it.";
24
25/// What the model should do when output could not be saved completely.
26pub(crate) const STORAGE_NOTE: &str = "The full output could not be saved. Tell the user the \
27    system temporary directory needs attention (see storage_error) and say what is missing. \
28    The call's outcome is unchanged; do not repeat it to recover the text.";
29
30static SERIAL: AtomicU64 = AtomicU64::new(0);
31
32/// Results longer than this many UTF-8 bytes are saved instead of inlined.
33pub(crate) fn inline_bytes() -> usize {
34    std::env::var("ROBONIX_OUTPUT_INLINE_BYTES")
35        .ok()
36        .and_then(|value| value.parse().ok())
37        .unwrap_or(32 * 1024)
38}
39
40/// This process's private directory under the system temporary directory.
41pub(crate) fn output_dir() -> io::Result<PathBuf> {
42    static DIR: Mutex<Option<PathBuf>> = Mutex::new(None);
43    let mut dir = DIR.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
44    if let Some(path) = dir.as_ref() {
45        return Ok(path.clone());
46    }
47    let path = std::env::temp_dir().join(format!(
48        "robonix-output-{}-{}",
49        std::process::id(),
50        now_unix()
51    ));
52    let mut builder = fs::DirBuilder::new();
53    #[cfg(unix)]
54    std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
55    builder.create(&path)?;
56    *dir = Some(path.clone());
57    Ok(path)
58}
59
60pub(crate) fn now_unix() -> u64 {
61    SystemTime::now()
62        .duration_since(UNIX_EPOCH)
63        .unwrap_or_default()
64        .as_secs()
65}
66
67/// Create a new private file for one output.
68pub(crate) fn create(dir: &Path) -> io::Result<(PathBuf, fs::File)> {
69    let serial = SERIAL.fetch_add(1, Ordering::Relaxed);
70    let path = dir.join(format!("output-{serial}.txt"));
71    let mut options = fs::OpenOptions::new();
72    options.write(true).create_new(true);
73    #[cfg(unix)]
74    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
75    let file = options.open(&path)?;
76    Ok((path, file))
77}
78
79/// Path, size, line count and preview of a saved file.
80pub(crate) fn describe(path: &Path) -> io::Result<serde_json::Value> {
81    let mut reader = io::BufReader::new(fs::File::open(path)?);
82    let (mut bytes, mut lines, mut last, mut head) = (0u64, 0u64, b'\n', Vec::new());
83    loop {
84        let chunk = reader.fill_buf()?;
85        let Some(&end) = chunk.last() else { break };
86        let room = (PREVIEW_CHARS * 4).saturating_sub(head.len());
87        head.extend_from_slice(&chunk[..chunk.len().min(room)]);
88        lines += chunk.iter().filter(|byte| **byte == b'\n').count() as u64;
89        bytes += chunk.len() as u64;
90        last = end;
91        let read = chunk.len();
92        reader.consume(read);
93    }
94    if last != b'\n' {
95        lines += 1;
96    }
97    let preview: String = String::from_utf8_lossy(&head)
98        .chars()
99        .take(PREVIEW_CHARS)
100        .collect();
101    Ok(serde_json::json!({
102        "file": path,
103        "bytes": bytes,
104        "lines": lines,
105        "preview": preview,
106    }))
107}
108
109/// Return `result` with long text replaced by a reference to its saved copy.
110pub async fn prepare(result: &CapabilityCallResult) -> CapabilityCallResult {
111    prepare_in(result, inline_bytes(), output_dir).await
112}
113
114async fn prepare_in(
115    result: &CapabilityCallResult,
116    inline: usize,
117    dir: impl FnOnce() -> io::Result<PathBuf> + Send + 'static,
118) -> CapabilityCallResult {
119    let mut view = result.clone();
120    if result.output.len() <= inline || is_image(&result.output) {
121        return view;
122    }
123    let text = result.output.clone();
124    let saved = tokio::task::spawn_blocking(move || save(&dir()?, &text))
125        .await
126        .unwrap_or_else(|error| Err(io::Error::other(error)));
127    let mut reference = serde_json::json!({
128        "call_id": result.call_id,
129        "contract_id": result.contract_id,
130        "observed_unix": now_unix(),
131    });
132    match saved {
133        Ok(output) => {
134            reference["output"] = output;
135            reference["note"] = SEARCH_NOTE.into();
136        }
137        Err(error) => {
138            robonix_scribe::warn!(
139                "[executor] could not save output of call_id={} to the temporary directory: {error}",
140                result.call_id
141            );
142            let preview: String = result.output.chars().take(PREVIEW_CHARS).collect();
143            reference["output"] = serde_json::json!({
144                "bytes": result.output.len(),
145                "preview": preview,
146            });
147            reference["storage_error"] = error.to_string().into();
148            reference["note"] = STORAGE_NOTE.into();
149        }
150    }
151    view.output = reference.to_string();
152    view
153}
154
155fn save(dir: &Path, text: &str) -> io::Result<serde_json::Value> {
156    let (path, mut file) = create(dir)?;
157    if let Err(error) = file.write_all(text.as_bytes()) {
158        let _ = fs::remove_file(&path);
159        return Err(error);
160    }
161    describe(&path)
162}
163
164/// Images keep their existing multimodal path in Pilot.
165fn is_image(output: &str) -> bool {
166    let Ok(value) = serde_json::from_str::<serde_json::Value>(output) else {
167        return false;
168    };
169    let text = |key: &str| value.get(key).and_then(|v| v.as_str());
170    text("image_base64").is_some_and(|data| !data.is_empty())
171        || (value.get("width").is_some()
172            && value.get("height").is_some()
173            && text("encoding").is_some_and(|encoding| encoding != "error")
174            && text("data").is_some_and(|data| !data.is_empty()))
175}
176
177#[cfg(test)]
178pub(crate) mod tests {
179    use super::*;
180
181    /// Temporary directory removed when the test ends, including on panic.
182    pub(crate) struct TempDir(pub PathBuf);
183    impl TempDir {
184        pub(crate) fn new() -> Self {
185            let path =
186                std::env::temp_dir().join(format!("robonix-output-{}", uuid::Uuid::new_v4()));
187            fs::create_dir(&path).unwrap();
188            Self(path)
189        }
190        fn source(&self) -> impl FnOnce() -> io::Result<PathBuf> + Send + 'static {
191            let path = self.0.clone();
192            move || Ok(path)
193        }
194    }
195    impl Drop for TempDir {
196        fn drop(&mut self) {
197            let _ = fs::remove_dir_all(&self.0);
198        }
199    }
200
201    fn result(output: String) -> CapabilityCallResult {
202        CapabilityCallResult {
203            call_id: "p:0".into(),
204            contract_id: "robonix/system/executor/builtin/read_capability_doc".into(),
205            success: true,
206            output,
207            ..Default::default()
208        }
209    }
210
211    #[tokio::test]
212    async fn long_result_is_saved_whole_and_original_is_unchanged() {
213        let dir = TempDir::new();
214        let text = format!("{}目标:stable-id-972\n", "manual line\n".repeat(3000)); // i18n-ok: UTF-8 tail fixture
215        let original = result(text.clone());
216        let view = prepare_in(&original, 8192, dir.source()).await;
217        assert_eq!(original.output, text);
218        assert!(view.success);
219        assert!(view.output.len() < 2048);
220        let reference: serde_json::Value = serde_json::from_str(&view.output).unwrap();
221        assert_eq!(reference["call_id"], "p:0");
222        assert_eq!(reference["output"]["lines"], 3001);
223        assert_eq!(reference["output"]["bytes"], text.len());
224        assert!(reference["observed_unix"].as_u64().unwrap() > 0);
225        let saved = fs::read(reference["output"]["file"].as_str().unwrap()).unwrap();
226        assert_eq!(saved, text.as_bytes());
227    }
228
229    #[tokio::test]
230    async fn short_results_and_images_are_not_saved() {
231        let dir = TempDir::new();
232        let image = serde_json::json!({"width": 2, "height": 2, "encoding": "jpeg", "data": "a".repeat(4000)});
233        for text in ["small".to_owned(), image.to_string()] {
234            let view = prepare_in(&result(text.clone()), 100, dir.source()).await;
235            assert_eq!(view.output, text);
236        }
237        assert_eq!(fs::read_dir(&dir.0).unwrap().count(), 0);
238        assert!(!is_image(
239            r#"{"width":1,"height":1,"encoding":"error","data":"x"}"#
240        ));
241    }
242
243    #[tokio::test]
244    async fn failed_save_reports_preview_without_changing_success() {
245        let view = prepare_in(&result("x".repeat(5000)), 100, || {
246            Err(io::Error::from_raw_os_error(28))
247        })
248        .await;
249        assert!(view.success);
250        let reference: serde_json::Value = serde_json::from_str(&view.output).unwrap();
251        assert!(reference["output"].get("file").is_none());
252        assert!(!reference["storage_error"].as_str().unwrap().is_empty());
253        assert_eq!(reference["note"], STORAGE_NOTE);
254        assert_eq!(
255            reference["output"]["preview"].as_str().unwrap().len(),
256            PREVIEW_CHARS
257        );
258    }
259
260    #[test]
261    fn saved_outputs_are_never_deleted_or_overwritten() {
262        let dir = TempDir::new();
263        let path = |saved: serde_json::Value| PathBuf::from(saved["file"].as_str().unwrap());
264        let first = path(save(&dir.0, "first").unwrap());
265        let second = path(save(&dir.0, "second").unwrap());
266        assert_ne!(first, second);
267        assert_eq!(fs::read_to_string(first).unwrap(), "first");
268        assert_eq!(fs::read_to_string(second).unwrap(), "second");
269    }
270}
浙ICP备2023005800号-2 浙公网安备33010902005384号