Skip to main content

Session

Struct Session 

Source
pub struct Session {
Show 42 fields pub id: String, pub session_version: Option<u32>, pub observed_runtime_session_version: Option<Option<u32>>, pub title: String, pub pinned: bool, pub title_version: u64, pub title_generated: bool, pub metadata_version: u64, pub root_orchestration_only: bool, pub root_tool_authority_revision: u64, pub root_mode_transition_epoch: u64, pub root_mode_operations: Vec<RootModeOperationReceipt>, pub kind: SessionKind, pub authority_identity: SessionAuthorityIdentity, pub supervisor_management: Option<SupervisorManagementState>, pub conversation_reset: Option<ConversationResetState>, pub parent_session_id: Option<String>, pub parent_created_at: Option<DateTime<Utc>>, pub root_session_id: String, pub spawn_depth: u32, pub messages: Vec<Message>, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, pub task_list: Option<TaskList>, pub pending_question: Option<PendingQuestion>, pub model: String, pub model_ref: Option<ProviderModelRef>, pub reasoning_effort: Option<ReasoningEffort>, pub metadata: HashMap<String, String>, pub token_budget: Option<TokenBudget>, pub resolved_token_budget: Option<(String, TokenBudget)>, pub token_usage: Option<TokenBudgetUsage>, pub conversation_summary: Option<ConversationSummary>, pub prompt_snapshot: Option<PromptSnapshot>, pub compression_events: Vec<CompressionEvent>, pub model_context_state: Option<ModelContextState>, pub provider_transcript: ProviderTranscriptState, pub compression_instructions: Option<String>, pub agent_runtime_state: Option<AgentRuntimeState>, pub runtime_metadata: Option<SessionRuntimeMetadata>, pub force_manual_compression: Option<String>, pub workspace: Option<String>,
}
Expand description

A complete conversation session with state management.

Fields§

§id: String§session_version: Option<u32>

Behavior contract selected at creation. Missing is supported legacy data, never an automatic upgrade or a permission grant.

§observed_runtime_session_version: Option<Option<u32>>

Storage-only observation; Main remains the canonical behavior stamp. Retaining a conflicting sidecar version prevents a silent downgrade.

§title: String§pinned: bool§title_version: u64§title_generated: bool

Whether the initial title lifecycle has been finalized. New root sessions start pending (false); generated, fallback, and explicit manual titles finalize it (true). Legacy sessions default to true so an upgrade never overwrites an existing user-authored title.

§metadata_version: u64

Authoritative UI metadata revision. Bumped by every authoritative metadata write (title / pinned / future replayable metadata fields). Runtime / non-authoritative paths must not bump this; they read it to detect when their session struct holds stale UI metadata.

§root_orchestration_only: bool

Host-selected Root execution authority, independent of prompt guidance.

§root_tool_authority_revision: u64

CAS fence for changing Root execution authority across Store instances.

§root_mode_transition_epoch: u64

Monotonic CAS for terminal Root-mode operations, including fences that leave the tool policy unchanged. Independent of tool authority revision.

§root_mode_operations: Vec<RootModeOperationReceipt>

Bounded terminal receipts. V2 binds this history into the Root proof.

§kind: SessionKind§authority_identity: SessionAuthorityIdentity

Trusted identity; raw metadata and ordinary persistence cannot assign it.

§supervisor_management: Option<SupervisorManagementState>

Trusted host-managed scope and links; ordinary constructors never inherit it.

§conversation_reset: Option<ConversationResetState>

Canonical conversation-reset generation and bounded operation receipts. Absence is the original zero generation. Only the separate fenced reset transaction may advance it; ordinary writers preserve the exact ledger.

§parent_session_id: Option<String>§parent_created_at: Option<DateTime<Utc>>

Exact direct-parent birth captured at creation, never inferred on activation. Legacy / ID-only children lack this proof; Roots leave it absent.

§root_session_id: String§spawn_depth: u32§messages: Vec<Message>§created_at: DateTime<Utc>§updated_at: DateTime<Utc>§task_list: Option<TaskList>§pending_question: Option<PendingQuestion>§model: String§model_ref: Option<ProviderModelRef>§reasoning_effort: Option<ReasoningEffort>§metadata: HashMap<String, String>§token_budget: Option<TokenBudget>§resolved_token_budget: Option<(String, TokenBudget)>

