summaryrefslogtreecommitdiffstats
path: root/src/session.rs
blob: d017edaa94d49ce25d898cd6ba97efc2c85ff6a7 (plain) (blame)
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
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<Session, String> {
        Self::create_as(new_id(), model, system)
    }

    /// Creates a session with a caller-chosen id, for `--session <id>` on a
    /// conversation that does not exist yet.
    pub fn create_as(id: String, model: &str, system: &Value) -> Result<Session, String> {
        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<Value>), 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 cwd = String::new();
        let mut version = String::new();
        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();
                    }
                    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 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<Vec<SessionInfo>, 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<Option<String>, 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
}