1use std::fs::OpenOptions;
2use std::io::Write;
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicU64, Ordering};
5
6use blyte_provider::Message;
7use serde::Serialize;
8
9static TMP_SEQ: AtomicU64 = AtomicU64::new(0);
10
11#[derive(Debug, Clone, PartialEq)]
12pub struct LoadedConversation {
13 pub model: Option<String>,
14 pub goal: Option<String>,
15 pub messages: Vec<Message>,
16}
17
18pub struct ConversationStore {
19 path: PathBuf,
20 last_model: Option<String>,
21 last_goal: Option<String>,
22 saved_messages: usize,
23 file_initialized: bool,
24}
25
26#[derive(Serialize)]
27struct VersionLine {
28 version: u64,
29}
30
31#[derive(Serialize)]
32struct ModelLine<'a> {
33 model: &'a str,
34}
35
36#[derive(Serialize)]
37struct GoalLine<'a> {
38 goal: Option<&'a str>,
39}
40
41#[derive(Serialize)]
42struct MessageLine<'a> {
43 message: &'a Message,
44}
45
46pub fn conversation_path_for_id(surface_id: &str) -> Result<PathBuf, String> {
48 blyte_agent::sandbox::validate_surface_id(surface_id)?;
49 let dir = blyte_agent::sandbox::surface_token_dir().ok_or_else(|| {
50 "cannot determine surface token directory: neither XDG_STATE_HOME nor HOME is set"
51 .to_string()
52 })?;
53 Ok(dir.join(format!("{surface_id}.conversation.jsonl")))
54}
55
56fn format_read_error(path: &Path, line_no: usize, reason: &str) -> String {
57 format!(
58 "cannot read the saved conversation {} (line {line_no}): {reason}; delete that file to resume without the model's memory",
59 path.display()
60 )
61}
62
63fn push_json_line<T: Serialize>(buf: &mut Vec<u8>, value: &T) -> Result<(), String> {
64 serde_json::to_writer(&mut *buf, value)
65 .map_err(|e| format!("failed to serialize conversation line: {e}"))?;
66 buf.push(b'\n');
67 Ok(())
68}
69
70fn encode_full_file(
71 model: Option<&str>,
72 goal: Option<&str>,
73 messages: &[Message],
74) -> Result<Vec<u8>, String> {
75 let mut buf = Vec::new();
76 push_json_line(&mut buf, &VersionLine { version: 1 })?;
77 if let Some(m) = model {
78 push_json_line(&mut buf, &ModelLine { model: m })?;
79 }
80 if goal.is_some() {
81 push_json_line(&mut buf, &GoalLine { goal })?;
82 }
83 for message in messages {
84 push_json_line(&mut buf, &MessageLine { message })?;
85 }
86 Ok(buf)
87}
88
89fn ensure_parent_dir(path: &Path) -> Result<(), String> {
90 if let Some(parent) = path.parent() {
91 if !parent.as_os_str().is_empty() {
92 std::fs::create_dir_all(parent)
93 .map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
94 }
95 }
96 Ok(())
97}
98
99#[cfg(unix)]
100fn set_file_mode_0600(path: &Path) -> Result<(), String> {
101 use std::os::unix::fs::PermissionsExt;
102 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
103 .map_err(|e| format!("cannot set permissions on {}: {e}", path.display()))
104}
105
106#[cfg(not(unix))]
107fn set_file_mode_0600(_path: &Path) -> Result<(), String> {
108 Ok(())
109}
110
111fn open_append_0600(path: &Path) -> Result<std::fs::File, String> {
112 let mut opts = OpenOptions::new();
113 opts.create(true).append(true);
114 #[cfg(unix)]
115 {
116 use std::os::unix::fs::OpenOptionsExt;
117 opts.mode(0o600);
118 }
119 opts.open(path)
120 .map_err(|e| format!("cannot open {}: {e}", path.display()))
121}
122
123fn rewrite_atomic(
124 path: &Path,
125 model: Option<&str>,
126 goal: Option<&str>,
127 messages: &[Message],
128) -> Result<(), String> {
129 let parent = path
130 .parent()
131 .filter(|p| !p.as_os_str().is_empty())
132 .ok_or_else(|| {
133 format!(
134 "cannot rewrite conversation file {}: path has no parent directory",
135 path.display()
136 )
137 })?;
138 let file_name = path.file_name().ok_or_else(|| {
139 format!(
140 "cannot rewrite conversation file {}: path has no file name",
141 path.display()
142 )
143 })?;
144 let base_name = file_name.to_str().ok_or_else(|| {
145 format!(
146 "cannot rewrite conversation file {}: file name is not valid UTF-8",
147 path.display()
148 )
149 })?;
150 ensure_parent_dir(path)?;
151 let buf = encode_full_file(model, goal, messages)?;
152 let pid = std::process::id();
153 let mut attempt = 0u64;
154 let (tmp_path, mut file) = loop {
155 let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed);
156 let candidate = parent.join(format!(".{base_name}.tmp.{pid}.{seq}.{attempt}"));
157 let mut opts = OpenOptions::new();
158 opts.write(true).create_new(true);
159 #[cfg(unix)]
160 {
161 use std::os::unix::fs::OpenOptionsExt;
162 opts.mode(0o600);
163 }
164 match opts.open(&candidate) {
165 Ok(f) => break (candidate, f),
166 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
167 attempt += 1;
168 }
169 Err(e) => {
170 return Err(format!("cannot create {}: {e}", candidate.display()));
171 }
172 }
173 };
174 let write_res = file
175 .write_all(&buf)
176 .and_then(|()| file.flush())
177 .and_then(|()| file.sync_all());
178 drop(file);
179 if let Err(e) = write_res {
180 let _ = std::fs::remove_file(&tmp_path);
181 return Err(format!("cannot write {}: {e}", tmp_path.display()));
182 }
183 if let Err(e) = set_file_mode_0600(&tmp_path) {
184 let _ = std::fs::remove_file(&tmp_path);
185 return Err(e);
186 }
187 if let Err(e) = std::fs::rename(&tmp_path, path) {
188 let _ = std::fs::remove_file(&tmp_path);
189 return Err(format!(
190 "cannot rename {} to {}: {e}",
191 tmp_path.display(),
192 path.display()
193 ));
194 }
195 Ok(())
196}
197
198fn strip_trailing_unmatched_tool_calls(messages: &mut Vec<Message>) -> bool {
199 let mut changed = false;
200 loop {
201 let results_start = messages
202 .iter()
203 .rposition(|m| !matches!(m, Message::ToolResult { .. }))
204 .map(|i| i + 1)
205 .unwrap_or(0);
206 let calls_start = messages[..results_start]
207 .iter()
208 .rposition(|m| !matches!(m, Message::ToolCall { .. }))
209 .map(|i| i + 1)
210 .unwrap_or(0);
211 let num_calls = results_start - calls_start;
212 let num_results = messages.len() - results_start;
213 if num_calls > num_results {
214 messages.drain(calls_start + num_results..results_start);
215 changed = true;
216 } else {
217 break;
218 }
219 }
220 changed
221}
222
223fn parse_version_line(path: &Path, line: &str) -> Result<(), String> {
224 let val: serde_json::Value =
225 serde_json::from_str(line).map_err(|e| format_read_error(path, 1, &e.to_string()))?;
226 let Some(map) = val.as_object() else {
227 return Err(format_read_error(
228 path,
229 1,
230 "first line must be {\"version\":1}",
231 ));
232 };
233 if map.len() != 1 {
234 if let Some(unknown) = map.keys().find(|k| k.as_str() != "version") {
235 return Err(format_read_error(
236 path,
237 1,
238 &format!("unknown key \"{unknown}\""),
239 ));
240 }
241 return Err(format_read_error(
242 path,
243 1,
244 "first line must be {\"version\":1}",
245 ));
246 }
247 match map.get("version") {
248 Some(v) if v.as_u64() == Some(1) => Ok(()),
249 Some(v) => Err(format_read_error(
250 path,
251 1,
252 &format!("unsupported version {v}; expected 1"),
253 )),
254 None => {
255 if let Some(unknown) = map.keys().next() {
256 Err(format_read_error(
257 path,
258 1,
259 &format!("unknown key \"{unknown}\""),
260 ))
261 } else {
262 Err(format_read_error(
263 path,
264 1,
265 "first line must be {\"version\":1}",
266 ))
267 }
268 }
269 }
270}
271
272impl ConversationStore {
273 pub fn path(&self) -> &Path {
274 &self.path
275 }
276
277 pub fn new_for_fresh(path: PathBuf) -> Result<Self, String> {
278 match std::fs::symlink_metadata(&path) {
279 Ok(_) => Err(format!(
280 "conversation file already exists for new surface: {}",
281 path.display()
282 )),
283 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self {
284 path,
285 last_model: None,
286 last_goal: None,
287 saved_messages: 0,
288 file_initialized: false,
289 }),
290 Err(e) => Err(format!("cannot inspect {}: {e}", path.display())),
291 }
292 }
293
294 pub fn load(path: PathBuf) -> Result<(Self, Option<LoadedConversation>), String> {
295 let raw = match std::fs::read(&path) {
296 Ok(bytes) => bytes,
297 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
298 return Ok((
299 Self {
300 path,
301 last_model: None,
302 last_goal: None,
303 saved_messages: 0,
304 file_initialized: false,
305 },
306 None,
307 ));
308 }
309 Err(e) => return Err(format_read_error(&path, 1, &e.to_string())),
310 };
311
312 let (complete_bytes, truncate_to) = if !raw.is_empty() && !raw.ends_with(b"\n") {
313 let cut = raw
314 .iter()
315 .rposition(|&b| b == b'\n')
316 .map(|i| i + 1)
317 .unwrap_or(0);
318 (&raw[..cut], Some(cut as u64))
319 } else {
320 (&raw[..], None)
321 };
322
323 let lines: Vec<&[u8]> = if complete_bytes.is_empty() {
324 Vec::new()
325 } else {
326 let trimmed = complete_bytes.strip_suffix(b"\n").unwrap_or(complete_bytes);
327 trimmed.split(|&b| b == b'\n').collect()
328 };
329
330 let Some(first_raw) = lines.first() else {
331 return Err(format_read_error(
332 &path,
333 1,
334 "first line must be {\"version\":1}",
335 ));
336 };
337 let first_str = std::str::from_utf8(first_raw)
338 .map_err(|e| format_read_error(&path, 1, &e.to_string()))?;
339 parse_version_line(&path, first_str)?;
340
341 let mut model: Option<String> = None;
342 let mut goal: Option<String> = None;
343 let mut messages: Vec<Message> = Vec::new();
344
345 for (idx, raw_line) in lines.iter().enumerate().skip(1) {
346 let line_no = idx + 1;
347 let line_str = std::str::from_utf8(raw_line)
348 .map_err(|e| format_read_error(&path, line_no, &e.to_string()))?;
349 let val: serde_json::Value = serde_json::from_str(line_str)
350 .map_err(|e| format_read_error(&path, line_no, &e.to_string()))?;
351 let serde_json::Value::Object(map) = val else {
352 return Err(format_read_error(&path, line_no, "expected a JSON object"));
353 };
354 if map.len() != 1 {
355 if let Some(unknown) = map
356 .keys()
357 .find(|k| !matches!(k.as_str(), "model" | "goal" | "message"))
358 {
359 return Err(format_read_error(
360 &path,
361 line_no,
362 &format!("unknown key \"{unknown}\""),
363 ));
364 }
365 return Err(format_read_error(
366 &path,
367 line_no,
368 "expected a JSON object with exactly one key",
369 ));
370 }
371 let (key, value) = map.into_iter().next().unwrap();
372 match key.as_str() {
373 "model" => {
374 let parsed: String = serde_json::from_value(value)
375 .map_err(|e| format_read_error(&path, line_no, &e.to_string()))?;
376 model = Some(parsed);
377 }
378 "goal" => {
379 let parsed: Option<String> = serde_json::from_value(value)
380 .map_err(|e| format_read_error(&path, line_no, &e.to_string()))?;
381 goal = parsed;
382 }
383 "message" => {
384 let parsed: Message = serde_json::from_value(value)
385 .map_err(|e| format_read_error(&path, line_no, &e.to_string()))?;
386 messages.push(parsed);
387 }
388 other => {
389 return Err(format_read_error(
390 &path,
391 line_no,
392 &format!("unknown key \"{other}\""),
393 ));
394 }
395 }
396 }
397
398 let trimmed_tool_calls = strip_trailing_unmatched_tool_calls(&mut messages);
399 if trimmed_tool_calls {
400 rewrite_atomic(&path, model.as_deref(), goal.as_deref(), &messages)?;
401 } else if let Some(cut) = truncate_to {
402 let f = OpenOptions::new()
403 .write(true)
404 .open(&path)
405 .map_err(|e| format!("cannot truncate {}: {e}", path.display()))?;
406 f.set_len(cut)
407 .and_then(|()| f.sync_all())
408 .map_err(|e| format!("cannot truncate {}: {e}", path.display()))?;
409 }
410
411 let store = Self {
412 path,
413 last_model: model.clone(),
414 last_goal: goal.clone(),
415 saved_messages: messages.len(),
416 file_initialized: true,
417 };
418 Ok((
419 store,
420 Some(LoadedConversation {
421 model,
422 goal,
423 messages,
424 }),
425 ))
426 }
427
428 pub fn save(
429 &mut self,
430 model: &str,
431 goal: Option<&str>,
432 messages: &[Message],
433 ) -> Result<(), String> {
434 if self.file_initialized && messages.len() < self.saved_messages {
435 rewrite_atomic(&self.path, Some(model), goal, messages)?;
436 self.last_model = Some(model.to_string());
437 self.last_goal = goal.map(str::to_string);
438 self.saved_messages = messages.len();
439 return Ok(());
440 }
441
442 let mut buf = Vec::new();
443 if !self.file_initialized {
444 push_json_line(&mut buf, &VersionLine { version: 1 })?;
445 }
446 if self.last_model.as_deref() != Some(model) {
447 push_json_line(&mut buf, &ModelLine { model })?;
448 }
449 if self.last_goal.as_deref() != goal {
450 push_json_line(&mut buf, &GoalLine { goal })?;
451 }
452 for message in &messages[self.saved_messages..] {
453 push_json_line(&mut buf, &MessageLine { message })?;
454 }
455
456 if buf.is_empty() && self.file_initialized {
457 return Ok(());
458 }
459
460 if !self.file_initialized {
461 ensure_parent_dir(&self.path)?;
462 }
463 let mut file = open_append_0600(&self.path)?;
464 if !self.file_initialized {
465 set_file_mode_0600(&self.path)?;
466 }
467 file.write_all(&buf)
468 .and_then(|()| file.flush())
469 .and_then(|()| file.sync_all())
470 .map_err(|e| format!("cannot write {}: {e}", self.path.display()))?;
471
472 self.file_initialized = true;
473 self.last_model = Some(model.to_string());
474 self.last_goal = goal.map(str::to_string);
475 self.saved_messages = messages.len();
476 Ok(())
477 }
478
479 pub fn rewrite(
480 &mut self,
481 model: Option<&str>,
482 goal: Option<&str>,
483 messages: &[Message],
484 ) -> Result<(), String> {
485 rewrite_atomic(&self.path, model, goal, messages)?;
486 self.file_initialized = true;
487 self.last_model = model.map(str::to_string);
488 self.last_goal = goal.map(str::to_string);
489 self.saved_messages = messages.len();
490 Ok(())
491 }
492}
493
494pub fn digest_for_provider_in_memory(
497 loaded: &mut LoadedConversation,
498 starting_model: &str,
499) -> bool {
500 if loaded.messages.is_empty() {
501 return false;
502 }
503 let Some(ref saved_model) = loaded.model else {
504 return false;
505 };
506 let saved_kind = blyte_provider::detect_provider_kind(Some(saved_model.as_str()));
507 let starting_kind = blyte_provider::detect_provider_kind(Some(starting_model));
508 if saved_kind == starting_kind {
509 return false;
510 }
511 let summary = blyte_agent::context::digest(&loaded.messages, 1, loaded.messages.len());
512 loaded.messages = vec![summary];
513 loaded.model = Some(starting_model.to_string());
514 true
515}
516
517pub fn maybe_digest_for_provider(
520 store: &mut ConversationStore,
521 loaded: &mut LoadedConversation,
522 starting_model: &str,
523) -> Result<bool, String> {
524 if !digest_for_provider_in_memory(loaded, starting_model) {
525 return Ok(false);
526 }
527 store.rewrite(
528 Some(starting_model),
529 loaded.goal.as_deref(),
530 &loaded.messages,
531 )?;
532 Ok(true)
533}