Skip to main content

Agent

Struct Agent 

Source
pub struct Agent<C: Channel> { /* private fields */ }

Implementations§

Source§

impl<C: Channel> Agent<C>

Source

pub fn with_status_tx(self, tx: UnboundedSender<String>) -> Self

Attach a status channel for spinner/status messages sent to TUI or stderr. The sender must be cloned from the provider’s StatusTx before provider.set_status_tx() consumes it.

Source

pub fn with_structured_summaries(self, enabled: bool) -> Self

Source

pub fn with_autosave_config( self, autosave_assistant: bool, min_length: usize, ) -> Self

Source

pub fn with_tool_call_cutoff(self, cutoff: usize) -> Self

Source

pub fn with_shutdown_summary_config( self, enabled: bool, min_messages: usize, max_messages: usize, timeout_secs: u64, ) -> Self

Source

pub fn with_response_cache(self, cache: Arc<ResponseCache>) -> Self

Source

pub fn with_parent_tool_use_id(self, id: impl Into<String>) -> Self

Set the parent tool call ID for subagent sessions.

When set, every LoopbackEvent::ToolStart and LoopbackEvent::ToolOutput emitted by this agent will carry the parent_tool_use_id so the IDE can build a subagent hierarchy tree.

Source

pub fn with_stt(self, stt: Box<dyn SpeechToText>) -> Self

Source

pub fn with_embedding_provider(self, provider: AnyProvider) -> Self

Set the dedicated embedding provider (resolved once at bootstrap, never changed by /provider switch). When not called, defaults to the primary provider clone set in Agent::new.

Source

pub fn with_provider_pool( self, pool: Vec<ProviderEntry>, snapshot: ProviderConfigSnapshot, ) -> Self

Store the provider pool and config snapshot for runtime /provider switching.

Source

pub fn with_debug_dumper(self, dumper: DebugDumper) -> Self

Enable debug dump mode, writing LLM requests/responses and raw tool output to dumper.

Source

pub fn with_trace_collector(self, collector: TracingCollector) -> Self

Enable OTel trace collection. The collector writes trace.json at session end.

Source

pub fn with_trace_config( self, dump_dir: PathBuf, service_name: impl Into<String>, redact: bool, ) -> Self

Store trace config so /dump-format trace can create a TracingCollector at runtime (CR-04).

Source

pub fn with_update_notifications(self, rx: Receiver<String>) -> Self

Source

pub fn with_custom_task_rx(self, rx: Receiver<String>) -> Self

Source

