rx4 0.4.0

The agent harness engine — loop, tools, providers, sessions, permissions, computer-use
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
//! Rollout persistence: durable JSONL event logging with buffered I/O.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use thiserror::Error;

const EVENTS_FILE: &str = "events.jsonl";
const PAYLOADS_DIR: &str = "payloads";
const PAYLOAD_THRESHOLD: usize = 1024;
/// Maximum file size for rollout events JSONL (10 MB).
const MAX_ROLLOUT_FILE_BYTES: u64 = 10 * 1024 * 1024;

#[derive(Debug, Error)]
pub enum RolloutError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("json error: {0}")]
    Json(#[from] serde_json::Error),
}

type Result<T> = std::result::Result<T, RolloutError>;

/// A buffered writer for JSONL event logs.
pub struct TraceWriter {
    writer: BufWriter<File>,
}

impl TraceWriter {
    /// Create a new `TraceWriter`, making the directory and opening `events.jsonl`.
    pub fn new(dir: PathBuf) -> Result<Self> {
        fs::create_dir_all(&dir)?;
        let path = dir.join(EVENTS_FILE);
        let file = fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(path)?;
        Ok(Self {
            writer: BufWriter::new(file),
        })
    }

    /// Serialize `event` to JSON, write it with a trailing newline, and flush.
    pub fn append(&mut self, event: &serde_json::Value) -> Result<()> {
        let line = serde_json::to_string(event)?;
        self.writer.write_all(line.as_bytes())?;
        self.writer.write_all(b"\n")?;
        self.flush()?;
        Ok(())
    }

    /// Flush the underlying buffer to disk.
    pub fn flush(&mut self) -> Result<()> {
        self.writer.flush()?;
        Ok(())
    }
}

impl Drop for TraceWriter {
    fn drop(&mut self) {
        let _ = self.writer.flush();
    }
}

/// A single rollout event.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum RolloutEntry {
    #[serde(rename = "turn_start")]
    TurnStart {
        turn: usize,
        timestamp: DateTime<Utc>,
    },
    #[serde(rename = "turn_end")]
    TurnEnd {
        turn: usize,
        timestamp: DateTime<Utc>,
    },
    #[serde(rename = "message")]
    Message {
        role: String,
        content: String,
        timestamp: DateTime<Utc>,
    },
    #[serde(rename = "tool_call")]
    ToolCall {
        id: String,
        name: String,
        arguments: String,
        timestamp: DateTime<Utc>,
    },
    #[serde(rename = "tool_result")]
    ToolResult {
        id: String,
        content: String,
        is_error: bool,
        timestamp: DateTime<Utc>,
    },
    #[serde(rename = "error")]
    Error {
        message: String,
        timestamp: DateTime<Utc>,
    },
}

impl RolloutEntry {
    /// The timestamp associated with this entry.
    pub fn timestamp(&self) -> DateTime<Utc> {
        match self {
            RolloutEntry::TurnStart { timestamp, .. }
            | RolloutEntry::TurnEnd { timestamp, .. }
            | RolloutEntry::Message { timestamp, .. }
            | RolloutEntry::ToolCall { timestamp, .. }
            | RolloutEntry::ToolResult { timestamp, .. }
            | RolloutEntry::Error { timestamp, .. } => *timestamp,
        }
    }

    /// Returns a mutable reference to the content field, if present.
    fn content_mut(&mut self) -> Option<&mut String> {
        match self {
            RolloutEntry::Message { content, .. } => Some(content),
            RolloutEntry::ToolCall { arguments, .. } => Some(arguments),
            RolloutEntry::ToolResult { content, .. } => Some(content),
            _ => None,
        }
    }
}

/// Manages rollout persistence for a single session.
pub struct RolloutManager {
    writer: TraceWriter,
    dir: PathBuf,
    closed: bool,
}

impl RolloutManager {
    /// Create a new manager rooted at `session_dir`.
    pub fn new(session_dir: PathBuf) -> Result<Self> {
        let writer = TraceWriter::new(session_dir.join("rollout"))?;
        Ok(Self {
            writer,
            dir: session_dir,
            closed: false,
        })
    }

