Skip to main content

Context

Struct Context 

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

The entire context window state. Fully serializable for persistence.

Implementations§

Source§

impl Context

Source

pub fn new() -> Self

Creates a new empty context.

Source

pub fn insert_system<T: Serialize>(&mut self, value: &T)

Inserts or replaces a persistent system block.

Identity is derived from the snake_case type name of T.

Source

pub fn insert_system_named( &mut self, tag: impl Into<String>, content: impl Into<String>, )

Inserts or replaces a persistent system block with an explicit tag.

Source

pub fn remove_system<T>(&mut self)

Removes a persistent system block by type.

Source

pub fn remove_system_named(&mut self, tag: &str)

Removes a persistent system block by explicit tag.

Source

pub fn system_block_count(&self) -> usize

Returns the number of persistent system blocks.

Source

pub fn has_system_block(&self, tag: &str) -> bool

Returns whether a persistent system block with tag exists.

Source

pub const fn system_blocks(&self) -> &IndexMap<String, String>

Returns an immutable view of persistent system blocks.

Source

pub const fn system_blocks_mut(&mut self) -> &mut IndexMap<String, String>

Returns a mutable view of persistent system blocks.

Source

pub fn insert_system_text( &mut self, tag: impl Into<String>, content: impl Into<String>, )

Inserts or replaces a persistent system block with raw text.

Unlike insert_system and insert_system_named, the content is stored verbatim without any XML wrapping. This is the preferred entry point for prose system blocks such as workspace descriptions, runtime metadata, and environment hints, where XML structure adds tokens without providing semantic value.

Use insert_system only when the block is a structured payload that genuinely needs XML delimiters to separate context from instructions (for example, attached documents).

Source

pub fn stable_prefix_fingerprint(&self) -> u64

Returns a stable fingerprint of the current system blocks in order.

The fingerprint changes if and only if the ordered set of (tag, content) pairs changes. Hosts can use this to detect cache-invalidating modifications to the stable system prefix (for example, to track KV-cache hit rate over time).

Source

pub fn insert_reminder<T: Serialize>(&mut self, value: &T)

Inserts an ephemeral reminder.

Reminders are transient by design: clear_reminders runs at the top of every request’s reminder repopulation, so a reminder reaches the model only when it is (re)generated inside that populate pass. Anything the agent must actually deliver — mid-turn corrections, queued alerts — belongs in push_alert, which survives repopulation and is pruned by reassembly/compaction instead.

Source

pub fn push_alert<T: Serialize>(&mut self, value: &T)

Pushes a durable system alert, rendered like a reminder.

The alert enters the conversation stream as a system message and stays there until reassembly or compaction prunes system alerts — the channel to use for content that must reach the next request rather than being regenerated by reminder repopulation.

Source

pub fn clear_reminders(&mut self)

Clears all ephemeral reminders.

Source

pub fn reminders(&self) -> Vec<&str>

Returns current reminders.

Source

pub fn set_handoff(&mut self, handoff: impl Into<String>)

Sets or replaces the compaction handoff document.

Source

pub fn set_handoff_document(&mut self, handoff: &HandoffDocument)

Sets the compaction handoff document from a structured handoff artifact.

Source

pub fn clear_handoff(&mut self)

Clears the compaction handoff document.

Source

pub fn handoff(&self) -> Option<&str>

Returns the current compaction handoff document.

Source

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

Appends a message to recent conversation.

Source

pub fn extend(&mut self, messages: impl IntoIterator<Item = Message>)

Extends recent conversation with multiple messages.

Source

pub fn len_recent(&self) -> usize

Returns number of recent conversation messages.

Source

pub fn count_recent_system_messages(&self) -> usize

Returns the number of recent system messages.

Source

pub fn recent(&self) -> Vec<&Message>

Returns recent conversation messages.

Source

pub fn last(&self) -> Option<&Message>

Returns the latest recent message.

Source

pub fn is_conversation_empty(&self) -> bool

Returns whether recent conversation is empty.

Source

pub fn drain_oldest(&mut self, keep: usize) -> Vec<Message>

Drains oldest recent messages while keeping the latest keep messages.

Source

pub fn conversation_messages(&self) -> Vec<Message>

Returns recent conversation messages cloned.

Source

pub fn build_messages(&self) -> Vec<Message>

Builds the full LLM message list.

Layout:

  1. Persistent system blocks (single cacheable prefix)
  2. Compaction handoff (optional system message)
  3. Ordered runtime items (reminders and conversation messages)
Source

pub fn clear_recent(&mut self)

Clears only recent conversation messages.

Source

pub fn clear_history(&mut self)

Clears all non-persistent context: reminders, handoff, recent conversation.

Source

pub fn clear_all(&mut self)

Clears everything, including persistent system blocks.

Source

pub fn fork(&self) -> Self

Clones the context.

Source

pub fn checkpoint(&self) -> ContextCheckpoint

Creates a checkpoint that can be restored later.

Source

pub fn restore(&mut self, checkpoint: ContextCheckpoint)

Restores reminders, handoff, and recent conversation from checkpoint.

Source

pub fn stage_system_text( &mut self, tag: impl Into<String>, content: impl Into<String>, ) -> bool

Stages a replacement for a system block, deferring the cache-invalidating rewrite until the next reassemble.

If no block with tag exists yet, the content is inserted immediately (nothing to preserve in the cache) and false is returned. Otherwise the update is staged and true is returned; the host should surface the change to the model as an appended diff alert.

Source

pub fn staged_system_update(&self, tag: &str) -> Option<&str>

Returns the staged replacement for tag, if any.

Source

pub fn reassemble(&mut self) -> ReassemblyReport

Performs a lightweight context reassembly.

This rewrites the window without calling any LLM:

  1. folds staged system block updates into the stable prefix,
  2. clears all ephemeral reminders,
  3. removes recent system messages (system alerts),
  4. tombstones tool results superseded by a later identical call or an identical later result.

Reassembly invalidates the KV-cache prefix, so hosts should run it when the cache is already cold (idle gap) or right before compaction.

Source

pub fn estimate_reassembly_savings(&self) -> usize

Estimates how many bytes a reassemble would free, without mutating the context.

Source

pub fn prune_recent_system_messages(&mut self) -> usize

Removes recent system messages and returns how many were pruned.

Source

pub fn restore_runtime_state(&mut self, restored: Self)

Restores runtime-managed state from another serialized context while preserving the current persistent system blocks.

Trait Implementations§

Source§

impl Clone for Context

Source§

fn clone(&self) -> Self

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 Context

Source§

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

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

impl Default for Context

Source§

fn default() -> Self

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

impl<'de> Deserialize<'de> for Context

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 Serialize for Context

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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> TryClone for T
where T: Clone,

Source§

fn try_clone(&self) -> Result<T, Error>

Clones self, possibly returning an error.
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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