repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

smith-core/src/session.rs

Raw
File outline
use serde::{Deserialize, Serialize};
use smith::{id::*, message::Message};

/// Deterministic JSON: recursively sort object keys so equivalent values
/// encode to identical CBOR regardless of insertion order.
pub fn canonical_json(value: &serde_json::Value) -> serde_json::Value {
    match value {
        serde_json::Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort();
            let mut out = serde_json::Map::new();
            for key in keys {
                out.insert(key.clone(), canonical_json(&map[key]));
            }
            serde_json::Value::Object(out)
        }
        serde_json::Value::Array(items) => {
            serde_json::Value::Array(items.iter().map(canonical_json).collect())
        }
        other => other.clone(),
    }
}

/// A session entry (message, tool call/result, or metadata).
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Entry {
    /// Entry ID.
    pub id: EntryId,
    /// Parent entry ID (None for root).
    pub parent: Option<EntryId>,
    /// Timestamp (Unix ms).
    pub timestamp_ms: i64,
    /// The content of the entry.
    pub content: EntryContent,
}

#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(tag = "kind", content = "data")]
pub enum EntryContent {
    /// Chat message.
    Message(Message),
    /// Tool call (recorded for replay).
    ToolCall {
        name: String,
        input: serde_json::Value,
        call_id: smith::id::ToolCallId,
    },
    /// Tool result.
    ToolResult {
        ok: bool,
        output: String,
        call_id: smith::id::ToolCallId,
    },
    /// Session metadata event (compaction, branch selection).
    Meta {
        kind: String,
        detail: serde_json::Value,
    },
}

impl Entry {
    pub fn new(parent: Option<EntryId>, content: EntryContent) -> Self {
        Self {
            id: EntryId::new(),
            parent,
            timestamp_ms: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis() as i64)
                .unwrap_or(0),
            content,
        }
    }

    pub fn message(msg: Message, parent: Option<EntryId>) -> Self {
        Self::new(parent, EntryContent::Message(msg))
    }
}

/// Selected branch in a session.
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Branch {
    /// Branch ID.
    pub branch_id: BranchId,
    /// Entries ordered by time.
    pub entries: Vec<Entry>,
    /// Index of selected leaf.
    pub selected_idx: usize,
}

impl Branch {
    pub fn new() -> Self {
        Self {
            branch_id: BranchId::new(),
            entries: Vec::new(),
            selected_idx: 0,
        }
    }

    pub fn append(&mut self, entry: Entry) -> usize {
        self.entries.push(entry);
        self.selected_idx = self.entries.len().saturating_sub(1);
        self.selected_idx
    }

    pub fn selected_entry(&self) -> Option<&Entry> {
        self.entries.get(self.selected_idx)
    }
}

/// A session is a persistent, branching message/tool history.
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Session {
    /// Session identifier.
    pub id: SessionId,
    /// All branches (default branch is index 0).
    pub branches: Vec<Branch>,
    /// Index of active branch.
    pub active_branch_idx: usize,
    /// Compaction boundary entry (if any).
    pub compaction_boundary: Option<EntryId>,
}

impl Session {
    pub fn new() -> Self {
        Self {
            id: SessionId::new(),
            branches: vec![Branch::new()],
            active_branch_idx: 0,
            compaction_boundary: None,
        }
    }

    pub fn active_branch(&self) -> &Branch {
        &self.branches[self.active_branch_idx]
    }

    pub fn active_branch_mut(&mut self) -> &mut Branch {
        &mut self.branches[self.active_branch_idx]
    }

    pub fn append_to_active(&mut self, entry: Entry) {
        let branch = self.active_branch_mut();
        branch.append(entry);
    }

    pub fn selected_id(&self) -> Option<EntryId> {
        self.active_branch().selected_entry().map(|e| e.id)
    }

    /// Restore in-memory state from decoded frames.
    /// Known entries keep their stored order, IDs, and parent links;
    /// the last entry becomes the selected leaf. Unknown frames are
    /// skipped here. `compaction` meta entries set the compaction boundary.
    pub fn from_frames(frames: &[crate::frame::Frame]) -> Self {
        let mut session = Self::new();
        let mut restored: Vec<Entry> = Vec::new();
        for frame in frames {
            if let crate::frame::Frame::Known { entry } = frame {
                if let EntryContent::Meta { kind, .. } = &entry.content {
                    if kind == "compaction" {
                        session.compaction_boundary = Some(entry.id);
                    }
                }
                restored.push(entry.clone());
            }
        }
        let branch = session.active_branch_mut();
        branch.entries = restored;
        branch.selected_idx = branch.entries.len().saturating_sub(1);
        session
    }
}