use std::collections::BTreeMap;
use yk_core::{Id, Result};
use crate::{Entry, SessionLog, next_id};
impl SessionLog {
pub fn head_id(&self) -> Result<Option<Id>> {
Ok(head_id(&self.all_entries()?))
}
pub fn active_entries(&self) -> Result<Vec<Entry>> {
let entries = self.all_entries()?;
if entries.is_empty() {
return Ok(Vec::new());
}
let by_id: BTreeMap<&Id, &Entry> =
entries.iter().map(|entry| (entry.id(), entry)).collect();
let head = head_id(&entries);
let mut current = head.as_ref();
let mut chain: Vec<&Entry> = Vec::new();
let mut seen: Vec<&Id> = Vec::new();
while let Some(id) = current {
let entry = by_id
.get(id)
.copied()
.ok_or_else(|| yk_core::Error::Malformed(format!("entry `{id}` is missing")))?;
if seen.contains(&id) {
return Err(yk_core::Error::Malformed(format!(
"entry `{id}` is its own ancestor"
)));
}
seen.push(id);
match entry {
Entry::Compaction { .. } => {
chain.push(entry);
break;
}
Entry::Rewind { .. } => {
return Err(yk_core::Error::Malformed(format!(
"entry `{id}` is a rewind and cannot be part of a branch"
)));
}
_ => chain.push(entry),
}
current = entry.parent();
}
chain.reverse();
Ok(chain.into_iter().cloned().collect())
}
pub fn active_messages(&self) -> Result<Vec<yk_core::Message>> {
Ok(self
.active_entries()?
.iter()
.filter_map(entry_to_message)
.collect())
}
pub fn all_entries(&self) -> Result<Vec<Entry>> {
Ok(self.load()?.1)
}
pub fn active_model(&self) -> Result<Option<String>> {
Ok(self.active_entries()?.iter().rev().find_map(|entry| {
if let Entry::Model { model, .. } = entry {
Some(model.clone())
} else {
None
}
}))
}
pub fn fork(&self, destination: &std::path::Path) -> Result<()> {
let (header, entries) = self.load()?;
if let Some(parent) = destination.parent() {
std::fs::create_dir_all(parent).map_err(|source| yk_core::Error::Write {
path: parent.display().to_string(),
source,
})?;
}
let mut rendered = String::new();
if let Some(header) = &header {
let line = serde_json::to_string(header)
.map_err(|error| yk_core::Error::Malformed(error.to_string()))?;
rendered.push_str(&line);
rendered.push('\n');
}
for entry in &entries {
let line = serde_json::to_string(entry)
.map_err(|error| yk_core::Error::Malformed(error.to_string()))?;
rendered.push_str(&line);
rendered.push('\n');
}
std::fs::write(destination, rendered).map_err(|source| yk_core::Error::Write {
path: destination.display().to_string(),
source,
})
}
pub fn rewind(&mut self, to: &Id) -> Result<()> {
let entries = self.all_entries()?;
if !entries.iter().any(|entry| entry.id() == to) {
return Err(yk_core::Error::Malformed(format!(
"cannot rewind to `{to}`; no such entry"
)));
}
let id = next_id(entries.len());
let entry = Entry::Rewind {
id,
parent: None,
to: to.clone(),
};
self.append(&entry)
}
pub fn rewind_by(&mut self, messages: usize) -> Result<Id> {
let entries = self.active_entries()?;
let count = entries.len();
if messages == 0 || messages >= count {
return Err(yk_core::Error::InvalidInput(format!(
"cannot rewind by {messages}; the branch has {count} entries"
)));
}
let target = entries
.get(count.saturating_sub(messages).saturating_sub(1))
.ok_or_else(|| yk_core::Error::Malformed(format!("branch has only {count} entries")))?
.id()
.clone();
self.rewind(&target)?;
Ok(target)
}
pub fn compact(&mut self, summary: &str, parent: Option<&Id>) -> Result<Id> {
let entries = self.all_entries()?;
let id = next_id(entries.len());
let entry = Entry::Compaction {
id: id.clone(),
parent: parent.map(ToOwned::to_owned),
summary: summary.to_owned(),
};
self.append(&entry)?;
Ok(id)
}
}
fn head_id(entries: &[Entry]) -> Option<Id> {
entries.last().map(|last| match last {
Entry::Rewind { to, .. } => to.clone(),
other => other.id().clone(),
})
}
#[must_use]
pub fn entry_to_message(entry: &Entry) -> Option<yk_core::Message> {
match entry {
Entry::Message { message, .. } => Some(message.clone()),
Entry::Assistant { turn, .. } => Some(yk_core::Message::assistant_with_calls(
turn.text.clone(),
turn.tool_calls.clone(),
)),
Entry::Result { result, .. } => Some(yk_core::Message::tool_result(
result.call_id.clone(),
result.output.clone(),
result.is_error,
)),
Entry::Compaction { summary, .. } => Some(summary_message(summary)),
Entry::Model { .. } | Entry::Rewind { .. } => None,
}
}
#[must_use]
pub fn summary_message(summary: &str) -> yk_core::Message {
yk_core::Message::user(format!("Summary of the conversation so far:\n\n{summary}"))
}