Runtime snapshot of the model-limit-derived budget for downstream readers in the current round, keyed by model. It is never persisted and never short-circuits the next round’s resolution, so live model_limits.json edits and provider-metadata refreshes take effect without reloading the session. token_budget above remains the persisted genuine/child override that takes priority. (#180, #763)

§token_usage: Option<TokenBudgetUsage>§conversation_summary: Option<ConversationSummary>§prompt_snapshot: Option<PromptSnapshot>§compression_events: Vec<CompressionEvent>§model_context_state: Option<ModelContextState>

Durable, provider-neutral host-context timeline. Synthetic ledger events are projected only into model requests and never exposed through messages or the existing session API/UI transcript.

§provider_transcript: ProviderTranscriptState

Durable provider-native discovery history. This is separate from the user-visible messages lane and is replayed only through a matching provider family/protocol adapter.

§compression_instructions: Option<String>

Custom instructions for conversation summarization at the session level. Overrides config-level compression_instructions when set.

§agent_runtime_state: Option<AgentRuntimeState>§runtime_metadata: Option<SessionRuntimeMetadata>

Typed view over the well-known runtime metadata keys previously smuggled through metadata. Accessed via the symmetric accessor layer (runtime_metadata_access) which dual-writes the legacy metadata strings and falls back to them on read. Additive/optional: old persisted sessions without this field load cleanly.

§force_manual_compression: Option<String>

Runtime-only flag: when set, the next mid-turn compression check should force compression regardless of threshold. Set by compact_context tool.

§workspace: Option<String>

Workspace directory for file operations in this session. For child sessions, this is set from the workspace field in CreateChildInput.

Implementations§

Source§

impl Session

Source

pub fn record_llm_request_diagnostic( &mut self, diagnostic: LlmRequestDiagnostic, ) -> bool

Capture only the observer for this actual provider call; existing final Session persistence carries it without a second store or background job.

Source

pub fn last_run_diagnostic(&self) -> Option<LlmRequestDiagnostic>

Public/cold-read projection requires the same Session, run and exact canonical error. Old, foreign, malformed or overwritten evidence is absent.

Source§

impl Session

Source

pub fn supervisor_incarnation_id(&self) -> Option<Uuid>

Identity shape observed from an executing snapshot, never a live grant. Every management operation must still revalidate canonical storage.

Source§

impl Session

Source

pub fn independent_root_spawn_contract(&self) -> bool

Historical v2 stamp used to assess retained operation ambiguity and snapshot compatibility. Fresh tool routing is independent of this flag.

Source

pub fn observe_main_session_version(&mut self, main_version: Option<u32>)

Called only by the storage overlay: Main owns the behavior stamp, while a conflicting runtime observation must remain visible to execution. Absence and v1 have the same existing semantics, so that pair is safe.

Source

pub fn execution_compatibility(&self) -> SessionCompatibilityReport

Source

pub fn check_execution_compatibility( &self, ) -> Result<(), SessionCompatibilityError>

Source§

impl Session

Source

pub fn conversation_generation_observation( &self, ) -> ConversationGenerationObservation

Capture data only; final use validates canonical state and authority.

Source

pub fn conversation_revision(&self) -> u64

Observation only, never an authority grant. Invalid ledgers are rejected by validate_conversation_state and final canonical writer checks.

Source

pub fn validate_conversation_state( &self, ) -> Result<(), ConversationGenerationError>

Source

pub fn check_conversation_generation( &self, canonical: &Session, ) -> Result<(), ConversationGenerationError>

Preserve the exact canonical ledger, including receipts at the same revision. A copied revision number alone cannot authorize stale context. Original zero/zero Sessions retain their existing lifetime validation at their own caller/storage boundary; this method adds no new zero-state rebind or identity semantics.

Source

pub fn conversation_reset_sha256( &self, ) -> Result<Option<String>, ConversationGenerationError>

Bounded proof projection of the complete canonical ledger. The inline state stays authoritative; a hash alone is not a replacement ledger.

Source§

impl Session

Source§

impl Session

Source

pub fn root_mode_birth_token(&self) -> String

Opaque lifetime token, so a deleted Root ID cannot reuse an old CAS.

Source

pub fn root_mode_operation( &self, operation_id: &str, ) -> Option<&RootModeOperationReceipt>

Source

pub fn record_root_mode_operation( &mut self, receipt: RootModeOperationReceipt, ) -> Result<(), RootToolAuthorityError>

Source§

impl Session

Source

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

Source

pub fn set_subagent_type(&mut self, value: impl Into<String>)

Source

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

Source

pub fn set_last_run_status(&mut self, value: impl Into<String>)

Source

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

Source

pub fn set_last_run_error(&mut self, value: impl Into<String>)

Source

pub fn clear_last_run_error(&mut self)

Source

pub fn child_launch_generation(&self) -> u64

The queued launch identity is durable on the logical Child session, independent of a process-local runner or scheduler entry.

Source

pub fn advance_child_launch_generation(&mut self) -> Option<u64>

Source

pub fn is_child_launch_cancelled(&self, generation: u64) -> bool

Source

pub fn cancel_child_launch_generation(&mut self)

Source

pub fn mark_child_auto_run_launch_intent(&mut self)

Explicitly promise to launch the current Child generation. A draft never acquires this marker merely by being pending.

Source

pub fn recoverable_child_launch_generation(&self) -> Option<u64>

Reconciliation is deliberately narrower than a pending status: an old intent cannot borrow a later draft/retry generation.

Source

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

Source

pub fn set_provider_name(&mut self, value: impl Into<String>)

Source

pub fn pending_injected_messages(&self) -> Option<Vec<Value>>

Read the pending injected messages, decoding the legacy JSON-string form defensively. Malformed legacy JSON yields None (never a panic).

Source

pub fn set_pending_injected_messages(&mut self, messages: Vec<Value>)

Set pending injected messages on both planes. The legacy mirror stores the JSON-encoded string form to preserve byte-for-byte compatibility.

Source

pub fn has_pending_injected_messages(&self) -> bool

True when there are queued injected messages on either plane.

Source

pub fn take_pending_injected_messages(&mut self) -> Option<Vec<Value>>

Take and clear pending injected messages from both planes.

Source

pub fn clear_pending_injected_messages(&mut self)

Source

pub fn session_inbox_admission(&self) -> Option<&SessionInboxAdmissionState>

Source

pub fn session_inbox_admission_mut(&mut self) -> &mut SessionInboxAdmissionState

Source

pub fn selected_skill_ids(&self) -> Option<Vec<String>>

Read selected skill ids. The typed field is preferred; the legacy fallback parses the stored JSON-array string defensively (malformed → None).

Source

pub fn set_selected_skill_ids(&mut self, ids: Vec<String>)

Set selected skill ids on both planes. The legacy mirror stores the JSON-array string form.

Source

pub fn clear_selected_skill_ids(&mut self)

Source

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

Read the skill mode. Resolution order: typed field, then legacy skill_mode key, then the historical mode key. When both legacy keys are present and disagree, a warning is logged and skill_mode wins.

Source

pub fn set_skill_mode(&mut self, value: impl Into<String>)

Set the skill mode. Writes the typed field and the canonical skill_mode legacy key (the legacy mode key is never written).

Source

pub fn clear_skill_mode(&mut self)

Source

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

Source

pub fn set_reasoning_effort_meta(&mut self, value: impl Into<String>)

Source

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

Source

pub fn set_enhance_prompt(&mut self, value: impl Into<String>)

Source

pub fn clear_enhance_prompt(&mut self)

Source

pub fn root_orchestration_prompt_enabled(&self) -> bool

Host-selected delegation guidance is scoped to a genuine root Session. An imported or malformed child cannot acquire it from inherited metadata.

Source

pub fn set_root_orchestration_prompt_enabled(&mut self, enabled: bool)

An explicit false clears the selection while preserving the default serialization of ordinary roots. Omitted chat values leave it untouched.

Source

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

Source

pub fn set_task_list_version_meta(&mut self, value: impl Into<String>)

Source

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

Source

pub fn set_todo_list_version_meta(&mut self, value: impl Into<String>)

Source

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

Source

pub fn set_workspace_path_meta(&mut self, value: impl Into<String>)

Source

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

Read the stable Project identity, preferring typed runtime metadata and falling back to the legacy metadata string during migration.

Source

pub fn set_project_id_meta(&mut self, value: impl Into<String>)

Persist Project identity on both planes while legacy raw-map readers remain in the tree.

Source

pub fn clear_project_id_meta(&mut self)

Source§

impl Session

Source

pub fn supervisor_orchestration_revision(&self) -> Option<u64>

A trusted Supervisor’s delegation-only business authority is independent of thinking mode. Callers still need Storage’s canonical identity proof. Thinking-mode counters are not business permission epochs. Existing positive Work binding revisions remain in their canonical Ticket store; the Host verifies their unchanged Supervisor namespace separately.

Source

pub fn root_thinking_mode(&self) -> RootThinkingMode

Source

pub fn root_orchestration_only_enabled(&self) -> bool

Source

pub fn set_root_orchestration_only( &mut self, enabled: bool, ) -> Result<(), RootToolAuthorityError>

Called only by a host-owned selection, never by a model tool.

Source

pub fn validate_root_orchestration_compatibility( &self, ) -> Result<(), RootToolAuthorityError>

Keep the narrow tool catalog usable when an old turn or a new request carries a mode that requires tools outside the Root allowlist.

Source

pub fn model_orchestration_only_enabled(&self) -> bool

Derived model posture, not a persisted selection or permission grant. A trusted Supervisor orchestrates in both thinking modes. Children and ordinary Roots retain their own independent mode and permissions.

Source

pub fn allows_model_tool_execution(&self, execution_name: &str) -> bool

Defense in depth at both catalog projection and final dispatch.

Source

pub fn adopt_root_tool_authority_from( &mut self, latest: &Session, ) -> Result<(), RootToolAuthorityError>

Refresh a running snapshot from the durable control plane before tool dispatch. An older snapshot can never loosen a selected Root policy.

Source§

impl Session

Source

pub fn clear_stale_root_token_budget(&mut self)

Load-boundary migration: a persisted Root session’s token_budget can only be a stale pre-#180 resolved-budget cache — genuine budgets flow through config.token_budget, and only a Child persists an assigned sub-budget. Clear it so resolve_token_budget re-resolves from the current model_limits.json instead of short-circuiting on the stale value forever.

MUST be called only on freshly disk-loaded sessions — never inside resolve_token_budget, which can’t tell a stale disk cache from a legitimate in-memory budget injection (tests, child sub-budgets). (#230)

Source

pub fn effective_token_budget(&self) -> Option<&TokenBudget>

The effective token budget: a genuine/child override (token_budget) if set, otherwise the current round’s resolved-budget snapshot (resolved_token_budget). Both are None until the first resolution. Downstream readers should use this rather than token_budget directly so they observe the engine-resolved budget without persisting it. Note the snapshot is returned regardless of which model it was resolved for; that is safe because resolve_token_budget runs at round start (re-keying to the current model) before any reader — don’t call this expecting model-freshness without a preceding same-round resolve. (#180)

Source

pub fn new(id: impl Into<String>, model: impl Into<String>) -> Session

Source

pub fn new_child( id: impl Into<String>, root_session_id: impl Into<String>, model: impl Into<String>, title: impl Into<String>, ) -> Session

Create a child session directly under root_session_id — a flat, depth-1 child of the root. Use Session::new_child_of when the parent may itself be a child (nested sub-agents).

Source

pub fn new_child_of( id: impl Into<String>, parent: &Session, model: impl Into<String>, title: impl Into<String>, ) -> Session

Create a child session whose parent is parent, supporting arbitrary nesting depth. The child inherits the parent’s tree root and sits one level deeper, so completion/SSE bookkeeping (which keys on root_session_id) sees the whole tree regardless of depth.

Source

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

Source

pub fn compact_oversized_tool_messages(&mut self) -> usize

Source

pub fn clear_derived_context_state(&mut self)

Clear all ephemeral/derived state that should not persist across turns.

Resets token usage, compression state, previous response metadata, and message compression flags. Typically called before a truncation or when refreshing session state for a new execution.

Source

pub fn reset_model_context_epoch(&mut self, reason: ModelContextResetReason)

Mark a deliberate model-history rewrite. The next engine reconciliation coalesces current host state into this new epoch before dispatch.

Source

pub fn reset_provider_transcript_for_model_context( &mut self, reason: ModelContextResetReason, )

Apply a model-context boundary to the provider-native replay lane. Engine reconciliation uses this when it discovers an implicit boundary; callers that already declared a full model-context reset use Self::reset_model_context_epoch so both lanes move atomically.

Source

pub fn set_task_list(&mut self, task_list: TaskList)

Source

pub fn update_task_item( &mut self, item_id: &str, status: TaskItemStatus, notes: Option<&str>, criteria_met: Option<&[String]>, ) -> Result<String, String>

Source

pub fn format_task_list_for_prompt(&self) -> String

Source

pub fn set_pending_question( &mut self, tool_call_id: String, tool_name: String, question: String, options: Vec<String>, allow_custom: bool, )

Source

pub fn set_pending_question_with_source( &mut self, tool_call_id: String, tool_name: String, question: String, options: Vec<String>, allow_custom: bool, source: PendingQuestionSource, )

Source

pub fn clear_pending_question(&mut self)

Source

pub fn has_pending_question(&self) -> bool

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<(), Error>

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

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

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<Session, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

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

impl Serialize for Session

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::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> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
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> 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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. 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, 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