    /// The directory holding this manager's rollout data.
    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// Serialize `entry`, separating large payloads, and append it to the log.
    pub fn record(&mut self, entry: &RolloutEntry) -> Result<()> {
        let mut to_write = entry.clone();
        if let Some(content) = to_write.content_mut() {
            if content.len() > PAYLOAD_THRESHOLD {
                let rollout_dir = self.dir.join("rollout");
                let path = write_payload(&rollout_dir, content)?;
                *content = path;
            }
        }
        let value = serde_json::to_value(&to_write)?;
        self.writer.append(&value)
    }

    /// Load all entries previously written to `dir/rollout/events.jsonl`.
    pub fn load(dir: &Path) -> Result<Vec<RolloutEntry>> {
        let path = dir.join("rollout").join(EVENTS_FILE);
        // Reject oversized rollout files before reading into memory.
        if let Ok(meta) = fs::metadata(&path) {
            if meta.len() > MAX_ROLLOUT_FILE_BYTES {
                return Err(RolloutError::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "rollout file too large: {} bytes (max {MAX_ROLLOUT_FILE_BYTES})",
                        meta.len()
                    ),
                )));
            }
        }
        let contents = fs::read_to_string(path)?;
        let mut entries = Vec::new();
        for line in contents.lines() {
            if line.trim().is_empty() {
                continue;
            }
            let entry: RolloutEntry = serde_json::from_str(line)?;
            entries.push(entry);
        }
        Ok(entries)
    }

    /// Flush pending writes and mark the rollout as complete.
    pub fn close(&mut self) -> Result<()> {
        if !self.closed {
            self.writer.flush()?;
            self.closed = true;
        }
        Ok(())
    }
}

