aboutsummaryrefslogtreecommitdiffstats
path: root/src/session.rs
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/session.rs182
1 files changed, 175 insertions, 7 deletions
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 @@
1use std::fs::{File, OpenOptions};
1use std::hash::{Hash, Hasher}; 2use std::hash::{Hash, Hasher};
2use std::io::Read; 3use std::io::{BufRead, BufReader, Read, Write};
4use std::path::PathBuf;
3use std::time::{SystemTime, UNIX_EPOCH}; 5use std::time::{SystemTime, UNIX_EPOCH};
4 6
7use serde_json::{json, Map, Value};
8
5/// A session id is opaque to the provider: it only has to be stable for the life 9/// A session id is opaque to the provider: it only has to be stable for the life
6/// of one conversation. 16 random-ish bytes as lowercase hex is plenty and keeps 10/// of one conversation. 16 random-ish bytes as lowercase hex is plenty and keeps
7/// it usable as a file name. 11/// it usable as a file name.
8pub fn new_id() -> String { 12pub fn new_id() -> String {
9 let mut bytes = random_bytes(); 13 let mut bytes = random_bytes();
10 // Put the creation time in the first bytes so ids sort roughly by age. 14 // Creation time first, so ids sort roughly by age.
11 let ms = SystemTime::now() 15 let ms = now_ms();
12 .duration_since(UNIX_EPOCH)
13 .map(|d| d.as_millis() as u64)
14 .unwrap_or(0);
15 bytes[..8].copy_from_slice(&ms.to_be_bytes()); 16 bytes[..8].copy_from_slice(&ms.to_be_bytes());
16 17
17 let mut out = String::with_capacity(32); 18 let mut out = String::with_capacity(32);
@@ -21,9 +22,176 @@ pub fn new_id() -> String {
21 out 22 out
22} 23}
23 24
25pub fn now_ms() -> u64 {
26 SystemTime::now()
27 .duration_since(UNIX_EPOCH)
28 .map(|d| d.as_millis() as u64)
29 .unwrap_or(0)
30}
31
32pub fn data_root() -> PathBuf {
33 if let Some(dir) = std::env::var_os("AGENT686_DATA") {
34 return PathBuf::from(dir);
35 }
36 let home = std::env::var_os("HOME").unwrap_or_default();
37 PathBuf::from(home).join(".local/share/agent686")
38}
39
40pub fn sessions_dir() -> PathBuf {
41 data_root().join("sessions")
42}
43
44pub struct Session {
45 pub id: String,
46 pub model: String,
47 path: PathBuf,
48 file: File,
49}
50
51impl Session {
52 pub fn create(model: &str, system: &Value) -> Result<Session, String> {
53 let id = new_id();
54 let dir = sessions_dir();
55 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
56 let path = dir.join(format!("{id}.jsonl"));
57 let mut file = OpenOptions::new()
58 .create_new(true)
59 .append(true)
60 .open(&path)
61 .map_err(|e| format!("{}: {e}", path.display()))?;
62
63 let header = json!({
64 "t": "header",
65 "session": id,
66 "model": model,
67 "created": now_ms(),
68 "system": system,
69 });
70 writeln!(file, "{header}").map_err(|e| e.to_string())?;
71 file.flush().map_err(|e| e.to_string())?;
72
73 Ok(Session {
74 id,
75 model: model.to_string(),
76 path,
77 file,
78 })
79 }
80
81 /// Rebuilds the wire history exactly as it was sent, plus the system message
82 /// that was frozen when the session started.
83 pub fn open(id: &str) -> Result<(Session, Value, Vec<Value>), String> {
84 let path = sessions_dir().join(format!("{id}.jsonl"));
85 let file = File::open(&path).map_err(|e| format!("{}: {e}", path.display()))?;
86 let reader = BufReader::new(file.try_clone().map_err(|e| e.to_string())?);
87
88 let mut model = String::new();
89 let mut system = Value::Null;
90 let mut session_id = id.to_string();
91 let mut messages = Vec::new();
92
93 for line in reader.lines() {
94 let line = line.map_err(|e| e.to_string())?;
95 if line.trim().is_empty() {
96 continue;
97 }
98 let value: Value = match serde_json::from_str(&line) {
99 Ok(v) => v,
100 // A torn last line is expected after kill -9; ignore it.
101 Err(_) => continue,
102 };
103 match value.get("t").and_then(|t| t.as_str()) {
104 Some("header") => {
105 model = value
106 .get("model")
107 .and_then(|m| m.as_str())
108 .unwrap_or_default()
109 .to_string();
110 system = value.get("system").cloned().unwrap_or(Value::Null);
111 if let Some(s) = value.get("session").and_then(|s| s.as_str()) {
112 session_id = s.to_string();
113 }
114 }
115 Some("msg") => {
116 let mut message = value.clone();
117 if let Some(object) = message.as_object_mut() {
118 object.remove("t");
119 object.remove("_reasoning");
120 }
121 messages.push(message);
122 }
123 _ => {}
124 }
125 }
126
127 let file = OpenOptions::new()
128 .append(true)
129 .open(&path)
130 .map_err(|e| format!("{}: {e}", path.display()))?;
131
132 Ok((
133 Session {
134 id: session_id,
135 model,
136 path,
137 file,
138 },
139 system,
140 messages,
141 ))
142 }
143
144 /// Append one wire message. `reasoning` is stored beside it for humans and
145 /// stripped on replay: sending it back is wasted tokens at best.
146 pub fn append(&mut self, message: &Value, reasoning: Option<&str>) -> Result<(), String> {
147 let mut line = match message.as_object() {
148 Some(object) => object.clone(),
149 None => Map::new(),
150 };
151 line.insert("t".into(), json!("msg"));
152 if let Some(reasoning) = reasoning {
153 if !reasoning.is_empty() {
154 line.insert("_reasoning".into(), json!(reasoning));
155 }
156 }
157 writeln!(self.file, "{}", Value::Object(line)).map_err(|e| e.to_string())?;
158 self.file.flush().map_err(|e| e.to_string())
159 }
160
161 pub fn path(&self) -> &PathBuf {
162 &self.path
163 }
164}
165
166/// Most recently written session, for --continue.
167pub fn latest() -> Result<Option<String>, String> {
168 let dir = sessions_dir();
169 let entries = match std::fs::read_dir(&dir) {
170 Ok(entries) => entries,
171 Err(_) => return Ok(None),
172 };
173 let mut newest: Option<(SystemTime, String)> = None;
174 for entry in entries.flatten() {
175 let path = entry.path();
176 if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
177 continue;
178 }
179 let modified = entry
180 .metadata()
181 .and_then(|m| m.modified())
182 .unwrap_or(UNIX_EPOCH);
183 if newest.as_ref().is_none_or(|(t, _)| modified > *t) {
184 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
185 newest = Some((modified, stem.to_string()));
186 }
187 }
188 }
189 Ok(newest.map(|(_, id)| id))
190}
191
24fn random_bytes() -> [u8; 16] { 192fn random_bytes() -> [u8; 16] {
25 let mut bytes = [0u8; 16]; 193 let mut bytes = [0u8; 16];
26 if let Ok(mut f) = std::fs::File::open("/dev/urandom") { 194 if let Ok(mut f) = File::open("/dev/urandom") {
27 if f.read_exact(&mut bytes).is_ok() { 195 if f.read_exact(&mut bytes).is_ok() {
28 return bytes; 196 return bytes;
29 } 197 }