From 343f2a8a6148b8004d6f4d74fb779b4f30c9686a Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 03:11:22 +0100 Subject: M1-M5: sessions, six tools, approvals, prompt, Ctrl-C, target gate - append-only JSONL sessions with --continue/--session; reasoning stored, stripped on replay - read/write/edit/grep/glob + bash with timeout and capped output - diff-preview approval for the first edit of a session, per-call approval for bash - system prompt frozen per session with AGENTS.md snapshot and change warning - SIGINT aborts the turn, second Ctrl-C exits - glibc gate ignores weak symbols; verified in linux/386 debian:12 - acceptance test (calculator in C) passes on both x86-64 and i386 --- src/session.rs | 182 ++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 175 insertions(+), 7 deletions(-) (limited to 'src/session.rs') diff --git a/src/session.rs b/src/session.rs index aef4835..7090dcf 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1,17 +1,18 @@ +use std::fs::{File, OpenOptions}; use std::hash::{Hash, Hasher}; -use std::io::Read; +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(); - // Put the creation time in the first bytes so ids sort roughly by age. - let ms = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_millis() as u64) - .unwrap_or(0); + // 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); @@ -21,9 +22,176 @@ pub fn new_id() -> String { 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) = std::fs::File::open("/dev/urandom") { + if let Ok(mut f) = File::open("/dev/urandom") { if f.read_exact(&mut bytes).is_ok() { return bytes; } -- cgit v1.2.3