Skip to main content

Session

Struct Session 

Source
pub struct Session { /* private fields */ }
Expand description

A conversation session with full history

Uses Arc<Vec> internally for efficient forking (copy-on-write).

Implementations§

Source§

impl Session

Source

pub fn new() -> Self

Create a new empty session

Source

pub fn with_id(id: SessionId) -> Self

Create a session with a specific ID (for loading)

Source

pub fn id(&self) -> &SessionId

Get the session ID

Source

pub fn version(&self) -> u32

Get the session version

Source

pub fn messages(&self) -> &[Message]

Get all messages.

Source

pub fn created_at(&self) -> SystemTime

Get creation time

Source

pub fn updated_at(&self) -> SystemTime

Get last update time

Source

pub fn push(&mut self, message: Message)

Add a message to the session

Updates the timestamp. For adding multiple messages, prefer push_batch.

Source

pub fn push_batch(&mut self, messages: Vec<Message>)

Add multiple messages in one operation (single timestamp update)

More efficient than multiple push calls when adding many messages.

Source

pub async fn externalize_media( &mut self, blob_store: &dyn BlobStore, start: usize, ) -> Result<(), BlobStoreError>

Rewrite inline media payloads in-place as BlobRef pointers.

Message count is invariant across this operation — externalize only swaps inline image/media bytes for opaque blob references. This is the cross-crate-legitimate rewrite operation that used to require public messages_mut(); post-C-H1 callers in meerkat-session go through this typed method.

Does not touch updated_at — externalization is bookkeeping, not a semantic session mutation.

Source

pub fn touch(&mut self)

Explicitly update the timestamp

Call this after bulk operations that don’t update timestamps automatically.

Source

pub fn has_pending_boundary(&self) -> bool

Whether the conversation has a pending turn boundary.

Returns true if the last message is User or ToolResults, meaning the conversation is waiting for an assistant turn and run_pending can resume without a new user message.

Source

pub fn last_n(&self, n: usize) -> &[Message]

Get the last N messages

Source

pub fn total_tokens(&self) -> u64

Count total tokens used.

Source

pub fn total_usage(&self) -> Usage

Get total usage statistics for the session.

Source

pub fn record_usage(&mut self, turn_usage: Usage)

Update cumulative usage after an LLM call.

Source

pub fn append_external_user_content(&mut self, content: ContentInput)

Append externally-produced user content to the canonical transcript.

Source

pub fn append_external_assistant_blocks( &mut self, blocks: Vec<AssistantBlock>, stop_reason: StopReason, usage: Usage, )

Append externally-produced assistant output to the canonical transcript.

Source

pub fn append_realtime_transcript_event( &mut self, event: RealtimeTranscriptEvent, ) -> RealtimeTranscriptApplyOutcome

Apply an identity-bearing provider realtime transcript event.

This is the canonical append authority for provider-managed realtime turns: provider item ids, predecessor links, and content segment ids are persisted in session metadata so duplicate websocket delivery, reconnect replay, and causally equivalent event ordering cannot create duplicate or misordered canonical messages.

Source

pub fn in_flight_realtime_assistant_response_ids(&self) -> Vec<String>

Return every distinct provider response_id currently staged in the realtime-transcript metadata that has at least one unmaterialized assistant item and is not already discarded.

CC4 (Round-4 architectural reconciliation): when the live boundary signals a barge-in (TurnInterrupted), the projection sink does not know which provider response_ids have streaming deltas staged in session metadata. This accessor lets the sink fan RealtimeTranscriptEvent::AssistantTurnInterrupted events out to each in-flight response so staged-but-not-yet-materialized transcript fragments are discarded — preventing them from silently committing when the next turn’s AssistantTurnCompleted (synthesized by the CC2 fix in signal_turn_completed) sweeps the materializer.

Order is the [SessionRealtimeTranscriptState::first_seen_order] projection so callers see deterministic iteration. Items already materialized or skipped are excluded — only response_ids with at least one live unmaterialized assistant item are returned.

Source

pub fn set_system_prompt(&mut self, prompt: String)

Set a system prompt (adds or replaces System message at start)

Source

pub fn discard_transient_runtime_steer_context(&mut self) -> usize

Remove transient active-turn steer context from persisted session state.

Operator steers accepted into an already-running turn are request-local: they should be visible to that turn’s next model boundary, then vanish instead of replaying into later turns after persistence or resume.

Source

pub fn append_system_context_blocks( &mut self, appends: &[PendingSystemContextAppend], )

Append one or more runtime system-context blocks to the canonical system prompt.

Source

pub fn last_assistant_text(&self) -> Option<String>

Get the last assistant message text content.

Concatenates both Text (display) and Transcript (spoken) blocks in document order, since both lanes project to the same human-readable stream. Lane provenance is preserved on the underlying AssistantBlock for callers that need it.

Source

pub fn tool_call_count(&self) -> usize

Count tool calls made

Source

pub fn metadata(&self) -> &Map<String, Value>

