use std::fs::{File, OpenOptions}; use std::hash::{Hash, Hasher}; use std::io::{BufRead, BufReader, Read, Write}; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; use serde_json::{json, Map, Value}; /// A session id is opaque to the provider: it only has to be stable for the life /// of one conversation. 16 random-ish bytes as lowercase hex is plenty and keeps /// it usable as a file name. pub fn new_id() -> String { let mut bytes = random_bytes(); // Creation time first, so ids sort roughly by age. let ms = now_ms(); bytes[..8].copy_from_slice(&ms.to_be_bytes()); let mut out = String::with_capacity(32); for b in bytes { out.push_str(&format!("{b:02x}")); } out } pub fn now_ms() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_millis() as u64) .unwrap_or(0) } pub fn data_root() -> PathBuf { if let Some(dir) = std::env::var_os("AGENT686_DATA") { return PathBuf::from(dir); } let home = std::env::var_os("HOME").unwrap_or_default(); PathBuf::from(home).join(".local/share/agent686") } pub fn sessions_dir() -> PathBuf { data_root().join("sessions") } pub struct Session { pub id: String, pub model: String, path: PathBuf, file: File, } impl Session { pub fn create(model: &str, system: &Value) -> Result { let id = new_id(); let dir = sessions_dir(); std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; let path = dir.join(format!("{id}.jsonl")); let mut file = OpenOptions::new() .create_new(true) .append(true) .open(&path) .map_err(|e| format!("{}: {e}", path.display()))?; let header = json!({ "t": "header", "session": id, "model": model, "created": now_ms(), "system": system, }); writeln!(file, "{header}").map_err(|e| e.to_string())?; file.flush().map_err(|e| e.to_string())?; Ok(Session { id, model: model.to_string(), path, file, }) } /// Rebuilds the wire history exactly as it was sent, plus the system message /// that was frozen when the session started. pub fn open(id: &str) -> Result<(Session, Value, Vec), String> { let path = sessions_dir().join(format!("{id}.jsonl")); let file = File::open(&path).map_err(|e| format!("{}: {e}", path.display()))?; let reader = BufReader::new(file.try_clone().map_err(|e| e.to_string())?); let mut model = String::new(); let mut system = Value::Null; let mut session_id = id.to_string(); let mut messages = Vec::new(); for line in reader.lines() { let line = line.map_err(|e| e.to_string())?; if line.trim().is_empty() { continue; } let value: Value = match serde_json::from_str(&line) { Ok(v) => v, // A torn last line is expected after kill -9; ignore it. Err(_) => continue, }; match value.get("t").and_then(|t| t.as_str()) { Some("header") => { model = value .get("model") .and_then(|m| m.as_str()) .unwrap_or_default() .to_string(); system = value.get("system").cloned().unwrap_or(Value::Null); if let Some(s) = value.get("session").and_then(|s| s.as_str()) { session_id = s.to_string(); } } Some("msg") => { let mut message = value.clone(); if let Some(object) = message.as_object_mut() { object.remove("t"); object.remove("_reasoning"); } messages.push(message); } _ => {} } } let file = OpenOptions::new() .append(true) .open(&path) .map_err(|e| format!("{}: {e}", path.display()))?; Ok(( Session { id: session_id, model, path, file, }, system, messages, )) } /// Append one wire message. `reasoning` is stored beside it for humans and /// stripped on replay: sending it back is wasted tokens at best. pub fn append(&mut self, message: &Value, reasoning: Option<&str>) -> Result<(), String> { let mut line = match message.as_object() { Some(object) => object.clone(), None => Map::new(), }; line.insert("t".into(), json!("msg")); if let Some(reasoning) = reasoning { if !reasoning.is_empty() { line.insert("_reasoning".into(), json!(reasoning)); } } writeln!(self.file, "{}", Value::Object(line)).map_err(|e| e.to_string())?; self.file.flush().map_err(|e| e.to_string()) } pub fn path(&self) -> &PathBuf { &self.path } } /// Most recently written session, for --continue. pub fn latest() -> Result, String> { let dir = sessions_dir(); let entries = match std::fs::read_dir(&dir) { Ok(entries) => entries, Err(_) => return Ok(None), }; let mut newest: Option<(SystemTime, String)> = None; for entry in entries.flatten() { let path = entry.path(); if path.extension().and_then(|e| e.to_str()) != Some("jsonl") { continue; } let modified = entry .metadata() .and_then(|m| m.modified()) .unwrap_or(UNIX_EPOCH); if newest.as_ref().is_none_or(|(t, _)| modified > *t) { if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { newest = Some((modified, stem.to_string())); } } } Ok(newest.map(|(_, id)| id)) } fn random_bytes() -> [u8; 16] { let mut bytes = [0u8; 16]; if let Ok(mut f) = File::open("/dev/urandom") { if f.read_exact(&mut bytes).is_ok() { return bytes; } } // Fallback: not cryptographic, but an id only has to not collide. let mut h = std::collections::hash_map::DefaultHasher::new(); SystemTime::now().hash(&mut h); std::process::id().hash(&mut h); let v = h.finish(); bytes[..8].copy_from_slice(&v.to_be_bytes()); bytes[8..].copy_from_slice(&(v ^ 0x9e37_79b9_7f4a_7c15).to_be_bytes()); bytes }