Skip to main content

Agent

Struct Agent 

pub struct Agent { /* private fields */ }

Implementations§

Source§

impl Agent

Source

pub fn builder() -> AgentBuilder

Source

pub fn set_channel_name(&mut self, name: String)

Source

pub fn set_interaction_context( &mut self, interaction: Option<InteractionContext>, )

Set the host-resolved, descriptive interaction context for this live session. This does not alter tools, policy, routing, memory, or storage.

Source

pub fn history(&self) -> &[ConversationMessage]

Source

pub fn strip_trailing_interruption_marker(&mut self) -> bool

Remove the trailing assistant interruption marker (turn-interrupted-by-user) the tool loop appends to live history when a turn is cancelled, returning whether one was removed. When cancellation folds the marker into a partial assistant response, preserve the partial response and remove only the runtime-owned marker suffix.

External surfaces that project cancellation differently on their durable transcript (the ACP channel records a structured, replay-only cancellation event instead) call this so the generic marker is not re-sent to the provider on the next turn of the same still-active session. The marker string stays owned by the runtime here rather than being re-derived and content-matched at the call site.

Source

pub fn degrade_trailing_turn_media(&mut self) -> usize

Degrade image references in the trailing turn of live history.

A turn that just ended in a non-retryable failure is the newest whole turn: its opening user prompt is the last turn-opening user message and nothing was appended after the failure. Prompt-mode [Tool results] carriers inside the turn are not turn openings, so the span reaches back past them to the prompt that actually opened the turn. Any attachment in that span was already rejected (or already defeated the request), so leaving it in place resends it on the next prompt of the same still-active session and reproduces the failure. The span is projected in place with the shared failed-turn media degradation (see media_degrade::degrade_media_in_messages); the durable transcript keeps the original content for client replay.

Returns the number of image references degraded.

Source

pub fn replace_history_suffix( &mut self, expected_suffix: &[ConversationMessage], replacement: Vec<ConversationMessage>, ) -> bool

Replace one completed turn only after confirming that the live history still ends with the exact messages the turn committed. A mismatch is a fail-closed signal: callers must discard this Agent rather than mixing generations in its provider history.

Source

pub fn channel_handles(&self) -> &AgentChannelHandles

Source

pub fn populate_channels( &self, channel_map: &HashMap<String, Arc<dyn Channel>>, ) -> Vec<String>

Source

pub fn attribution_fields(&self) -> (String, String, String)

Attribution fields for opening a turn span at external call sites (ACP, gateway WS) so every record inside a streamed turn carries the same agent_alias/model_provider/model the RPC dispatch path sets. Returns (agent_alias, model_provider, model).

Source

pub fn context_limits(&self) -> ResolvedContextLimits

Capacity and proactive-trim budget for the currently selected route. This is resolved on demand so a model/provider switch cannot leave a stale snapshot in a long-lived session.

Source

pub fn context_generation_limits_resolver( generation: Arc<RwLock<RawRwLock, Arc<Config>>>, agent_alias: String, ) -> impl Fn(&str, &str) + Send + Sync + 'static

Build a limits resolver bound to a config generation CELL. Kept next to sync_config_generation because the two form the single-generation contract: this resolver reports capacity/budget from whatever generation that function last published, which is the same generation try_apply_model_switch rebuilds the provider and route resolver from.

Source

pub fn sync_config_generation(&mut self)

Republish the agent’s config generation from its acknowledged live model config source, when one exists.

Called at a turn boundary, before any route is resolved. Provider rebuilding (try_apply_model_switch, via provider_switch_config) and limit resolution (context_limits_for_route, via config_generation) then read one identical Arc<Config>, so dispatch, route identity, and reported limits cannot straddle a mid-session config/set. Within a turn the generation is stable. Direct ACP/WS agents intentionally have no live model source here: they remain wholly on their construction generation until reconnect instead of partially adopting a reload.

Source

pub fn context_limits_for_route( &self, provider_name: &str, model: &str, ) -> ResolvedContextLimits

Resolve capacity and proactive budget for a route selected for the current turn, including values supplied by a live-config resolver.

Source

pub fn clear_history(&mut self)

Source

pub fn set_history_has_trim_breadcrumb(&mut self, flag: bool)

Source

pub fn history_has_trim_breadcrumb(&self) -> bool

Source

pub fn history_trim_generation(&self) -> u64

Source

pub fn set_memory_session_id(&mut self, session_id: Option<String>)

Source

pub fn set_temperature(&mut self, temperature: Option<f64>)

Source

pub fn refresh_memory_embedder( &self, model_provider: &str, api_key: Option<&str>, model: &str, dimensions: usize, )

Source

pub fn set_model_name(&mut self, model_name: String)

Source

pub fn disable_automatic_model_routing(&mut self)

