Skip to main content

AgentContext

Struct AgentContext 

Source
#[non_exhaustive]
pub struct AgentContext {
Show 13 fields pub llm: Arc<dyn LlmClient>, pub short_term: Arc<dyn ShortTermMemory>, pub long_term: Arc<dyn LongTermMemory>, pub episodic: Arc<dyn EpisodicMemory>, pub pubsub: Arc<dyn Pubsub>, pub kv: Arc<dyn KvStore>, pub request_reply: Arc<dyn RequestReply>, pub jobs: Arc<dyn JobQueue>, pub tools: Arc<dyn ToolInvoker>, pub run_id: RunId, pub cancel: CancellationToken, pub agent_name: String, pub progress: Option<Sender<AgentEvent>>, /* private fields */
}
Expand description

Borrow-free agent execution context. Holds Arc<dyn …> so it can be cloned freely across tokio::spawn boundaries ('static requirement).

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§llm: Arc<dyn LlmClient>

LLM provider.

§short_term: Arc<dyn ShortTermMemory>

Short-term conversation memory.

§long_term: Arc<dyn LongTermMemory>

Long-term semantic memory.

§episodic: Arc<dyn EpisodicMemory>

Episodic event log.

§pubsub: Arc<dyn Pubsub>

Pub/sub bus.

§kv: Arc<dyn KvStore>

KV store.

§request_reply: Arc<dyn RequestReply>

Synchronous request/reply.

§jobs: Arc<dyn JobQueue>

Job queue.

§tools: Arc<dyn ToolInvoker>

Tool dispatcher.

§run_id: RunId

Stable id for this run.

§cancel: CancellationToken

Cooperative cancellation token. Runtime checks between steps.

§agent_name: String

Agent name; recorded in episodic events. Caller must set this before invoking the runtime — typically from Agent::name().

§progress: Option<Sender<AgentEvent>>

Optional fan-out channel for step-level events. When Some, the runtime emits one AgentEvent per LLM call, tool call, and terminal transition. Caller (e.g. MCP HTTP transport) owns the receiver and serialises events to the wire.

Default None — existing single-shot callers see no behaviour change. Best-effort send; dropped receivers are silently ignored.

Implementations§

Source§

impl AgentContext

Source

pub fn builder() -> AgentContextBuilder

Fluent builder. See AgentContextBuilder.

Source

pub fn new( llm: Arc<dyn LlmClient>, short_term: Arc<dyn ShortTermMemory>, long_term: Arc<dyn LongTermMemory>, episodic: Arc<dyn EpisodicMemory>, pubsub: Arc<dyn Pubsub>, kv: Arc<dyn KvStore>, request_reply: Arc<dyn RequestReply>, jobs: Arc<dyn JobQueue>, tools: Arc<dyn ToolInvoker>, run_id: RunId, cancel: CancellationToken, agent_name: impl Into<String>, ) -> Self

Construct an AgentContext with all required fields. progress defaults to None.

Source

pub fn with_llm(self, llm: Arc<dyn LlmClient>) -> Self

Replace the LLM client, returning a new context with all other fields cloned.

Source

pub fn with_tools(self, tools: Arc<dyn ToolInvoker>) -> Self

Replace the tool invoker, returning a new context with all other fields cloned.

Source

pub fn with_episodic(self, episodic: Arc<dyn EpisodicMemory>) -> Self

Replace the episodic store, returning a new context with all other fields preserved (e.g. to inject a per-run scoped or durable backend).

Source

pub fn with_short_term(self, short_term: Arc<dyn ShortTermMemory>) -> Self

Replace the short-term memory store, returning a new context with all other fields preserved (e.g. to inject a thread-isolated backend).

Source

pub fn with_long_term(self, long_term: Arc<dyn LongTermMemory>) -> Self

Replace the long-term memory store, returning a new context with all other fields preserved (e.g. to swap vector backends per tenant).

Source

pub fn with_run_id(self, run_id: RunId) -> Self

Replace the run id, returning a new context with all other fields preserved (e.g. to resume a run or stitch episodes into a known chain).

Source

pub fn with_audit_redactor(self, audit_redactor: Arc<dyn AuditRedactor>) -> Self

Install the audit redactor for PII-flagged tools, returning a new context with all other fields cloned. When unset, dispatch falls back to the fail-closed crate::opaque_digest for flagged tools. Symmetric with AgentContextBuilder::audit_redactor for callers that construct via AgentContext::new.

Source

pub fn with_tenant_label(self, label: String) -> Self

Install the derived non-PII tenant attribution label. When set, the runtime records crate::Episode::RunAttributed alongside crate::Episode::Started at run entry. Caller must pre-derive the label (e.g. via crate::principal_hash); raw principals must never reach this surface. The label is audit metadata only and is never appended to short-term memory or LLM-visible messages.

Source

pub fn with_parent_anchor(self, anchor: String) -> Self

Install the cross-hop provenance anchor (the caller’s chain-entry id). When set, the runtime records crate::Episode::RunOrigin alongside crate::Episode::Started at run entry. The value is recorded verbatim, is a caller-asserted unverified claim, and is never appended to short-term memory or LLM-visible messages.

Source

pub async fn publish( &self, subject: &str, payload: Bytes, ) -> Result<(), BusError>

Publish payload on subject, threading this run’s id into the crate::bus::CAUSATION_HEADER so receivers can attribute causation, and record an crate::Episode::BusPublish. The publisher identity is the recording run, so the episode itself needs no extra field.

Each dotted subject segment is validated via crate::bus::validate_subject_token before publishing (CWE-74 subject injection guard); a forbidden segment returns BusError::Invalid and nothing is published. Episode recording is best-effort and logged on failure — the message is already on the wire at that point.

Source

pub async fn record_received(&self, subject: &str, msg: &Msg)

Record receipt of a bus msg on subject: always records a crate::Episode::BusReceive, and additionally records a crate::Episode::BusCausalLink when the message carries a crate::bus::CAUSATION_HEADER identifying the publishing run.

Episode recording is best-effort; failures are logged and not propagated — the message has already been delivered at call time.

Source

pub async fn enqueue(&self, queue: &str, job: Job) -> Result<JobId, BusError>

Enqueue job on queue, stamping this run as the causer (job.causation_run_id) so a worker that claims it can record a causation link via Self::record_claimed. Each dotted queue segment is validated (crate::bus::validate_subject_token, CWE-74).

Source

pub async fn record_claimed(&self, queue: &str, job: &ClaimedJob)

Record receipt of a claimed job from queue: always records a crate::Episode::BusReceive, and additionally records a crate::Episode::BusCausalLink when the job carries a causing run.

Episode recording is best-effort; failures are logged and not propagated — the job has already been claimed at call time.

Source

pub async fn kv_cas_caused_by( &self, bucket: &str, key: &str, value: Bytes, expected: Option<Revision>, ) -> Result<Revision, BusError>

CAS-write value at key in bucket and, on success, stamp this run as the value’s causer (crate::bus::KvStore::put_causer) so a later reader can attribute the write via Self::record_kv_read. A CAS conflict (e.g. dedup redelivery) leaves any existing causer intact — first-writer-wins. The causer write is best-effort (logged, not propagated). Returns the value revision.

Source

pub async fn record_kv_read(&self, bucket: &str, key: &str)

Record reading key from bucket: always a crate::Episode::BusReceive, plus a crate::Episode::BusCausalLink to the run that wrote the value when one was stamped (via Self::kv_cas_caused_by). Best-effort; failures are logged, not propagated.

Source

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

Read the derived non-PII tenant attribution label installed via Self::with_tenant_label or AgentContextBuilder::tenant_label. Returns None when the context has not been bound to a verified caller (e.g. an in-process supervisor run that elides the inbound-MCP tenant-binding hop). External crates use this to route per-tenant budget governance without touching the pub(crate) field directly.

Source

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

Spawn a child context for a sub-run. Clones every Arc<dyn …> handle, mints a fresh RunId, sets agent_name, and inherits the parent’s cancellation token (cancelling the parent cancels the child, but the child can also be cancelled independently).

Used by composite agents (klieo-flows’s SequentialAgent, ParallelAgent, etc.) to build per-leg contexts without manual struct-spread boilerplate.

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

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