repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

refactor(core): EntryContentRef records tool calls and results without owned copies; append_compaction removed

513dc51f4e6dd32f3f692659bd976b306726524a

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (5)

+171 / −86 text lines

Diff layout

smith-core/src/lib.rs

Modified

+2 / −2 text lines

2626pub use bash::{BashResult, execute};
2727pub use frame::{Frame, Recovery, encode_entry, read_frames, write_frame};
2828pub use session::{
29 Branch, COMPACTION_KIND, Entry, EntryContent, EntryFrame, EntryKind, Session, SessionHeader,
30 Span,
29 Branch, COMPACTION_KIND, Entry, EntryContent, EntryContentRef, EntryFrame, EntryKind, Session,
30 SessionHeader, Span,
3131};
3232pub use store::{
3333 OpenSession, SessionWriter, create_session, fork_session, load_session, open_session,

smith-core/src/session.rs

Modified

+144 / −67 text lines

1010use smith::error::{Result, SmithError};
1111use smith::id::{BranchId, EntryId, MessageId, SessionId, ToolCallId};
1212use smith::message::{ContentBlock, Message, Role};
13use std::borrow::Cow;
1413use std::collections::HashMap;
1615/// Meta entry kind that marks a compaction boundary.
278277 /// The record kind of this content.
279278 #[must_use]
280279 pub fn kind(&self) -> EntryKind {
281 match self {
282 Self::Message(message) => EntryKind::Message {
283 id: message.id,
284 role: message.role,
285 },
286 Self::ToolCall { call_id, .. } => EntryKind::ToolCall { call_id: *call_id },
287 Self::ToolResult { call_id, ok, .. } => EntryKind::ToolResult {
288 call_id: *call_id,
289 ok: *ok,
290 },
291 Self::Meta { kind, .. } => EntryKind::Meta {
292 compaction: kind == COMPACTION_KIND,
293 },
294 }
280 EntryContentRef::from(self).kind()
295281 }
297283 /// Decode content from its canonical CBOR bytes.
306292 })
307293 }
309 /// Append the canonical CBOR of this content to `out`. This is the one
310 /// place content is canonicalized.
295 /// Append the canonical CBOR of this content to `out`.
311296 fn encode_into(&self, out: &mut Vec<u8>) -> Result<()> {
312 ciborium::ser::into_writer(&*self.canonical(), out).map_err(|e| SmithError::Session {
313 code: "ENTRY_ENCODE".to_string(),
314 message: e.to_string(),
315 })
297 EntryContentRef::from(self).encode_into(out)
298 }
299}
301/// Borrowed [`EntryContent`]: what recording needs without owning a copy.
302///
303/// The serialize shape is the same as [`EntryContent`], so both produce the
304/// same canonical bytes; this is the one place content is canonicalized.
305#[derive(Clone, Copy, Debug, Serialize)]
306#[serde(tag = "kind", content = "data")]
307pub enum EntryContentRef<'a> {
308 /// Chat message.
309 Message(&'a Message),
310 /// Tool call.
311 ToolCall {
312 /// Invoked tool.
313 name: &'a str,
314 /// Tool arguments.
315 input: &'a serde_json::Value,
316 /// Identifier pairing this call with its result.
317 call_id: ToolCallId,
318 },
319 /// Tool result.
320 ToolResult {
321 /// Whether the effect succeeded.
322 ok: bool,
323 /// Output or error text.
324 output: &'a str,
325 /// Identifier of the call this result answers.
326 call_id: ToolCallId,
327 },
328 /// Session metadata event.
329 Meta {
330 /// Metadata kind.
331 kind: &'a str,
332 /// Kind-specific payload.
333 detail: &'a serde_json::Value,
334 },
335}
337impl<'a> From<&'a EntryContent> for EntryContentRef<'a> {
338 fn from(content: &'a EntryContent) -> Self {
339 match content {
340 EntryContent::Message(message) => Self::Message(message),
341 EntryContent::ToolCall {
342 name,
343 input,
344 call_id,
345 } => Self::ToolCall {
346 name,
347 input,
348 call_id: *call_id,
349 },
350 EntryContent::ToolResult {
351 ok,
352 output,
353 call_id,
354 } => Self::ToolResult {
355 ok: *ok,
356 output,
357 call_id: *call_id,
358 },
359 EntryContent::Meta { kind, detail } => Self::Meta { kind, detail },
360 }
361 }
362}
364impl EntryContentRef<'_> {
365 /// The record kind of this content.
366 #[must_use]
367 pub fn kind(&self) -> EntryKind {
368 match *self {
369 Self::Message(message) => EntryKind::Message {
370 id: message.id,
371 role: message.role,
372 },
373 Self::ToolCall { call_id, .. } => EntryKind::ToolCall { call_id },
374 Self::ToolResult { call_id, ok, .. } => EntryKind::ToolResult { call_id, ok },
375 Self::Meta { kind, .. } => EntryKind::Meta {
376 compaction: kind == COMPACTION_KIND,
377 },
378 }
316379 }
318 /// This content with every JSON value in canonical key order, borrowed
319 /// when it already is.
320 fn canonical(&self) -> Cow<'_, Self> {
321 match self {
381 /// Append the canonical CBOR of this content to `out`; JSON values are
382 /// re-ordered into canonical key order only when they are not already.
383 fn encode_into(&self, out: &mut Vec<u8>) -> Result<()> {
384 let canonical_value: serde_json::Value;
385 let canonical_message: Message;
386 // The view borrows from `self` or from a local canonical copy.
387 let view: EntryContentRef<'_> = match *self {
322388 Self::ToolCall {
323389 name,
324390 input,
325391 call_id,
326 } if !is_canonical(input) => Cow::Owned(Self::ToolCall {
327 name: name.clone(),
328 input: canonical_json(input),
329 call_id: *call_id,
330 }),
331 Self::Meta { kind, detail } if !is_canonical(detail) => Cow::Owned(Self::Meta {
332 kind: kind.clone(),
333 detail: canonical_json(detail),
334 }),
335 Self::Message(message)
336 if !message.blocks.iter().all(|block| match block {
337 ContentBlock::ToolUse { input, .. } => is_canonical(input),
338 _ => true,
339 }) =>
340 {
341 let mut message = message.clone();
342 for block in &mut message.blocks {
343 if let ContentBlock::ToolUse { input, .. } = block {
344 *input = canonical_json(input);
345 }
392 } if !is_canonical(input) => {
393 canonical_value = canonical_json(input);
394 EntryContentRef::ToolCall {
395 name,
396 input: &canonical_value,
397 call_id,
346398 }
347 Cow::Owned(Self::Message(message))
348399 }
349 other => Cow::Borrowed(other),
400 Self::Meta { kind, detail } if !is_canonical(detail) => {
401 canonical_value = canonical_json(detail);
402 EntryContentRef::Meta {
403 kind,
404 detail: &canonical_value,
405 }
406 }
407 Self::Message(message) if !message_is_canonical(message) => {
408 canonical_message = canonical_message_of(message);
409 EntryContentRef::Message(&canonical_message)
410 }
411 other => other,
412 };
413 ciborium::ser::into_writer(&view, out).map_err(|e| SmithError::Session {
414 code: "ENTRY_ENCODE".to_string(),
415 message: e.to_string(),
416 })
417 }
418}
420fn message_is_canonical(message: &Message) -> bool {
421 message.blocks.iter().all(|block| match block {
422 ContentBlock::ToolUse { input, .. } => is_canonical(input),
423 _ => true,
424 })
425}
427fn canonical_message_of(message: &Message) -> Message {
428 let mut message = message.clone();
429 for block in &mut message.blocks {
430 if let ContentBlock::ToolUse { input, .. } = block {
431 *input = canonical_json(input);
350432 }
351433 }
434 message
354437/// Wall-clock milliseconds since the Unix epoch, saturating on overflow.
479562 ///
480563 /// Returns [`SmithError::Session`] when the content cannot be encoded or
481564 /// the arena is full; the session is unchanged then.
482 pub fn append(&mut self, content: &EntryContent) -> Result<&Entry> {
565 pub fn append<'a>(&mut self, content: impl Into<EntryContentRef<'a>>) -> Result<&Entry> {
483566 self.append_with(content, |_, _| Ok(()))
484567 }
490573 ///
491574 /// As [`Session::append`], or the error of `persist`; the session is
492575 /// unchanged then.
493 pub fn append_with(
576 pub fn append_with<'a>(
494577 &mut self,
495 content: &EntryContent,
578 content: impl Into<EntryContentRef<'a>>,
496579 persist: impl FnOnce(&Entry, &[u8]) -> Result<()>,
497580 ) -> Result<&Entry> {
581 let content = content.into();
498582 let parent = self.selected_id();
499583 let offset = self.payloads.len();
500584 let staged = content
521605 Ok(self.branches[self.active_branch_idx].append(entry))
522606 }
524 /// Append a compaction boundary entry after the selected entry and
525 /// select it. Returns the record so callers can persist it.
526 ///
527 /// # Errors
528 ///
529 /// As [`Session::append`].
530 pub fn append_compaction(&mut self, detail: serde_json::Value) -> Result<Entry> {
531 let content = EntryContent::Meta {
532 kind: COMPACTION_KIND.to_string(),
533 detail,
534 };
535 self.append(&content).copied()
536 }
538608 /// The canonical CBOR content bytes of `entry`; empty when `entry` does
539609 /// not belong to this session.
540610 #[must_use]
765835 EntryContent::Message(Message::with_text(Role::User, text))
766836 }
838 fn compaction(detail: serde_json::Value) -> EntryContent {
839 EntryContent::Meta {
840 kind: COMPACTION_KIND.to_string(),
841 detail,
842 }
843 }
768845 fn text_of(session: &Session, entry: &Entry) -> String {
769846 match session.content(entry).unwrap() {
770847 EntryContent::Message(m) => format!("{}", m.blocks.len()),
888965 fn fork_preserves_ids_order_leaf_and_compaction_boundary() {
889966 let mut session = Session::new();
890967 let root = *session.append(&message("root")).unwrap();
891 let boundary = session
892 .append_compaction(serde_json::json!({"summarized": 1}))
968 let boundary = *session
969 .append(&compaction(serde_json::json!({"summarized": 1})))
893970 .unwrap();
894971 let after = *session.append(&message("after")).unwrap();
10141091 fn compaction_boundary_survives_a_frame_round_trip() {
10151092 let mut session = Session::new();
10161093 session.append(&message("root")).unwrap();
1017 let boundary = session.append_compaction(serde_json::json!({})).unwrap();
1094 let boundary = *session.append(&compaction(serde_json::json!({}))).unwrap();
10181095 let restored = Session::from_frames(&frames(&session)).unwrap();
10191096 assert_eq!(restored.compaction_boundary, Some(boundary.id));
10201097 assert_eq!(restored.id, session.id);

smith-core/src/store.rs

Modified

+6 / −2 text lines

339339)]
340340mod tests {
341341 use super::*;
342 use crate::session::COMPACTION_KIND;
342343 use crate::session::{EntryContent, EntryFrame, EntryKind, Session};
343344 use smith::message::{ContentBlock, Message, Role};
735736 .writer
736737 .append_entry(&root, opened.session.bytes(&root))
737738 .unwrap();
738 let boundary = opened
739 let boundary = *opened
739740 .session
740 .append_compaction(serde_json::json!({"kept": 1}))
741 .append(&EntryContent::Meta {
742 kind: COMPACTION_KIND.to_string(),
743 detail: serde_json::json!({"kept": 1}),
744 })
741745 .unwrap();
742746 opened
743747 .writer

smith-core/src/tools.rs

Modified

+15 / −14 text lines

11//! Tool registry, validation, built-in file effects, and the durable
22//! outcome boundary between successful effects and recorded session frames.
4use crate::session::{Entry, EntryContent, Session};
4use crate::session::{Entry, EntryContentRef, Session};
55use crate::store::SessionWriter;
66use smith::config::Config;
77use smith::error::{Result, SmithError};
345345 if self.cancel.is_cancelled() && failure == EffectFailure::ReturnError {
346346 return Err(SmithError::Cancelled);
347347 }
348 self.record(&EntryContent::ToolCall {
349 name: name.to_string(),
350 input: recorded_input.clone(),
348 self.record(EntryContentRef::ToolCall {
349 name,
350 input: recorded_input,
351351 call_id,
352352 })?;
353353 let effect = if self.cancel.is_cancelled() {
367367 Ok(text) => redact_output(text),
368368 Err(err) => redact_output(&err.to_string()),
369369 };
370 let outcome = ToolOutcome {
371 call_id,
372 name: name.to_string(),
370 self.record(EntryContentRef::ToolResult {
373371 ok,
374 output: output.clone(),
375 timestamp_ms: now_ms(),
376 };
377 self.record(&EntryContent::ToolResult {
378 ok,
379 output,
372 output: &output,
380373 call_id,
381374 })
382375 .map_err(|err| SmithError::RecordFailed {
384377 mutation_applied: ok && mutates_host(name),
385378 message: err.to_string(),
386379 })?;
380 let outcome = ToolOutcome {
381 call_id,
382 name: name.to_string(),
383 ok,
384 output,
385 timestamp_ms: now_ms(),
386 };
387387 match effect {
388388 Ok(_) => Ok(outcome),
389389 Err(_) if failure == EffectFailure::ReturnOutcome => Ok(outcome),
394394 /// Append `content` after the selected entry and durably record it
395395 /// first; a failed write leaves the session unchanged.
396 pub(crate) fn record(&mut self, content: &EntryContent) -> Result<Entry> {
396 pub(crate) fn record<'a>(&mut self, content: impl Into<EntryContentRef<'a>>) -> Result<Entry> {
397397 let writer = self.writer.as_mut();
398398 self.session
399399 .append_with(content, |entry, bytes| {
934934)]
935935mod tests {
936936 use super::*;
937 use crate::session::EntryContent;
937938 use crate::session::EntryKind;
938939 use std::path::PathBuf;

smith-core/src/trace.rs

Modified

+4 / −1 text lines

142142 .unwrap();
143143 tools
144144 .session
145 .append_compaction(serde_json::json!({}))
145 .append(&EntryContent::Meta {
146 kind: COMPACTION_KIND.to_string(),
147 detail: serde_json::json!({}),
148 })
146149 .unwrap();
148151 assert_eq!(