Skip to main content

AgentContext

Struct AgentContext 

Source
pub struct AgentContext {
Show 30 fields pub agent_id: AgentId, pub run_id: Option<RunId>, pub session_id: Option<SessionId>, pub parent_run_id: Option<RunId>, pub parent_task_id: Option<TaskId>, pub conversation_id: ConversationId, pub message_history: Vec<ModelMessage>, pub pending_tool_returns: Vec<ToolReturnPart>, pub subagent_history: BTreeMap<String, Vec<ModelMessage>>, pub user_prompts: Option<Vec<ContentPart>>, pub previous_assistant_response_reference: Option<String>, pub steering_messages: Vec<String>, pub handoff_message: Option<String>, pub runtime: RuntimeEphemeralState, pub tools: AgentToolState, pub agent_registry: BTreeMap<String, AgentInfo>, pub usage: Usage, pub usage_snapshot_entries: BTreeMap<String, UsageSnapshotEntry>, pub model_config: ModelConfig, pub tool_config: ToolConfig, pub security: SecurityConfig, pub started_at: DateTime<Utc>, pub ended_at: Option<DateTime<Utc>>, pub state: StateStore, pub events: EventBus, pub notes: NoteStore, pub messages: MessageBus, pub trace_context: TraceContext, pub metadata: Metadata, pub dependencies: DependencyStore,
}
Expand description

Lifecycle-wide agent context.

Fields§

§agent_id: AgentId

Agent identifier.

§run_id: Option<RunId>

Current run identifier.

§session_id: Option<SessionId>

Stable logical session affinity identifier.

§parent_run_id: Option<RunId>

Parent run identifier if this context belongs to a delegated child run.

§parent_task_id: Option<TaskId>

Parent-scoped delegated task identifier if this context executes a lightweight task.

§conversation_id: ConversationId

Conversation identifier.

§message_history: Vec<ModelMessage>

Canonical message history.

§pending_tool_returns: Vec<ToolReturnPart>

Tool returns to inject at the start of the next run.

§subagent_history: BTreeMap<String, Vec<ModelMessage>>

Subagent message history keyed by agent id.

§user_prompts: Option<Vec<ContentPart>>

User prompt content collected for the current run.

§previous_assistant_response_reference: Option<String>

Visible assistant response immediately before the current user prompt.

§steering_messages: Vec<String>

Accumulated user steering messages for compact restore.

§handoff_message: Option<String>

Rendered handoff message for post-compact or post-handoff restore.

§runtime: RuntimeEphemeralState

Runtime-only state, flattened to preserve the established serialized context shape.

§tools: AgentToolState

Agent-owned durable state used by tool bundles.

§agent_registry: BTreeMap<String, AgentInfo>

Agent registry keyed by agent id.

§usage: Usage

Accumulated usage.

§usage_snapshot_entries: BTreeMap<String, UsageSnapshotEntry>

Per-run cumulative usage ledger entries keyed by stable source id.

§model_config: ModelConfig

Model/runtime configuration used for injected runtime context and tool policies.

§tool_config: ToolConfig

Tool-level configuration used by first-party and host tools.

§security: SecurityConfig

Security-related runtime configuration.

§started_at: DateTime<Utc>

Context creation/entry time used for elapsed runtime context.

§ended_at: Option<DateTime<Utc>>

Context exit time.

§state: StateStore

State store.

§events: EventBus

Event bus.

§notes: NoteStore

Persisted notes.

§messages: MessageBus

Message bus.

§trace_context: TraceContext

Trace correlation context.

§metadata: Metadata

Context metadata.

§dependencies: DependencyStore

Typed dependencies, skipped from serialization.

Implementations§

Source§

impl AgentContext

Source

pub fn new(agent_id: AgentId) -> Self

Create a fresh context.

Source

pub fn from_state(state: ResumableState) -> Self

Restore a context from serialized state.

Source

pub fn export_state(&self) -> ResumableState

Export curated portable context state for session restoration.

Source

pub fn export_full_state(&self) -> ResumableState

Export full Starweaver runtime context state.

Source

pub fn run_attachments(&self) -> RunAttachments

Return JSON-compatible run attachments for this context.

This is a typed view over context metadata. Generic SDK code keeps these attachments local to Starweaver execution and does not forward them to provider HTTP headers or provider-specific request fields.

Source

pub const fn run_attachment_values(&self) -> &Metadata

Return the underlying JSON-compatible run attachment values.

Source

pub const fn run_attachment_values_mut(&mut self) -> &mut Metadata

Return mutable underlying JSON-compatible run attachment values.

Source