Mark the current model/provider selection as an explicit runtime choice.

Source

pub fn set_model_provider(&mut self, model_provider: Box<dyn ModelProvider>)

Source

pub fn set_model_provider_name(&mut self, model_provider_name: String)

Source

pub fn set_multimodal_config(&mut self, config: MultimodalConfig)

Refreshes the [multimodal] policy snapshot alongside a live provider swap. The provider boundary carries its own clone of the same policy, so both must move together or the runtime preparation pass and the provider boundary disagree after a refresh.

Source

pub fn set_model_route_resolver( &mut self, model_route_resolver: Arc<ModelRouteResolver>, )

Install the route resolver that belongs to a newly swapped provider. The resolver holds the hint→provider/model route table bound to a specific provider set, so it MUST be replaced together with the provider box (see set_model_provider); otherwise a routed hint resolves through the previous provider’s table while the new provider serves the call.

Source

pub fn set_config_generation(&mut self, config_generation: Arc<Config>)

Publish the config generation a freshly swapped provider box was built from. MUST be called in the same state transition as set_model_provider / set_model_route_resolver (see SessionStore::apply_model_provider): it moves the provider-rebuild snapshot and the limits generation together, so a later explicit model_switch cannot rebuild dispatch from stale profiles and routes while context_limits_for_route reports the new config’s capacity.

Source

pub fn set_tool_dispatcher(&mut self, tool_dispatcher: Box<dyn ToolDispatcher>)

Source

pub fn route_memory_to_principal( &mut self, scope: PrincipalScope, ) -> Result<(), Error>

Pin this session’s memory to its OWNER’s private plane (RFC 7141).

Called once at session construction with the session owner’s scope, never with a later caller’s: an administrator prompting another principal’s session must not re-route that session’s memory. Every memory operation the session’s tools and loop issue afterwards goes to the backend’s principal-scoped forms; a backend without private support fails them closed. The shared operator (no owner) keeps the legacy shared handle. Idempotent: a second call with the same owner is a no-op, and a call with a different owner is refused.

Source

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

The principal whose private plane this session’s memory is pinned to, if any.

Source

pub fn narrow_to_principal_tools(&mut self, allowed: Option<&[String]>)

Apply a current principal tool ceiling to an existing session. This is intentionally narrowing-only: session construction already intersects the principal and agent policies, while a later policy refresh must never let an old static or activated tool survive a removed grant.

Pinned MCP resource content is governed by the same selector: each block was admitted at assembly under its <server>__<uri> name, so a narrowing that no longer names it withdraws the block from every later prompt rather than letting construction-time text outlive its grant.

Source

pub fn seed_history(&mut self, messages: &[ChatMessage])

Source

pub fn seed_history_with_event( &mut self, messages: &[ChatMessage], ) -> Option<TurnEvent>

Hydrate prior chat messages and return a transport event when restoring the history enforces the structured whole-turn limit.

Source

pub fn seed_conversation_history(&mut self, messages: Vec<ConversationMessage>)

Hydrate the agent with a full ConversationMessage history (e.g. restored from an ACP session store). Preserves all variants including AssistantToolCalls and ToolResults — use this for ACP restore; use seed_history for flat channel session hydration.

Source

pub fn seed_conversation_history_with_event( &mut self, messages: Vec<ConversationMessage>, ) -> Option<TurnEvent>

Hydrate structured conversation history and return a transport event when restoring the history enforces the structured whole-turn limit.

Source

pub async fn from_config( config: &Config, agent_alias: &str, ) -> Result<Agent, Error>

Source

pub async fn from_config_with_session_cwd( config: &Config, agent_alias: &str, session_cwd: Option<&Path>, ) -> Result<Agent, Error>

Source

pub async fn from_config_with_session_cwd_and_mcp( config: &Config, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, ) -> Result<Agent, Error>

Source

pub async fn from_config_with_session_cwd_and_mcp_backchannel( config: &Config, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, acp_delivery: bool, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, canvas_store: Option<CanvasStore>, ) -> Result<Agent, Error>

Source

pub async fn from_config_with_session_cwd_and_mcp_backchannel_with_capability( config: &Config, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, acp_delivery: bool, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, canvas_store: Option<CanvasStore>, execution_capability: Option<AgentExecutionCapability>, ) -> Result<Agent, Error>

Source

pub async fn from_config_with_session_cwd_and_mcp_backchannel_and_acp_sessions( config: &Config, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, acp_delivery: bool, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, canvas_store: Option<CanvasStore>, acp_session_store: Arc<AcpSessionStore>, ) -> Result<Agent, Error>

Source

pub async fn from_pinned_live_config_with_session_cwd_and_mcp_backchannel( live_config: LiveConfigHandle, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, acp_delivery: bool, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, canvas_store: Option<CanvasStore>, ) -> Result<Agent, Error>

