use std::fs::{File, OpenOptions}; use std::hash::{Hash, Hasher}; use std::io::{BufRead, BufReader, Read, Write}; use std::os::unix::fs::PermissionsExt; use std::os::unix::io::AsRawFd; use std::path::Path; 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") } /// Sessions contain the whole conversation, so they are for this user only. fn restrict(path: &Path, mode: u32) { let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)); } /// Two processes appending to one transcript interleave messages and corrupt it /// permanently, because history is never rewritten. Refuse the second one. fn lock_exclusive(file: &File, id: &str) -> Result<(), String> { let locked = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; if locked != 0 { return Err(format!( "session {id} is already open in another process" )); } Ok(()) } pub struct Session { pub id: String, pub model: String, /// Directory the session was started in; the system prompt is frozen with it. pub cwd: String, /// Harness version that created the session, for prefix-change warnings. pub version: String, path: PathBuf, file: File, } pub struct SessionInfo { pub id: String, pub model: String, pub messages: usize, pub modified: SystemTime, pub path: PathBuf, } impl Session { pub fn create(model: &str, system: &Value) -> Result { Self::create_as(new_id(), model, system) } /// Creates a session with a caller-chosen id, for `--session ` on a /// conversation that does not exist yet. pub fn create_as(id: String, model: &str, system: &Value) -> Result { let dir = sessions_dir(); std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; restrict(&data_root(), 0o700); restrict(&dir, 0o700); 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()))?; restrict(&path, 0o600); lock_exclusive(&file, &id)?; let cwd = std::env::current_dir() .map(|path| path.display().to_string()) .unwrap_or_default(); let header = json!({ "t": "header", "session": id, "model": model, "cwd": cwd, "version": env!("CARGO_PKG_VERSION"), "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(), cwd, version: env!("CARGO_PKG_VERSION").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 raw = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?; let _ = File::open(&path); let mut model = String::new(); let mut system = Value::Null; let mut session_id = id.to_string(); let mut cwd = String::new(); let mut version = String::new(); let mut messages = Vec::new(); for line in raw.split(|&byte| byte == b'\n') { if line.is_empty() { continue; } // Lossy decoding: a torn write can split a multi-byte character, and // one bad byte must not make the whole transcript unopenable. let text = String::from_utf8_lossy(line); let value: Value = match serde_json::from_str(&text) { Ok(v) => v, 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(); } if let Some(c) = value.get("cwd").and_then(|c| c.as_str()) { cwd = c.to_string(); } if let Some(v) = value.get("version").and_then(|v| v.as_str()) { version = v.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()))?; // Older builds created these 0644. restrict(&path, 0o600); lock_exclusive(&file, &session_id)?; Ok(( Session { id: session_id, model, cwd, version, 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 } /// Records a model switch so `--list` shows what the last turn used. Appending /// is legal; the header itself is never rewritten. pub fn record_model(&mut self, model: &str) -> Result<(), String> { let line = json!({ "t": "model", "model": model, "at": now_ms() }); writeln!(self.file, "{line}").map_err(|e| e.to_string())?; self.file.flush().map_err(|e| e.to_string()) } } pub struct LastReply { pub content: String, pub reasoning: String, } /// The last thing the agent said, for the resume banner. Prefers a real answer; /// falls back to reasoning when the last block had no content. pub fn last_reply(id: &str) -> Option { let raw = std::fs::read(sessions_dir().join(format!("{id}.jsonl"))).ok()?; let mut with_content: Option = None; let mut with_reasoning: Option = None; for line in raw.split(|&byte| byte == b'\n') { if line.is_empty() { continue; } let text = String::from_utf8_lossy(line); let Ok(value) = serde_json::from_str::(&text) else { continue; }; if value.get("role").and_then(|role| role.as_str()) != Some("assistant") { continue; } let content = value .get("content") .and_then(|c| c.as_str()) .unwrap_or("") .to_string(); let reasoning = value .get("_reasoning") .and_then(|r| r.as_str()) .unwrap_or("") .to_string(); let reply = LastReply { content, reasoning, }; if !reply.content.trim().is_empty() { with_content = Some(LastReply { content: reply.content.clone(), reasoning: reply.reasoning.clone(), }); } if !reply.reasoning.trim().is_empty() { with_reasoning = Some(reply); } } with_content.or(with_reasoning) } pub fn exists(id: &str) -> bool { sessions_dir().join(format!("{id}.jsonl")).is_file() } /// Every session, most recently used first. Reads each file once; fine for the /// handful of conversations a person accumulates. pub fn list() -> Result, String> { let dir = sessions_dir(); let entries = match std::fs::read_dir(&dir) { Ok(entries) => entries, Err(_) => return Ok(Vec::new()), }; let mut sessions = Vec::new(); for entry in entries.flatten() { let path = entry.path(); if path.extension().and_then(|e| e.to_str()) != Some("jsonl") { continue; } let id = match path.file_stem().and_then(|s| s.to_str()) { Some(id) => id.to_string(), None => continue, }; let modified = entry .metadata() .and_then(|m| m.modified()) .unwrap_or(UNIX_EPOCH); let (model, messages) = scan(&path); sessions.push(SessionInfo { id, model, messages, modified, path, }); } sessions.sort_by(|a, b| b.modified.cmp(&a.modified)); Ok(sessions) } fn scan(path: &PathBuf) -> (String, usize) { let mut model = String::from("?"); let mut messages = 0usize; if let Ok(file) = File::open(path) { for line in BufReader::new(file).lines().map_while(Result::ok) { let value: Value = match serde_json::from_str(&line) { Ok(value) => value, Err(_) => continue, }; match value.get("t").and_then(|t| t.as_str()) { Some("header") => { if let Some(name) = value.get("model").and_then(|m| m.as_str()) { model = name.to_string(); } } Some("msg") => messages += 1, Some("model") => { if let Some(name) = value.get("model").and_then(|m| m.as_str()) { model = name.to_string(); } } _ => {} } } } (model, messages) } /// 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 }