pub fn set_run_attachment( &mut self, key: impl Into<String>, value: Value, ) -> Option<Value>

Insert or replace one run attachment value.

Source

pub fn merge_run_attachments(&mut self, attachments: impl Into<Metadata>)

Merge run attachments into the context. Incoming keys replace existing values.

Source

pub fn export_state_with_options( &self, options: ResumableExportOptions, ) -> ResumableState

Export context state with explicit export options.

Source

pub fn restore_state(&mut self, state: ResumableState)

Replace context with serialized state.

Source

pub fn set_session_id(&mut self, session_id: SessionId)

Set the stable logical session affinity identifier.

Source

pub const fn session_id(&self) -> Option<&SessionId>

Return the stable logical session affinity identifier.

Source

pub fn prepare_new_run(&mut self)

Prepare context for a new run.

Source

pub fn finish_run(&mut self)

Mark the active run as finished.

Source

pub fn subagent_context(&self, agent_id: impl Into<String>) -> Self

Create a child context for subagent execution using the same value for id and name.

Source

pub fn subagent_context_with_agent_id( &self, agent_name: impl Into<String>, agent_id: impl Into<String>, ) -> Self

Create a child context for subagent execution with separate display name and stable id.

Source

pub fn absorb_subagent_context(&mut self, child: &Self)

Absorb child context state that should survive successful subagent execution.

Source

pub fn with_trace_context(self, trace_context: TraceContext) -> Self

Attach trace correlation context.

Source

pub fn set_trace_context(&mut self, trace_context: TraceContext)

Replace trace correlation context.

Source

pub fn record_tool_search_loaded_tool(&mut self, tool_name: impl Into<String>)

Record a tool name loaded through dynamic tool search.

Source

pub fn record_tool_search_loaded_namespace( &mut self, namespace: impl Into<String>, )

Record a namespace loaded through dynamic tool search.

Source

pub fn record_tool_search_loaded( &mut self, tools: impl IntoIterator<Item = impl Into<String>>, namespaces: impl IntoIterator<Item = impl Into<String>>, )

Record loaded tool-search state in one update.

Source

pub fn clear_tool_search_loaded(&mut self) -> ToolSearchInvalidation

Clear all loaded tool-search state and return the removed values.

Source

pub fn retain_tool_search_loaded( &mut self, keep_tool: impl FnMut(&str) -> bool, keep_namespace: impl FnMut(&str) -> bool, ) -> ToolSearchInvalidation

Retain only loaded tool-search entries accepted by the supplied predicates.

Source

pub fn tool_search_state(&self) -> ToolSearchState

Return the current tool-search state snapshot.

Source

pub fn push_message(&mut self, message: ModelMessage)

Record a model message in context history.

Source

pub const fn add_usage(&mut self, usage: &Usage)

Record usage in the context ledger.

Source

pub fn update_usage_snapshot_entry( &mut self, agent_id: impl Into<String>, agent_name: impl Into<String>, model_id: impl Into<String>, usage: Usage, estimate_pricing: Option<PricingEstimate>, usage_id: Option<String>, source: impl Into<String>, ledger_key: Option<String>, ) -> UsageSnapshot

Update one cumulative usage snapshot ledger entry and return the latest run snapshot.

Source

pub fn update_external_usage_snapshot_entry( &mut self, source_id: impl Into<String>, source_name: impl Into<String>, model_id: impl Into<String>, usage: Usage, estimate_pricing: Option<PricingEstimate>, usage_id: Option<String>, ) -> UsageSnapshot

Update one cumulative external usage ledger entry.

This helper is for host services, sub-systems, and adapters that need to include non-model usage in the run snapshot without pretending the usage came from the active model request.

Source

pub fn build_usage_snapshot(&self) -> UsageSnapshot

Build a cumulative usage snapshot for this run.

Source

pub fn latest_request_usage(&self) -> Option<&Usage>

Return the latest model request usage reported by the provider.

Source

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

Return the latest model request token usage reported by the provider.

Source

pub fn repair_dangling_tool_calls(&mut self, reason: impl Into<String>) -> usize

Append synthetic error tool returns for any unclosed tool calls in message history.

This is used when a run fails or is interrupted after a provider has emitted tool calls but before every tool return has been recorded. It keeps recovered history acceptable to providers that require every tool call to be closed by a matching tool return.

Source

pub fn publish_event(&mut self, event: AgentEvent)

Publish an event.

Source

pub fn tasks(&self) -> Vec<Task>

Return all tasks from the typed task manager.

Source

pub fn set_tasks(&mut self, tasks: Vec<Task>)

Replace all tasks in the typed task manager.

Source

pub fn task_snapshot(&self) -> TaskSnapshot