Get metadata

Source

pub fn set_metadata(&mut self, key: &str, value: Value)

Set a metadata value

Source

pub fn backfill_metadata_if_absent(&mut self, key: &str, value: Value) -> bool

Backfill a missing metadata value without changing updated_at.

This is only for compatibility reads that need to hydrate metadata from an older projection. Semantic metadata mutations must use Session::set_metadata so the session timestamp advances.

Source

pub fn remove_metadata(&mut self, key: &str)

Remove a metadata value.

Source

pub fn set_session_metadata( &mut self, metadata: SessionMetadata, ) -> Result<(), Error>

Store SessionMetadata in the session metadata map.

Source

pub fn session_metadata(&self) -> Option<SessionMetadata>

Load SessionMetadata from the session metadata map.

Source

pub fn set_system_context_state( &mut self, state: SessionSystemContextState, ) -> Result<(), Error>

Store durable system-context control state in the session metadata map.

Source

pub fn system_context_state(&self) -> Option<SessionSystemContextState>

Load durable system-context control state from the session metadata map.

Source

pub fn set_deferred_turn_state( &mut self, state: SessionDeferredTurnState, ) -> Result<(), Error>

Store durable deferred-turn control state in the session metadata map.

Source

pub fn deferred_turn_state(&self) -> Option<SessionDeferredTurnState>

Load durable deferred-turn control state from the session metadata map.

Source

pub fn set_build_state(&mut self, state: SessionBuildState) -> Result<(), Error>

Store recoverable build-only session state in the session metadata map.

Source

pub fn build_state(&self) -> Option<SessionBuildState>

Load recoverable build-only session state from the session metadata map.

Source

pub fn set_tool_visibility_state( &mut self, state: SessionToolVisibilityState, ) -> Result<(), Error>

Store durable tool-visibility control state in the session metadata map.

Source

pub fn tool_visibility_state( &self, ) -> Result<Option<SessionToolVisibilityState>, Error>

Load durable tool-visibility control state from the session metadata map.

Source

pub fn try_tool_visibility_state( &self, ) -> Result<Option<SessionToolVisibilityState>, Error>

Load durable tool-visibility control state while distinguishing absent metadata from malformed canonical metadata.

Source

pub fn transcript_history_state( &self, ) -> Result<Option<TranscriptHistoryState>, Error>

Load typed transcript revision state from metadata.

Source

pub fn validate_transcript_history_state( &self, ) -> Result<(), TranscriptEditError>

Validate the retained transcript revision graph, when present.

Source

pub fn transcript_revision_body( &self, revision: &str, ) -> Result<Option<TranscriptRevisionBody>, Error>

Return the retained immutable body for a transcript revision.

Source

pub fn transcript_revision_messages( &self, revision: &str, ) -> Result<Option<Vec<Message>>, Error>

Return the ordered messages for a retained transcript revision.

Source

pub fn apply_transcript_history_state( &mut self, state: TranscriptHistoryState, ) -> Result<(), TranscriptEditError>

Materialize this session projection from a typed transcript history graph.

Source

pub fn transcript_revision(&self) -> Result<String, Error>

Current transcript head revision. Rows written before transcript revisions derive their implicit head from the current message snapshot.

Source

pub fn commit_transcript_rewrite( &mut self, selection: TranscriptRewriteSelection, replacement: Vec<Message>, reason: TranscriptRewriteReason, actor: Option<String>, expected_parent_revision: Option<String>, ) -> Result<TranscriptRewriteCommit, TranscriptEditError>

Commit a same-session transcript rewrite and advance the transcript head.

Source

pub fn set_mob_tool_authority_context( &mut self, authority_context: Option<MobToolAuthorityContext>, ) -> Result<(), Error>

Store typed mob operator authority inside canonical build-state metadata.

Source

pub fn mob_tool_authority_context(&self) -> Option<MobToolAuthorityContext>

Load typed mob operator authority from canonical build-state metadata.

Source

pub fn fork_at(&self, index: usize) -> Self

Fork the session at a specific message index

Creates a new session with a subset of messages. The messages are copied (not shared) since the new session has a different prefix.

Source

pub fn fork_replacing( &self, message_index: usize, replacement: TranscriptReplacement, ) -> Result<Self, TranscriptEditError>

Fork the session and replace the message at message_index.

The returned session contains the original prefix before message_index, followed by the typed replacement. Later source messages are intentionally omitted so follow-up work continues from the edited branch rather than replaying stale descendants.

Source

pub fn fork(&self) -> Self

Fork the entire session (full history)

This is O(1) - the new session shares the message buffer via Arc. Copy-on-write occurs when either session mutates its messages.

Trait Implementations§

Source§

impl Clone for Session

Source§

fn clone(&self) -> Session

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Session

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Session

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Session

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<&Session> for SessionMeta

Source§

fn from(session: &Session) -> Self

Converts to this type from the input type.
Source§

impl Serialize for Session

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,