aboutsummaryrefslogtreecommitdiffstats
path: root/src/session.rs
blob: 7090dcfbb7b69be5a13e3bb54e81bdc0cb35e03f (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
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<Session, String> {
        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<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 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<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
}