Return a full task snapshot.

Source

pub fn publish_task_snapshot_event(&mut self)

Publish a full task snapshot event.

Source

pub fn enqueue_message(&mut self, message: BusMessage)

Enqueue a message.

Source

pub fn send_message(&mut self, message: BusMessage) -> BusMessage

Send a bus message idempotently.

Source

pub fn consume_messages(&mut self) -> Vec<BusMessage>

Consume unread bus messages for this context agent.

Source

pub fn consume_messages_for(&mut self, agent_id: &str) -> Vec<BusMessage>

Consume unread bus messages for a specific agent id.

Source

pub fn consume_messages_matching( &mut self, predicate: impl Fn(&BusMessage) -> bool, ) -> Vec<BusMessage>

Consume unread bus messages matching a predicate for this context agent.

Source

pub fn subscribe_messages(&mut self)

Subscribe the current agent to the message bus.

Source

pub fn get_wrapper_metadata(&self) -> Metadata

Return wrapper metadata with built-in context fields and user overrides.

Source

pub fn tool_dependency_store(&self) -> DependencyStore

Build the typed dependency store supplied to one tool call.

Host capability handles are cloned from the context dependency store, while model/tool limits and shell environment values are exposed through a narrow, immutable snapshot instead of cloning the complete AgentContext.

Source

pub fn filtered_tool_dependency_store( &self, host_capability_names: &BTreeSet<String>, shell_environment: bool, ) -> DependencyStore

Build an opt-in filtered dependency store for one tool call.

Direct application dependencies remain available for compatibility. Generated host capabilities are filtered, the generated runtime snapshot omits shell values, and the runtime-generated broad context handle is assembled by the caller rather than here.

Source

pub fn strict_tool_dependency_store( &self, host_capability_names: &BTreeSet<String>, shell_environment: bool, ) -> DependencyStore

Build a strict least-authority dependency store for one tool call.

Unlike the compatibility-oriented filtered profile, application dependencies are not copied directly. The tool can reach only the named host capability subset and generated immutable projections explicitly requested in its metadata.

Source

pub fn host_capabilities(&self) -> HostCapabilities

Capture the read-only host capabilities supplied to tool calls.

Source

pub fn host_capabilities_subset( &self, names: &BTreeSet<String>, ) -> HostCapabilities

Capture a filtered read-only host capability subset.

Source

pub fn tool_runtime_snapshot(&self) -> ToolRuntimeSnapshot

Capture the read-only runtime configuration supplied to tool calls.

Source

pub fn filtered_tool_runtime_snapshot(&self) -> ToolRuntimeSnapshot

Capture runtime configuration without configured shell environment values.

Source

pub fn shell_environment_snapshot(&self) -> ShellEnvironmentSnapshot

Capture configured shell environment values in a dedicated projection.

Source

pub fn insert_dependency<T>(&mut self, value: T)
where T: Send + Sync + 'static,

Insert a typed dependency.

Source

pub fn insert_named_dependency<T>(&mut self, name: impl Into<String>, value: T)
where T: Send + Sync + 'static,

Insert a named typed dependency.

Source

pub fn grant_tool_capabilities( &mut self, tool_name: impl Into<String>, grant: ToolCapabilityGrant, )

Authorize dependency grants for one Strict tool name.

Source

pub fn tool_capability_grant(&self, tool_name: &str) -> ToolCapabilityGrant

Return host-authorized dependency grants for one Strict tool name.

Source

pub fn dependency<T>(&self) -> Option<Arc<T>>
where T: Send + Sync + 'static,

Get a typed dependency.

Source

pub fn named_dependency<T>(&self, name: &str) -> Option<Arc<T>>
where T: Send + Sync + 'static,

Get a named typed dependency.

Source

pub const fn set_context_window(&mut self, context_window: Option<u64>)

Set the context window exposed in model-facing runtime context.

Source

pub fn merge_model_config(&mut self, model_config: ModelConfig)

Merge runtime model defaults into this context.

Source

pub fn set_tool_config(&mut self, tool_config: ToolConfig)

Replace the tool config for this context.

Source

pub fn merge_tool_config(&mut self, tool_config: ToolConfig)

Merge runtime tool defaults into this context.

Source

pub fn render_runtime_context(&self, is_user_prompt: bool) -> Option<String>

Render runtime context for model-facing requests.

Trait Implementations§

Source§

impl Clone for AgentContext

Source§

fn clone(&self) -> AgentContext

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 AgentContext

Source§

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

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

impl Default for AgentContext

Source§

fn default() -> Self

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

impl<'de> Deserialize<'de> for AgentContext

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 AgentContext

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