/// Write `content` to `dir/payloads/{uuid}.txt` and return the relative path string.
pub fn write_payload(dir: &Path, content: &str) -> Result<String> {
    let payloads_dir = dir.join(PAYLOADS_DIR);
    fs::create_dir_all(&payloads_dir)?;
    let id = uuid::Uuid::new_v4();
    let file_name = format!("{id}.txt");
    let path = payloads_dir.join(&file_name);
    fs::write(&path, content)?;
    Ok(format!("{PAYLOADS_DIR}/{file_name}"))
}

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

    fn temp_dir() -> tempfile::TempDir {
        tempfile::tempdir().expect("create temp dir")
    }

    #[test]
    fn write_and_read_entries() {
        let tmp = temp_dir();
        let mut manager = RolloutManager::new(tmp.path().to_path_buf()).expect("new manager");
        let ts = Utc::now();
        manager
            .record(&RolloutEntry::TurnStart {
                turn: 1,
                timestamp: ts,
            })
            .expect("record turn start");
        manager
            .record(&RolloutEntry::Message {
                role: "user".into(),
                content: "hello".into(),
                timestamp: ts,
            })
            .expect("record message");
        manager.close().expect("close");

        let loaded = RolloutManager::load(tmp.path()).expect("load");
        assert_eq!(loaded.len(), 2);
        assert!(matches!(
            &loaded[0],
            RolloutEntry::TurnStart { turn, .. } if *turn == 1
        ));
        assert!(matches!(
            &loaded[1],
            RolloutEntry::Message { role, content, .. }
                if role == "user" && content == "hello"
        ));
    }

    #[test]
    fn payload_separation_for_large_content() {
        let tmp = temp_dir();
        let mut manager = RolloutManager::new(tmp.path().to_path_buf()).expect("new manager");
        let ts = Utc::now();
        let big = "x".repeat(PAYLOAD_THRESHOLD + 1);
        manager
            .record(&RolloutEntry::Message {
                role: "assistant".into(),
                content: big.clone(),
                timestamp: ts,
            })
            .expect("record large message");
        manager.close().expect("close");

        let loaded = RolloutManager::load(tmp.path()).expect("load");
        assert_eq!(loaded.len(), 1);
        if let RolloutEntry::Message { content, .. } = &loaded[0] {
            assert!(content.starts_with("payloads/"));
            assert!(content.ends_with(".txt"));
            let payload_path = tmp.path().join("rollout").join(content);
            let read_back = fs::read_to_string(&payload_path).expect("read payload");
            assert_eq!(read_back, big);
        } else {
            panic!("expected message entry");
        }
    }

    #[test]
    fn small_content_stays_inline() {
        let tmp = temp_dir();
        let mut manager = RolloutManager::new(tmp.path().to_path_buf()).expect("new manager");
        let ts = Utc::now();
        manager
            .record(&RolloutEntry::Message {
                role: "user".into(),
                content: "small".into(),
                timestamp: ts,
            })
            .expect("record small message");
        manager.close().expect("close");

        let loaded = RolloutManager::load(tmp.path()).expect("load");
        if let RolloutEntry::Message { content, .. } = &loaded[0] {
            assert_eq!(content, "small");
        } else {
            panic!("expected message entry");
        }
    }

    #[test]
    fn flush_on_drop() {
        let tmp = temp_dir();
        let ts = Utc::now();
        {
            let mut manager = RolloutManager::new(tmp.path().to_path_buf()).expect("new manager");
            manager
                .record(&RolloutEntry::TurnStart {
                    turn: 1,
                    timestamp: ts,
                })
                .expect("record");
        }

        let loaded = RolloutManager::load(tmp.path()).expect("load");
        assert_eq!(loaded.len(), 1);
    }

    #[test]
    fn multiple_entry_types_roundtrip() {
        let tmp = temp_dir();
        let ts = Utc::now();
        let entries = vec![
            RolloutEntry::TurnStart {
                turn: 1,
                timestamp: ts,
            },
            RolloutEntry::Message {
                role: "user".into(),
                content: "run tests".into(),
                timestamp: ts,
            },
            RolloutEntry::ToolCall {
                id: "call_1".into(),
                name: "shell".into(),
                arguments: "{}".into(),
                timestamp: ts,
            },
            RolloutEntry::ToolResult {
                id: "call_1".into(),
                content: "ok".into(),
                is_error: false,
                timestamp: ts,
            },
            RolloutEntry::TurnEnd {
                turn: 1,
                timestamp: ts,
            },
            RolloutEntry::Error {
                message: "boom".into(),
                timestamp: ts,
            },
        ];

        let mut manager = RolloutManager::new(tmp.path().to_path_buf()).expect("new manager");
        for entry in &entries {
            manager.record(entry).expect("record");
        }
        manager.close().expect("close");

        let loaded = RolloutManager::load(tmp.path()).expect("load");
        assert_eq!(loaded.len(), entries.len());
        for (i, expected) in entries.iter().enumerate() {
            assert_eq!(
                serde_json::to_string(expected).unwrap(),
                serde_json::to_string(&loaded[i]).unwrap(),
                "entry {i} mismatch"
            );
        }
    }

    #[test]
    fn type_tag_uses_snake_case() {
        let ts = Utc::now();
        let entry = RolloutEntry::TurnStart {
            turn: 1,
            timestamp: ts,
        };
        let value = serde_json::to_value(&entry).unwrap();
        assert_eq!(value["type"], "turn_start");

        let entry = RolloutEntry::TurnEnd {
            turn: 1,
            timestamp: ts,
        };
        let value = serde_json::to_value(&entry).unwrap();
        assert_eq!(value["type"], "turn_end");

        let entry = RolloutEntry::ToolCall {
            id: "1".into(),
            name: "n".into(),
            arguments: "{}".into(),
            timestamp: ts,
        };
        let value = serde_json::to_value(&entry).unwrap();
        assert_eq!(value["type"], "tool_call");

        let entry = RolloutEntry::ToolResult {
            id: "1".into(),
            content: "c".into(),
            is_error: false,
            timestamp: ts,
        };
        let value = serde_json::to_value(&entry).unwrap();
        assert_eq!(value["type"], "tool_result");
    }

    #[test]
    fn trace_writer_append_flushes() {
        let tmp = temp_dir();
        let mut writer = TraceWriter::new(tmp.path().to_path_buf()).expect("new writer");
        let value = serde_json::json!({"hello": "world"});
        writer.append(&value).expect("append");
        drop(writer);

        let contents = fs::read_to_string(tmp.path().join(EVENTS_FILE)).expect("read");
        assert!(contents.contains("hello"));
        assert!(contents.ends_with('\n'));
    }

    #[test]
    fn write_payload_returns_relative_path() {
        let tmp = temp_dir();
        let path = write_payload(tmp.path(), "payload data").expect("write payload");
        assert!(path.starts_with("payloads/"));
        assert!(path.ends_with(".txt"));
        let full = tmp.path().join(&path);
        assert_eq!(fs::read_to_string(full).unwrap(), "payload data");
    }
}