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 with the default SystemLayout.

Source

pub fn with_layout(layout: SystemLayout) -> Self

Creates a new empty context whose system blocks follow layout.

Source

pub fn set_layout(&mut self, layout: SystemLayout)

Lays the system blocks out in layout’s order.

§Panics

Panics if a block already present has no slot in layout.

Source

pub const fn instructions(&self) -> &SystemRegion<Instruction>

The instruction blocks.

Source

pub const fn instructions_mut(&mut self) -> &mut SystemRegion<Instruction>

The instruction blocks, for change.

Inserting or replacing a block rewrites the cacheable prefix immediately; content that changes mid-session goes through update_live instead.

Source

pub const fn external(&self) -> &SystemRegion<External>

The external-content blocks.

Source

pub const fn external_mut(&mut self) -> &mut SystemRegion<External>

The external-content blocks, for change.

Inserting or replacing a block rewrites the cacheable prefix immediately; content that changes mid-session goes through update_live instead.

Source

pub fn update_live( &mut self, content: &LiveContent, update: impl FnOnce(&mut LiveUpdate<'_>), ) -> bool

Brings live content — system blocks that change while the session runs, such as a repository’s AGENTS.md or the command table — to the versions update gives, without rewriting a prefix a provider may have cached.

Before any request has carried the prefix, the blocks are written into it. After, the prefix is left byte-identical: the changes are staged for the next reassembly and announced in one durable alert naming content, carrying the diff from what the model knows (the prefix with every earlier announced change applied) to the new versions. The next reassembly — a compaction, or a cache gone cold — folds the clean versions in and removes every such alert, so nothing restates a change. An update that leaves the model’s view as it is announces nothing, so a host may call this every turn.

Returns whether an alert was appended.

§Panics

Panics if update names a slot the layout does not have.

Source

pub const fn live_source_blocks(&self) -> &SystemRegion<Sourced>

The blocks live sources rendered, as the prefix holds them.

Source

pub fn system_block_count(&self) -> usize

Returns the number of persistent system blocks, live source blocks included.

Source

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

Renders the cacheable system prefix: the instruction blocks, then the external-content notice and blocks. None when there is no block.

Source

pub fn stable_prefix_fingerprint(&self) -> u64

Returns a stable fingerprint of the rendered system prefix and the live source blocks after it.

The fingerprint changes if and only if those bytes change. Hosts can use this to detect cache-invalidating modifications to the stable prefix (for example, to track KV-cache hit rate over time).

Source

pub fn has_staged_system_updates(&self) -> bool

Whether any system block or live source block rewrite is waiting for reassembly.

Source

pub fn set_handoff(&mut self, handoff: Handoff)

Sets or replaces the compaction handoff.

Source

pub fn clear_handoff(&mut self)

Clears the compaction handoff.

Source

pub const fn handoff(&self) -> Option<&Handoff>

Returns the current compaction handoff document.

Source

pub fn handoff_file_index(&self) -> &[String]

The file index of the current handoff, empty when there is none.

Source

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

Appends a message to the window and returns its sequence number.

Source

pub fn push_kept(&mut self, message: Message) -> u64

Appends a tool result that closes an exchange kept verbatim through compaction, and returns its sequence number.

Source

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

Appends several messages to the window.

Source

pub fn push_alert<T: Template>(&mut self, value: &T) -> u64

Appends a durable alert, rendered from its typed template as a system message.

The alert enters the conversation and stays there until reassembly or compaction prunes it — the channel for content that must reach the next request rather than being re-rendered by a ContextSource every time.

§Panics

Panics if the template fails to render.

Source

pub fn push_block_alert(&mut self, block: &Block) -> u64

Appends a durable alert rendered by a context source.

Source

pub const fn fork_point(&self) -> u64

Returns the sequence number the next item will receive.

This is the fork point handed to a background compaction: every item numbered at or above it arrived after the fork and must survive the handoff that replaces the rest.

Source

pub fn attachment_catalog(&self, fork_point: u64) -> Vec<AttachmentCatalogEntry>

The catalog of attachments the user messages below fork_point carry, in conversation order.

Offered to the compaction model so its handoff can name the attachments the next turns still need; apply_handoff resolves the names back to the reference each entry carries.

Source

pub fn items_since(&self, seq: u64) -> Vec<Message>

Returns the items added at or after seq.

Source

pub const fn len_recent(&self) -> usize

Returns number of conversation messages.

Source

pub fn len_below(&self, fork_point: u64) -> usize

The number of conversation messages older than fork_point: those a handoff forked there replaces.

Source

pub fn count_recent_system_messages(&self) -> usize

Returns the number of system messages in the conversation.

Source

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

Returns the conversation messages.

Source

pub fn configured_effort(&self) -> Option<ReasoningEffort>

The reasoning effort the window’s last configuration update set, if it holds one.

Source

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

Returns the latest conversation message.

Source

pub const fn is_conversation_empty(&self) -> bool

Returns whether the conversation is empty.

Source

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

Returns the conversation messages, cloned.

Source

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

Drains the oldest messages while keeping the latest keep of them.

Source

pub fn build_request(&self, tail: &[Block]) -> Vec<Message>

Builds the request message list, with tail appended after the conversation.

Layout:

  1. persistent system blocks, as one cacheable system message,
  2. each live source block, as a system message of its own,
  3. the compaction handoff, if any,
  4. the append-only conversation,
  5. one system message holding every live tail block.

Steps 1-4 are byte-identical to the previous request whenever nothing was staged or compacted, which is exactly the condition a provider prefix cache needs.

Source

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

Builds the request message list with no live tail.

Used for measurement and for the compaction fork, which must reproduce the prefix the main request already paid to cache.

Source

pub fn stable_chars(&self) -> usize

The number of characters the cacheable part of the window renders to.

Source

pub fn conversation_chars(&self) -> usize

The number of characters the conversation renders to.

Source

pub fn clear_recent(&mut self)

Clears only the conversation, keeping system blocks and the handoff.

Source

pub fn clear_history(&mut self)

Clears all non-persistent context: the handoff and the 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 the handoff and conversation from a checkpoint.

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.

Source

pub fn apply_handoff( &mut self, handoff: Handoff, fork_point: u64, user_message_chars: usize, kept_attachments: &HashSet<AttachmentRef>, )

Replaces the conversation with a compaction result.

handoff becomes the new anchor and only the items numbered at or above fork_point are kept: they arrived while the handoff was being written and are not described by it.

An alert below the fork that no request has carried yet stays too: the model has not seen it, whatever the handoff says of it.

The user’s own words outlive the handoff beside it, verbatim and in order: every ask_user exchange from below the fork, whatever its size, and the newest user messages that fit user_message_chars characters. An exchange is the question and its answer together, so it is kept or dropped whole, and it is dropped never.

The last configuration update below the fork is kept too, in its place, so the effort it set stays in force: the handoff restates it.

A kept user message carries only the attachments kept_attachments names, resolved from the catalog the compaction’s instruction rendered; a message whose attachment is named is kept even when it falls outside user_message_chars, and every unnamed attachment is gone with the conversation the handoff replaced.

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. removes durable system alerts,
  3. tombstones tool results superseded by a later identical call or an identical later result.

Reassembly invalidates the cacheable prefix, so it runs as part of applying a compaction, which rewrites the prefix anyway.

Source

pub fn reassemble_below(&mut self, fork_point: u64) -> ReassemblyReport

reassemble that removes only the durable system alerts numbered below fork_point, and every live-content and state alert.

Applying a compaction handoff uses it: alerts at or after the fork arrived while the handoff was written, are not described by it and must reach the model. A live-content alert is the exception: the change it announced is folded into the prefix here; so is a state alert, whose source restates the current value after it. An alert no request has carried yet stays wherever it is, so an event is dropped only once it was delivered.

Source

pub fn estimate_reassembly_savings(&self) -> usize

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

Source

pub fn prune_system_messages_below(&mut self, fork_point: u64) -> usize

Removes the delivered durable system alerts numbered below fork_point and returns how many were pruned. An alert no request has carried yet stays, as it does in reassemble_below.

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<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> 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 = !

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<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