refactor(core): EntryContentRef records tool calls and results without owned copies; append_compaction removed
513dc51f4e6dd32f3f692659bd976b306726524a
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: aba9ac391b82
There are many coding harnesses - but this one is fast
513dc51f4e6dd32f3f692659bd976b306726524a
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+171 / −86 text lines
+2 / −2 text lines
+144 / −67 text lines
use std::borrow::Cow; match self { Self::Message(message) => EntryKind::Message { id: message.id, role: message.role, }, Self::ToolCall { call_id, .. } => EntryKind::ToolCall { call_id: *call_id }, Self::ToolResult { call_id, ok, .. } => EntryKind::ToolResult { call_id: *call_id, ok: *ok, }, Self::Meta { kind, .. } => EntryKind::Meta { compaction: kind == COMPACTION_KIND, }, } EntryContentRef::from(self).kind() /// Append the canonical CBOR of this content to `out`. This is the one /// place content is canonicalized. /// Append the canonical CBOR of this content to `out`. ciborium::ser::into_writer(&*self.canonical(), out).map_err(|e| SmithError::Session { code: "ENTRY_ENCODE".to_string(), message: e.to_string(), }) EntryContentRef::from(self).encode_into(out) }}/// Borrowed [`EntryContent`]: what recording needs without owning a copy.////// The serialize shape is the same as [`EntryContent`], so both produce the/// same canonical bytes; this is the one place content is canonicalized.#[derive(Clone, Copy, Debug, Serialize)]#[serde(tag = "kind", content = "data")]pub enum EntryContentRef<'a> { /// Chat message. Message(&'a Message), /// Tool call. ToolCall { /// Invoked tool. name: &'a str, /// Tool arguments. input: &'a serde_json::Value, /// Identifier pairing this call with its result. call_id: ToolCallId, }, /// Tool result. ToolResult { /// Whether the effect succeeded. ok: bool, /// Output or error text. output: &'a str, /// Identifier of the call this result answers. call_id: ToolCallId, }, /// Session metadata event. Meta { /// Metadata kind. kind: &'a str, /// Kind-specific payload. detail: &'a serde_json::Value, },}impl<'a> From<&'a EntryContent> for EntryContentRef<'a> { fn from(content: &'a EntryContent) -> Self { match content { EntryContent::Message(message) => Self::Message(message), EntryContent::ToolCall { name, input, call_id, } => Self::ToolCall { name, input, call_id: *call_id, }, EntryContent::ToolResult { ok, output, call_id, } => Self::ToolResult { ok: *ok, output, call_id: *call_id, }, EntryContent::Meta { kind, detail } => Self::Meta { kind, detail }, } }}impl EntryContentRef<'_> { /// The record kind of this content. #[must_use] pub fn kind(&self) -> EntryKind { match *self { Self::Message(message) => EntryKind::Message { id: message.id, role: message.role, }, Self::ToolCall { call_id, .. } => EntryKind::ToolCall { call_id }, Self::ToolResult { call_id, ok, .. } => EntryKind::ToolResult { call_id, ok }, Self::Meta { kind, .. } => EntryKind::Meta { compaction: kind == COMPACTION_KIND, }, } /// This content with every JSON value in canonical key order, borrowed /// when it already is. fn canonical(&self) -> Cow<'_, Self> { match self { /// Append the canonical CBOR of this content to `out`; JSON values are /// re-ordered into canonical key order only when they are not already. fn encode_into(&self, out: &mut Vec<u8>) -> Result<()> { let canonical_value: serde_json::Value; let canonical_message: Message; // The view borrows from `self` or from a local canonical copy. let view: EntryContentRef<'_> = match *self { } if !is_canonical(input) => Cow::Owned(Self::ToolCall { name: name.clone(), input: canonical_json(input), call_id: *call_id, }), Self::Meta { kind, detail } if !is_canonical(detail) => Cow::Owned(Self::Meta { kind: kind.clone(), detail: canonical_json(detail), }), Self::Message(message) if !message.blocks.iter().all(|block| match block { ContentBlock::ToolUse { input, .. } => is_canonical(input), _ => true, }) => { let mut message = message.clone(); for block in &mut message.blocks { if let ContentBlock::ToolUse { input, .. } = block { *input = canonical_json(input); } Cow::Owned(Self::Message(message)) other => Cow::Borrowed(other), Self::Meta { kind, detail } if !is_canonical(detail) => { canonical_value = canonical_json(detail); EntryContentRef::Meta { kind, detail: &canonical_value, } } Self::Message(message) if !message_is_canonical(message) => { canonical_message = canonical_message_of(message); EntryContentRef::Message(&canonical_message) } other => other, }; ciborium::ser::into_writer(&view, out).map_err(|e| SmithError::Session { code: "ENTRY_ENCODE".to_string(), message: e.to_string(), }) }}fn message_is_canonical(message: &Message) -> bool { message.blocks.iter().all(|block| match block { ContentBlock::ToolUse { input, .. } => is_canonical(input), _ => true, })}fn canonical_message_of(message: &Message) -> Message { let mut message = message.clone(); for block in &mut message.blocks { if let ContentBlock::ToolUse { input, .. } = block { *input = canonical_json(input); message pub fn append(&mut self, content: &EntryContent) -> Result<&Entry> { pub fn append<'a>(&mut self, content: impl Into<EntryContentRef<'a>>) -> Result<&Entry> { let content = content.into(); /// Append a compaction boundary entry after the selected entry and /// select it. Returns the record so callers can persist it. /// /// # Errors /// /// As [`Session::append`]. pub fn append_compaction(&mut self, detail: serde_json::Value) -> Result<Entry> { let content = EntryContent::Meta { kind: COMPACTION_KIND.to_string(), detail, }; self.append(&content).copied() }+6 / −2 text lines
+15 / −14 text lines
use crate::session::{Entry, EntryContent, Session};use crate::session::{Entry, EntryContentRef, Session}; self.record(EntryContentRef::ToolResult { output: output.clone(), timestamp_ms: now_ms(), }; self.record(&EntryContent::ToolResult { ok, output, output: &output, pub(crate) fn record(&mut self, content: &EntryContent) -> Result<Entry> { pub(crate) fn record<'a>(&mut self, content: impl Into<EntryContentRef<'a>>) -> Result<Entry> { use crate::session::EntryContent;+4 / −1 text lines