Build a daemon-backed ACP/WS Agent whose model route generation is pinned until reconnect while independently live tool/history policy continues to follow the shared config.

Source

pub async fn from_live_config_with_session_cwd_and_mcp_backchannel_with_capability( live_config: LiveConfigHandle, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, acp_delivery: bool, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, canvas_store: Option<CanvasStore>, execution_capability: Option<AgentExecutionCapability>, ) -> Result<Agent, Error>

Source

pub async fn from_live_config_with_session_cwd_and_mcp_backchannel( live_config: LiveConfigHandle, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, acp_delivery: bool, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, canvas_store: Option<CanvasStore>, ) -> Result<Agent, Error>

Build a daemon-backed ACP/WS Agent from live tool and history policy while keeping its model route generation pinned until reconnect.

Source

pub async fn from_live_config_with_session_cwd_and_mcp_backchannel_and_acp_sessions( live_config: LiveConfigHandle, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, acp_delivery: bool, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, canvas_store: Option<CanvasStore>, acp_session_store: Arc<AcpSessionStore>, ) -> Result<Agent, Error>

Source

pub async fn from_live_config_with_session_cwd_and_mcp_backchannel_and_acp_sessions_with_capability( live_config: LiveConfigHandle, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, acp_delivery: bool, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, canvas_store: Option<CanvasStore>, acp_session_store: Arc<AcpSessionStore>, execution_capability: Option<AgentExecutionCapability>, ) -> Result<Agent, Error>

Source

pub async fn from_config_with_tui_env( config: &Config, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, tui_env: Option<HashMap<String, String>>, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, ) -> Result<Agent, Error>

Like Self::from_config_with_session_cwd_and_mcp_backchannel but also injects the TUI’s captured shell environment so that tools like ShellTool inherit the user’s real PATH, SSH_AUTH_SOCK, etc. rather than the daemon’s stripped-down process environment.

Source

pub async fn from_config_with_tui_env_with_capability( config: &Config, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, tui_env: Option<HashMap<String, String>>, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, execution_capability: Option<AgentExecutionCapability>, ) -> Result<Agent, Error>

Source

pub async fn from_live_config_with_tui_env( live_config: LiveConfigHandle, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, tui_env: Option<HashMap<String, String>>, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, ) -> Result<Agent, Error>

Build a daemon-backed TUI Agent whose structured-history cap follows the shared config after reloads.

Source

pub async fn from_live_config_with_tui_env_and_principal_tools( live_config: LiveConfigHandle, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, tui_env: Option<HashMap<String, String>>, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, principal_allowed_tools: Option<Vec<String>>, ) -> Result<Agent, Error>

Additive RPC constructor. The shared resolver owns grants; this argument is only the current assembly ceiling, not a long-lived policy snapshot.

Source

pub async fn from_live_config_with_tui_env_with_capability( live_config: LiveConfigHandle, agent_alias: &str, session_cwd: Option<&Path>, initialize_mcp: bool, exclude_memory: bool, tui_env: Option<HashMap<String, String>>, sop_engine: Option<Arc<Mutex<SopEngine>>>, sop_audit: Option<Arc<SopAuditLogger>>, execution_capability: Option<AgentExecutionCapability>, ) -> Result<Agent, Error>

Source

pub async fn turn(&mut self, user_message: &str) -> Result<String, Error>

Source

pub async fn turn_streamed( &mut self, user_message: &str, event_tx: Sender<TurnEvent>, cancel_token: Option<CancellationToken>, ) -> Result<(String, Vec<ConversationMessage>), Error>

Source

pub async fn turn_streamed_with_steering_state( &mut self, user_message: &str, event_tx: Sender<TurnEvent>, cancel_token: Option<CancellationToken>, steering_rx: Option<&mut Receiver<SteeringInput>>, ) -> Result<StreamedTurnSuccess, StreamedTurnError>

Run one streamed turn that can take steering messages mid-turn.

The steering receiver is closed on every exit: success, error, cancellation, a response-cache hit, and the returned future being dropped. The caller usually lends the receiver (&mut) and keeps it alive after the turn, so without the close a late try_send would get Ok and the message would never be read. Closed, the sender sees Closed and can send the text as an ordinary prompt instead.

Source

pub async fn run_single(&mut self, message: &str) -> Result<String, Error>

Source

pub async fn run_interactive(&mut self) -> Result<(), Error>

Trait Implementations§

Source§

impl Drop for Agent

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Agent

§

impl !UnwindSafe for Agent

§

impl Freeze for Agent

§

impl Send for Agent

§

impl Sync for Agent

§

impl Unpin for Agent

§

impl UnsafeUnpin for Agent

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
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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
§

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

§

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

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

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
§

impl<T> PolicyExt for T
where T: ?Sized,

§

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
§

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
§

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, 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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more