pub fn add_tool_executor(self, extra: impl ToolExecutor + 'static) -> Self

Wrap the current tool executor with an additional executor via CompositeExecutor.

Source

pub fn with_max_tool_iterations(self, max: usize) -> Self

Source

pub fn with_max_tool_retries(self, max: usize) -> Self

Set the maximum number of retry attempts for transient tool errors (0 = disabled, max 5).

Source

pub fn with_max_retry_duration_secs(self, secs: u64) -> Self

Set the maximum wall-clock budget (seconds) for retries per tool call (0 = unlimited).

Source

pub fn with_parameter_reformat_provider( self, provider: impl Into<String>, ) -> Self

Set the provider name for LLM-based parameter reformatting (empty = disabled).

Source

pub fn with_retry_backoff(self, base_ms: u64, max_ms: u64) -> Self

Set the exponential backoff parameters for tool retries.

Source

pub fn with_tool_repeat_threshold(self, threshold: usize) -> Self

Set the repeat-detection threshold (0 = disabled). Window size is 2 * threshold.

Source

pub fn with_memory( self, memory: Arc<SemanticMemory>, conversation_id: ConversationId, history_limit: u32, recall_limit: usize, summarization_threshold: usize, ) -> Self

Source

pub fn with_embedding_model(self, model: String) -> Self

Source

pub fn with_disambiguation_threshold(self, threshold: f32) -> Self

Source

pub fn with_two_stage_matching(self, enabled: bool) -> Self

Source

pub fn with_confusability_threshold(self, threshold: f32) -> Self

Source

pub fn with_skill_prompt_mode(self, mode: SkillPromptMode) -> Self

Source

pub fn with_document_config(self, config: DocumentConfig) -> Self

Source

pub fn with_compression_guidelines_config( self, config: CompressionGuidelinesConfig, ) -> Self

Source

pub fn with_digest_config(self, config: DigestConfig) -> Self

Source

pub fn with_context_strategy( self, strategy: ContextStrategy, crossover_turn_threshold: u32, ) -> Self

Source

pub fn with_graph_config(self, config: GraphConfig) -> Self

Source

pub fn with_anomaly_detector(self, detector: AnomalyDetector) -> Self

Source

pub fn with_instruction_blocks(self, blocks: Vec<InstructionBlock>) -> Self

Source

pub fn with_instruction_reload( self, rx: Receiver<InstructionEvent>, state: InstructionReloadState, ) -> Self

Source

pub fn with_shutdown(self, rx: Receiver<bool>) -> Self

Source

pub fn with_skill_reload( self, paths: Vec<PathBuf>, rx: Receiver<SkillEvent>, ) -> Self

Source

pub fn with_managed_skills_dir(self, dir: PathBuf) -> Self

Source

pub fn with_trust_config(self, config: TrustConfig) -> Self

Source

pub fn with_config_reload( self, path: PathBuf, rx: Receiver<ConfigEvent>, ) -> Self

Source

pub fn with_logging_config(self, logging: LoggingConfig) -> Self

Source

pub fn with_available_secrets( self, secrets: impl IntoIterator<Item = (String, Secret)>, ) -> Self

§Panics

Panics if the registry RwLock is poisoned.

Source

pub fn with_learning(self, config: LearningConfig) -> Self

Source

pub fn with_llm_classifier(self, classifier: LlmClassifier) -> Self

Attach an LlmClassifier for detector_mode = "model" feedback detection.

When attached, the model-based path is used instead of JudgeDetector. The classifier resolves the provider at construction time — if the provider is unavailable, do not call this method (fallback to regex-only).

Source

pub fn with_judge_provider(self, provider: AnyProvider) -> Self

Source

pub fn with_probe_provider(self, provider: AnyProvider) -> Self

Source

pub fn with_planner_provider(self, provider: AnyProvider) -> Self

Source

pub fn with_verify_provider(self, provider: AnyProvider) -> Self

Set a dedicated provider for PlanVerifier LLM calls.

When not set, verification falls back to the primary provider.

Source

pub fn with_server_compaction(self, enabled: bool) -> Self

Enable server-side compaction mode (Claude compact-2026-01-12 beta).

When active, client-side reactive and proactive compaction are skipped.

Source

pub fn with_mcp( self, tools: Vec<McpTool>, registry: Option<McpToolRegistry>, manager: Option<Arc<McpManager>>, mcp_config: &McpConfig, ) -> Self

Source

pub fn with_mcp_server_outcomes( self, outcomes: Vec<ServerConnectOutcome>, ) -> Self

Source

pub fn with_mcp_shared_tools(self, shared: Arc<RwLock<Vec<McpTool>>>) -> Self

Source

pub fn with_mcp_pruning( self, params: PruningParams, enabled: bool, pruning_provider: Option<AnyProvider>, ) -> Self

Configure MCP tool pruning (#2298).

Sets the pruning params derived from ToolPruningConfig and optionally a dedicated provider for pruning LLM calls. pruning_provider = None means fall back to the primary provider.

Source

pub fn with_mcp_discovery( self, strategy: ToolDiscoveryStrategy, params: DiscoveryParams, discovery_provider: Option<AnyProvider>, ) -> Self

Configure embedding-based MCP tool discovery (#2321).

Sets the discovery strategy, parameters, and optionally a dedicated embedding provider. discovery_provider = None means fall back to the agent’s primary embedding provider.

Source

pub fn with_mcp_tool_rx(self, rx: Receiver<Vec<McpTool>>) -> Self

Set the watch receiver for MCP tool list updates from tools/list_changed notifications.

The agent polls this receiver at the start of each turn to pick up refreshed tool lists.

Source

pub fn with_mcp_elicitation_rx(self, rx: Receiver<ElicitationEvent>) -> Self

Set the elicitation receiver for MCP elicitation requests from server handlers.

When set, the agent loop processes elicitation events concurrently with tool result awaiting to prevent deadlock.

Source

pub fn with_security( self, security: SecurityConfig, timeouts: TimeoutConfig, ) -> Self

Source

pub fn with_audit_logger(self, logger: Arc<AuditLogger>) -> Self

Attach an audit logger for pre-execution verifier blocks.

Source

pub fn with_redact_credentials(self, enabled: bool) -> Self

Source

pub fn with_tool_summarization(self, enabled: bool) -> Self

Source

pub fn with_overflow_config(self, config: OverflowConfig) -> Self

Source

pub fn with_tafc_config(self, config: TafcConfig) -> Self

Configure Think-Augmented Function Calling (TAFC).

complexity_threshold is clamped to [0.0, 1.0]; NaN / Inf are reset to 0.6.

Source

pub fn with_result_cache_config(self, config: &ResultCacheConfig) -> Self

Source

pub fn with_summary_provider(self, provider: AnyProvider) -> Self

Source

pub fn with_quarantine_summarizer(self, qs: QuarantinedSummarizer) -> Self

Source

pub fn with_acp_session(self, is_acp: bool) -> Self

Mark this agent session as serving an ACP client. When true and mcp_to_acp_boundary is enabled, MCP tool results receive unconditional quarantine and cross-boundary audit logging.

Source

pub fn with_causal_analyzer(self, analyzer: TurnCausalAnalyzer) -> Self

Attach a temporal causal IPI analyzer.

When Some, the native tool dispatch loop runs pre/post behavioral probes.

Source

pub fn with_permission_policy(self, policy: PermissionPolicy) -> Self

Source

pub fn with_context_budget( self, budget_tokens: usize, reserve_ratio: f32, hard_compaction_threshold: f32, compaction_preserve_tail: usize, prune_protect_tokens: usize, ) -> Self

Source

pub fn with_soft_compaction_threshold(self, threshold: f32) -> Self

Source

pub fn with_compaction_cooldown(self, cooldown_turns: u8) -> Self

Sets the number of turns to skip compaction after a successful compaction.

Prevents the compaction loop from re-triggering immediately when the summary itself is large. A value of 0 disables the cooldown.

Source

pub fn with_compression(self, compression: CompressionConfig) -> Self

Source

pub fn with_focus_config(self, config: FocusConfig) -> Self

Configure Focus-based active context compression (#1850).

Source

pub fn with_sidequest_config(self, config: SidequestConfig) -> Self

Configure SideQuest LLM-driven tool output eviction (#1885).

Source

pub fn with_routing(self, routing: StoreRoutingConfig) -> Self

Source

pub fn with_model_name(self, name: impl Into<String>) -> Self

Source

pub fn with_active_provider_name(self, name: impl Into<String>) -> Self

Set the configured provider name (from [[llm.providers]] name field).

Used by the TUI metrics panel and /provider status to display the logical name instead of the provider type string returned by LlmProvider::name().

Source

pub fn with_working_dir(self, path: impl Into<PathBuf>) -> Self

Source

pub fn with_hooks_config(self, config: &HooksConfig) -> Self

Configure reactive hook events from the [hooks] config section.

Stores hook definitions in SessionState and starts a FileChangeWatcher when file_changed.watch_paths is non-empty. Initializes last_known_cwd from the current process cwd at call time (the project root).

Source

pub fn with_warmup_ready(self, rx: Receiver<bool>) -> Self

Source

pub fn with_cost_tracker(self, tracker: CostTracker) -> Self

Source

pub fn with_extended_context(self, enabled: bool) -> Self

Source

pub fn with_repo_map(self, token_budget: usize, ttl_secs: u64) -> Self

Source

pub fn with_code_retriever(self, retriever: Arc<CodeRetriever>) -> Self

Source

pub fn with_metrics(self, tx: Sender<MetricsSnapshot>) -> Self

§Panics

Panics if the registry RwLock is poisoned.

Source

pub fn cancel_signal(&self) -> Arc<Notify>

Returns a handle that can cancel the current in-flight operation. The returned Notify is stable across messages — callers invoke notify_waiters() to cancel whatever operation is running.

Source

pub fn with_cancel_signal(self, signal: Arc<Notify>) -> Self

Inject a shared cancel signal so an external caller (e.g. ACP session) can interrupt the agent loop by calling notify_one().

Source

pub fn with_subagent_manager(self, manager: SubAgentManager) -> Self

Source

pub fn with_subagent_config(self, config: SubAgentConfig) -> Self

Source

pub fn with_orchestration_config(self, config: OrchestrationConfig) -> Self

Source

pub fn with_provider_override( self, slot: Arc<RwLock<Option<AnyProvider>>>, ) -> Self

Inject a shared provider override slot for runtime model switching (e.g. via ACP set_session_config_option). The agent checks and swaps the provider before each turn.

Source

pub fn with_tool_schema_filter(self, filter: ToolSchemaFilter) -> Self

Set the dynamic tool schema filter (pre-computed tool embeddings).

Source

pub fn with_dependency_config(self, config: DependencyConfig) -> Self

Set dependency config parameters (boost values) used per-turn.

Source

pub fn with_tool_dependency_graph( self, graph: ToolDependencyGraph, always_on: HashSet<String>, ) -> Self

Attach a tool dependency graph for sequential tool availability (issue #2024).

When set, hard gates (requires) are applied after schema filtering, and soft boosts (prefers) are added to similarity scores. Always-on tool IDs bypass hard gates.

Source

pub async fn maybe_init_tool_schema_filter( self, config: &ToolFilterConfig, provider: &AnyProvider, ) -> Self

Initialize and attach the tool schema filter if enabled in config.

Embeds all filterable tool descriptions at startup and caches the embeddings. Gracefully degrades: returns self unchanged if embedding is unsupported or fails.

Source

pub fn apply_session_config(self, cfg: AgentSessionConfig) -> Self

Apply all config-derived settings from AgentSessionConfig in a single call.

Takes cfg by value and destructures it so the compiler emits an unused-variable warning for any field that is added to AgentSessionConfig but not consumed here (S4).

Per-session wiring (cancel_signal, provider_override, memory, debug_dumper, etc.) must still be applied separately after this call, since those depend on runtime state.

Source§

impl<C: Channel> Agent<C>

Source

pub async fn handle_graph_command( &mut self, input: &str, ) -> Result<(), AgentError>

Dispatch /graph [subcommand] slash command.

§Errors

Returns an error if the channel send fails or graph store query fails.

Source§

impl<C: Channel> Agent<C>

Source

pub async fn handle_log_command(&mut self) -> Result<(), AgentError>

Handle the /log slash command: show current log file path and recent entries.

§Errors

Returns an error if the channel send fails.

Source§

impl<C: Channel> Agent<C>

Source

pub async fn init_semantic_index(&mut self)

Build (or rebuild) the in-memory semantic tool index for embedding-based discovery. Build the initial semantic tool index after agent construction.

Must be called once after with_mcp and with_mcp_discovery are applied, before the first user turn. Subsequent rebuilds happen automatically on tool list change events (check_tool_refresh, /mcp add, /mcp remove).

Source§

impl<C: Channel> Agent<C>

Source

pub async fn handle_memory_command( &mut self, input: &str, ) -> Result<(), AgentError>

Dispatch /memory [subcommand] slash command.

§Errors

Returns an error if the channel send fails or database query fails.

Source§

impl<C: Channel> Agent<C>

Source

pub async fn load_history(&mut self) -> Result<(), AgentError>

Load conversation history from memory and inject into messages.

§Errors

Returns an error if loading history from SQLite fails.

Source§

impl<C: Channel> Agent<C>

Source

pub fn sync_community_detection_failures(&self)

Read the community-detection failure counter from SemanticMemory and update metrics.

Source

pub fn sync_graph_extraction_metrics(&self)

Sync all graph counters (extraction count/failures) from SemanticMemory to metrics.

Source

pub async fn sync_graph_counts(&self)

Fetch entity/edge/community counts from the graph store and write to metrics.

Source

pub async fn check_vector_store_health(&self, backend_name: &str)

Perform a real health check on the vector store and update metrics.

Source

pub fn inject_code_context(&mut self, text: &str)

Inject pre-formatted code context into the message list. The caller is responsible for retrieving and formatting the text.

Source

pub fn context_messages(&self) -> &[Message]

Source§

impl<C: Channel> Agent<C>

Source

pub fn new( provider: AnyProvider, channel: C, registry: SkillRegistry, matcher: Option<SkillMatcherBackend>, max_active_skills: usize, tool_executor: impl ToolExecutor + 'static, ) -> Self

Source

pub fn new_with_registry_arc( provider: AnyProvider, channel: C, registry: Arc<RwLock<SkillRegistry>>, matcher: Option<SkillMatcherBackend>, max_active_skills: usize, tool_executor: impl ToolExecutor + 'static, ) -> Self

Create an agent from a pre-wrapped registry Arc, allowing the caller to share the same Arc with other components (e.g. crate::SkillLoaderExecutor).

§Panics

Panics if the registry RwLock is poisoned.

Source

pub async fn poll_subagents(&mut self) -> Vec<(String, String)>

Poll all active sub-agents for completed/failed/canceled results.

Non-blocking: returns immediately with a list of (task_id, result) pairs for agents that have finished. Each completed agent is removed from the manager.

Source

pub async fn shutdown(&mut self)

Source

pub async fn run(&mut self) -> Result<(), AgentError>

Run the agent main loop.

§Errors

Returns an error if the channel, LLM provider, or tool execution encounters a fatal error.

Source

pub fn set_model(&mut self, model_id: &str) -> Result<(), String>

Switch the active provider to one serving model_id.

Looks up the model in the provider’s remote model list (or cache).

§Errors

Returns Err if the model is not found.

Auto Trait Implementations§

§

impl<C> !Freeze for Agent<C>

§

impl<C> !RefUnwindSafe for Agent<C>

§

impl<C> Send for Agent<C>

§

impl<C> Sync for Agent<C>
where C: Sync,

§

impl<C> Unpin for Agent<C>
where C: Unpin,

§

impl<C> UnsafeUnpin for Agent<C>
where C: UnsafeUnpin,

§

impl<C> !UnwindSafe for Agent<C>

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

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
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: 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: 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, 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