pub struct Agent<C: Channel> { /* private fields */ }Expand description
Zeph agent: autonomous AI system with multi-model inference, semantic memory, skills, tool orchestration, and multi-channel I/O.
The agent maintains conversation history, manages LLM provider state, coordinates tool
execution, and orchestrates memory and skill subsystems. It communicates with the outside
world via the Channel trait, enabling support for CLI, Telegram, TUI, or custom I/O.
§Architecture
- Message state: Conversation history with system prompt, message queue, and metadata
- Memory state:
SQLite+ Qdrant vector store for semantic search and compaction - Skill state: Registry, matching engine, and self-learning evolution
- Context manager: Token budgeting, context assembly, and summarization
- Tool orchestrator: DAG-based multi-tool execution with streaming output
- MCP client: Multi-server support for Model Context Protocol
- Index state: AST-based code indexing and semantic retrieval
- Security: Sanitization, exfiltration detection, adversarial probes
- Metrics: Token usage, latency, cost, and anomaly tracking
§Channel Contract
The agent requires a Channel implementation for user interaction:
- Sends agent responses via
channel.send(message) - Receives user input via
channel.recv()/channel.recv_internal() - Supports structured events: tool invocations, tool output, streaming updates
§Lifecycle
- Create with
Self::neworSelf::new_with_registry_arc - Run main loop with
Self::run - Clean up with
Self::shutdownto persist state and close resources
Implementations§
Source§impl<C: Channel> Agent<C>
impl<C: Channel> Agent<C>
Sourcepub fn build(self) -> Result<Self, BuildError>
pub fn build(self) -> Result<Self, BuildError>
Validate the agent configuration and return self if all required fields are present.
Call this as the final step in any agent construction chain to catch misconfiguration
early. Production bootstrap code should propagate the error with ?; test helpers
may use .build().unwrap().
§Errors
Returns [BuildError::MissingProviders] when no provider pool was configured and the
model name has not been set via apply_session_config (the agent cannot make LLM calls).
§Examples
let agent = Agent::new(provider, channel, registry, None, 5, executor)
.apply_session_config(session_cfg)
.build()?;Sourcepub fn with_memory(
self,
memory: Arc<SemanticMemory>,
conversation_id: ConversationId,
history_limit: u32,
recall_limit: usize,
summarization_threshold: usize,
) -> Self
pub fn with_memory( self, memory: Arc<SemanticMemory>, conversation_id: ConversationId, history_limit: u32, recall_limit: usize, summarization_threshold: usize, ) -> Self
Configure the semantic memory store, conversation tracking, and recall parameters.
All five parameters are required together — they form the persistent-memory contract that the context assembly and summarization pipelines depend on.
Sourcepub fn with_autosave_config(
self,
autosave_assistant: bool,
min_length: usize,
) -> Self
pub fn with_autosave_config( self, autosave_assistant: bool, min_length: usize, ) -> Self
Configure autosave behaviour for assistant messages.
Sourcepub fn with_tool_call_cutoff(self, cutoff: usize) -> Self
pub fn with_tool_call_cutoff(self, cutoff: usize) -> Self
Set the maximum number of tool-call messages retained in the context window before older ones are truncated.
Sourcepub fn with_structured_summaries(self, enabled: bool) -> Self
pub fn with_structured_summaries(self, enabled: bool) -> Self
Enable or disable structured (JSON) summarization of conversation history.
Sourcepub fn with_memory_formatting_config(
self,
compression_guidelines: CompressionGuidelinesConfig,
digest: DigestConfig,
context_strategy: ContextStrategy,
crossover_turn_threshold: u32,
) -> Self
pub fn with_memory_formatting_config( self, compression_guidelines: CompressionGuidelinesConfig, digest: DigestConfig, context_strategy: ContextStrategy, crossover_turn_threshold: u32, ) -> Self
Configure memory formatting: compression guidelines, digest, and context strategy.
Sourcepub fn with_document_config(self, config: DocumentConfig) -> Self
pub fn with_document_config(self, config: DocumentConfig) -> Self
Set the document indexing configuration for MagicDocs and RAG.
Sourcepub fn with_trajectory_and_category_config(
self,
trajectory: TrajectoryConfig,
category: CategoryConfig,
) -> Self
pub fn with_trajectory_and_category_config( self, trajectory: TrajectoryConfig, category: CategoryConfig, ) -> Self
Configure trajectory and category memory settings together.
Sourcepub fn with_graph_config(self, config: GraphConfig) -> Self
pub fn with_graph_config(self, config: GraphConfig) -> Self
Configure knowledge-graph extraction and the RPE router.
When config.rpe.enabled is true, an RpeRouter is initialised and stored in the
memory state. Emits a WARN-level log when graph extraction is enabled, because extracted
entities are stored without PII redaction (pre-1.0 MVP limitation — see R-IMP-03).
Sourcepub fn with_tree_consolidation_loop(self, provider: AnyProvider) -> Self
pub fn with_tree_consolidation_loop(self, provider: AnyProvider) -> Self
Start the TiMem tree consolidation background loop and store the handle.
Call after memory and tree configuration have been applied so that both the SQLite
store and config are available. The loop runs until the agent cancel token fires.
The handle is kept in the memory state and is aborted when the agent is dropped.
No-op if tree consolidation is disabled in the config or memory has not been set.
Sourcepub fn with_shutdown_summary_config(
self,
enabled: bool,
min_messages: usize,
max_messages: usize,
timeout_secs: u64,
) -> Self
pub fn with_shutdown_summary_config( self, enabled: bool, min_messages: usize, max_messages: usize, timeout_secs: u64, ) -> Self
Configure the shutdown summary: whether to produce one, message count bounds, and timeout.
Sourcepub fn with_skill_reload(
self,
paths: Vec<PathBuf>,
rx: Receiver<SkillEvent>,
) -> Self
pub fn with_skill_reload( self, paths: Vec<PathBuf>, rx: Receiver<SkillEvent>, ) -> Self
Configure skill hot-reload: watch paths and the event receiver.
Sourcepub fn with_managed_skills_dir(self, dir: PathBuf) -> Self
pub fn with_managed_skills_dir(self, dir: PathBuf) -> Self
Set the directory used by /skill install and /skill remove.
Sourcepub fn with_trust_config(self, config: TrustConfig) -> Self
pub fn with_trust_config(self, config: TrustConfig) -> Self
Set the skill trust configuration (allowlists, sandbox flags).
Sourcepub fn with_skill_matching_config(
self,
disambiguation_threshold: f32,
two_stage_matching: bool,
confusability_threshold: f32,
) -> Self
pub fn with_skill_matching_config( self, disambiguation_threshold: f32, two_stage_matching: bool, confusability_threshold: f32, ) -> Self
Configure skill matching parameters (disambiguation, two-stage, confusability).
Sourcepub fn with_embedding_model(self, model: String) -> Self
pub fn with_embedding_model(self, model: String) -> Self
Override the embedding model name used for skill matching.
Sourcepub fn with_embedding_provider(self, provider: AnyProvider) -> Self
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.
Sourcepub fn with_hybrid_search(self, enabled: bool) -> Self
pub fn with_hybrid_search(self, enabled: bool) -> Self
Enable BM25 hybrid search alongside embedding-based skill matching.
§Panics
Sourcepub fn with_rl_routing(
self,
enabled: bool,
learning_rate: f32,
rl_weight: f32,
persist_interval: u32,
warmup_updates: u32,
) -> Self
pub fn with_rl_routing( self, enabled: bool, learning_rate: f32, rl_weight: f32, persist_interval: u32, warmup_updates: u32, ) -> Self
Configure the SkillOrchestra RL routing head.
When enabled = false, the head is not loaded and re-ranking is skipped.
Sourcepub fn with_rl_head(self, head: RoutingHead) -> Self
pub fn with_rl_head(self, head: RoutingHead) -> Self
Attach a pre-loaded RL routing head (loaded from DB weights at startup).
Sourcepub fn with_summary_provider(self, provider: AnyProvider) -> Self
pub fn with_summary_provider(self, provider: AnyProvider) -> Self
Set the dedicated summarization provider used for compaction LLM calls.
Sourcepub fn with_judge_provider(self, provider: AnyProvider) -> Self
pub fn with_judge_provider(self, provider: AnyProvider) -> Self
Set the judge provider for feedback-based correction detection.
Sourcepub fn with_probe_provider(self, provider: AnyProvider) -> Self
pub fn with_probe_provider(self, provider: AnyProvider) -> Self
Set the probe provider for compaction probing LLM calls.
Falls back to summary_provider (or primary) when None.
Sourcepub fn with_compress_provider(self, provider: AnyProvider) -> Self
pub fn with_compress_provider(self, provider: AnyProvider) -> Self
Set a dedicated provider for compress_context LLM calls (#2356).
When not set, handle_compress_context falls back to the primary provider.
Sourcepub fn with_planner_provider(self, provider: AnyProvider) -> Self
pub fn with_planner_provider(self, provider: AnyProvider) -> Self
Set the planner provider for LlmPlanner orchestration calls.
Sourcepub fn with_verify_provider(self, provider: AnyProvider) -> Self
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.
Sourcepub fn with_eval_provider(self, provider: AnyProvider) -> Self
pub fn with_eval_provider(self, provider: AnyProvider) -> Self
Set a dedicated judge provider for experiment evaluation.
When set, the evaluator uses this provider instead of the agent’s primary provider,
eliminating self-judge bias. Corresponds to experiments.eval_model in config.
Sourcepub fn with_provider_pool(
self,
pool: Vec<ProviderEntry>,
snapshot: ProviderConfigSnapshot,
) -> Self
pub fn with_provider_pool( self, pool: Vec<ProviderEntry>, snapshot: ProviderConfigSnapshot, ) -> Self
Store the provider pool and config snapshot for runtime /provider switching.
Sourcepub fn with_provider_override(
self,
slot: Arc<RwLock<Option<AnyProvider>>>,
) -> Self
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.
Sourcepub fn with_active_provider_name(self, name: impl Into<String>) -> Self
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().
Sourcepub fn with_stt(self, stt: Box<dyn SpeechToText>) -> Self
pub fn with_stt(self, stt: Box<dyn SpeechToText>) -> Self
Attach a speech-to-text backend for voice input.
Sourcepub fn with_mcp(
self,
tools: Vec<McpTool>,
registry: Option<McpToolRegistry>,
manager: Option<Arc<McpManager>>,
mcp_config: &McpConfig,
) -> Self
pub fn with_mcp( self, tools: Vec<McpTool>, registry: Option<McpToolRegistry>, manager: Option<Arc<McpManager>>, mcp_config: &McpConfig, ) -> Self
Attach MCP tools, registry, manager, and connection parameters.
Sourcepub fn with_mcp_server_outcomes(
self,
outcomes: Vec<ServerConnectOutcome>,
) -> Self
pub fn with_mcp_server_outcomes( self, outcomes: Vec<ServerConnectOutcome>, ) -> Self
Store the per-server connection outcomes for TUI and /status display.
Attach the shared MCP tool list (updated dynamically when servers reconnect).
Sourcepub fn with_mcp_pruning(
self,
params: PruningParams,
enabled: bool,
pruning_provider: Option<AnyProvider>,
) -> Self
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.
Sourcepub fn with_mcp_discovery(
self,
strategy: ToolDiscoveryStrategy,
params: DiscoveryParams,
discovery_provider: Option<AnyProvider>,
) -> Self
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.
Sourcepub fn with_mcp_tool_rx(self, rx: Receiver<Vec<McpTool>>) -> Self
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.
Sourcepub fn with_mcp_elicitation_rx(self, rx: Receiver<ElicitationEvent>) -> Self
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.
Sourcepub fn with_security(
self,
security: SecurityConfig,
timeouts: TimeoutConfig,
) -> Self
pub fn with_security( self, security: SecurityConfig, timeouts: TimeoutConfig, ) -> Self
Apply the full security configuration: sanitizers, exfiltration guard, PII filter, rate limiter, and pre-execution verifiers.
Sourcepub fn with_quarantine_summarizer(self, qs: QuarantinedSummarizer) -> Self
pub fn with_quarantine_summarizer(self, qs: QuarantinedSummarizer) -> Self
Attach a QuarantinedSummarizer for MCP cross-boundary audit.
Sourcepub fn with_acp_session(self, is_acp: bool) -> Self
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.
Sourcepub fn with_causal_analyzer(self, analyzer: TurnCausalAnalyzer) -> Self
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.
Sourcepub fn with_guardrail(self, filter: GuardrailFilter) -> Self
pub fn with_guardrail(self, filter: GuardrailFilter) -> Self
Attach a guardrail filter for output safety checking.
Sourcepub fn with_audit_logger(self, logger: Arc<AuditLogger>) -> Self
pub fn with_audit_logger(self, logger: Arc<AuditLogger>) -> Self
Attach an audit logger for pre-execution verifier blocks.
Sourcepub fn with_context_budget(
self,
budget_tokens: usize,
reserve_ratio: f32,
hard_compaction_threshold: f32,
compaction_preserve_tail: usize,
prune_protect_tokens: usize,
) -> Self
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
Configure the context token budget and compaction thresholds.
Sourcepub fn with_compression(self, compression: CompressionConfig) -> Self
pub fn with_compression(self, compression: CompressionConfig) -> Self
Apply the compression strategy configuration.
Sourcepub fn with_routing(self, routing: StoreRoutingConfig) -> Self
pub fn with_routing(self, routing: StoreRoutingConfig) -> Self
Set the memory store routing config (heuristic vs. embedding-based).
Sourcepub fn with_focus_and_sidequest_config(
self,
focus: FocusConfig,
sidequest: SidequestConfig,
) -> Self
pub fn with_focus_and_sidequest_config( self, focus: FocusConfig, sidequest: SidequestConfig, ) -> Self
Configure Focus and SideQuest LLM-driven context management (#1850, #1885).
Sourcepub fn add_tool_executor(self, extra: impl ToolExecutor + 'static) -> Self
pub fn add_tool_executor(self, extra: impl ToolExecutor + 'static) -> Self
Wrap the current tool executor with an additional executor via CompositeExecutor.
Sourcepub fn with_tafc_config(self, config: TafcConfig) -> Self
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.
Sourcepub fn with_dependency_config(self, config: DependencyConfig) -> Self
pub fn with_dependency_config(self, config: DependencyConfig) -> Self
Set dependency config parameters (boost values) used per-turn.
Sourcepub fn with_tool_dependency_graph(
self,
graph: ToolDependencyGraph,
always_on: HashSet<String>,
) -> Self
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.
Sourcepub async fn maybe_init_tool_schema_filter(
self,
config: &ToolFilterConfig,
provider: &AnyProvider,
) -> Self
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.
Sourcepub fn with_index_mcp_server(self, project_root: impl Into<PathBuf>) -> Self
pub fn with_index_mcp_server(self, project_root: impl Into<PathBuf>) -> Self
Add an in-process IndexMcpServer as a tool executor.
When enabled, the LLM can call symbol_definition, find_text_references,
call_graph, and module_summary tools on demand. Static repo-map injection
should be disabled when this is active (set repo_map_tokens = 0 or skip
inject_code_context).
Sourcepub fn with_repo_map(self, token_budget: usize, ttl_secs: u64) -> Self
pub fn with_repo_map(self, token_budget: usize, ttl_secs: u64) -> Self
Configure the in-process repo-map injector.
Sourcepub fn with_debug_dumper(self, dumper: DebugDumper) -> Self
pub fn with_debug_dumper(self, dumper: DebugDumper) -> Self
Enable debug dump mode, writing LLM requests/responses and raw tool output to dumper.
Sourcepub fn with_trace_collector(self, collector: TracingCollector) -> Self
pub fn with_trace_collector(self, collector: TracingCollector) -> Self
Enable OTel trace collection. The collector writes trace.json at session end.
Sourcepub fn with_trace_config(
self,
dump_dir: PathBuf,
service_name: impl Into<String>,
redact: bool,
) -> Self
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).
Sourcepub fn with_anomaly_detector(self, detector: AnomalyDetector) -> Self
pub fn with_anomaly_detector(self, detector: AnomalyDetector) -> Self
Attach an anomaly detector for turn-level error rate monitoring.
Sourcepub fn with_logging_config(self, logging: LoggingConfig) -> Self
pub fn with_logging_config(self, logging: LoggingConfig) -> Self
Apply the logging configuration (log level, structured output).
Sourcepub fn with_shutdown(self, rx: Receiver<bool>) -> Self
pub fn with_shutdown(self, rx: Receiver<bool>) -> Self
Attach the graceful-shutdown receiver.
Sourcepub fn with_config_reload(
self,
path: PathBuf,
rx: Receiver<ConfigEvent>,
) -> Self
pub fn with_config_reload( self, path: PathBuf, rx: Receiver<ConfigEvent>, ) -> Self
Attach the config-reload event stream.
Sourcepub fn with_warmup_ready(self, rx: Receiver<bool>) -> Self
pub fn with_warmup_ready(self, rx: Receiver<bool>) -> Self
Attach the warmup-ready signal (fires after background init completes).
Sourcepub fn with_update_notifications(self, rx: Receiver<String>) -> Self
pub fn with_update_notifications(self, rx: Receiver<String>) -> Self
Attach the update-notification receiver for in-process version alerts.
Sourcepub fn with_custom_task_rx(self, rx: Receiver<String>) -> Self
pub fn with_custom_task_rx(self, rx: Receiver<String>) -> Self
Attach a custom task receiver for programmatic task injection.
Sourcepub fn with_cancel_signal(self, signal: Arc<Notify>) -> Self
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().
Sourcepub fn with_hooks_config(self, config: &HooksConfig) -> Self
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).
Sourcepub fn with_working_dir(self, path: impl Into<PathBuf>) -> Self
pub fn with_working_dir(self, path: impl Into<PathBuf>) -> Self
Set the working directory and initialise the environment context snapshot.
Sourcepub fn with_policy_config(self, config: PolicyConfig) -> Self
pub fn with_policy_config(self, config: PolicyConfig) -> Self
Store a snapshot of the policy config for /policy command inspection.
Sourcepub fn with_parent_tool_use_id(self, id: impl Into<String>) -> Self
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.
Sourcepub fn with_response_cache(self, cache: Arc<ResponseCache>) -> Self
pub fn with_response_cache(self, cache: Arc<ResponseCache>) -> Self
Attach a cached response store for per-session deduplication.
Sourcepub fn with_lsp_hooks(self, runner: LspHookRunner) -> Self
pub fn with_lsp_hooks(self, runner: LspHookRunner) -> Self
Enable LSP context injection hooks (diagnostics-on-save, hover-on-read).
Sourcepub fn with_supervisor_config(self, config: &TaskSupervisorConfig) -> Self
pub fn with_supervisor_config(self, config: &TaskSupervisorConfig) -> Self
Configure the background task supervisor with explicit limits and optional recorder.
Re-initialises the supervisor from config. Call this after
with_histogram_recorder so the recorder is
available for passing to the supervisor.
Sourcepub fn cancel_signal(&self) -> Arc<Notify>
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.
Sourcepub fn with_metrics(self, tx: Sender<MetricsSnapshot>) -> Self
pub fn with_metrics(self, tx: Sender<MetricsSnapshot>) -> Self
Wire the metrics broadcast channel and emit the initial snapshot.
Sourcepub fn with_cost_tracker(self, tracker: CostTracker) -> Self
pub fn with_cost_tracker(self, tracker: CostTracker) -> Self
Attach a cost tracker for per-session token budget accounting.
Sourcepub fn with_extended_context(self, enabled: bool) -> Self
pub fn with_extended_context(self, enabled: bool) -> Self
Enable Claude extended-context mode tracking in metrics.
Sourcepub fn with_histogram_recorder(
self,
recorder: Option<Arc<dyn HistogramRecorder>>,
) -> Self
pub fn with_histogram_recorder( self, recorder: Option<Arc<dyn HistogramRecorder>>, ) -> Self
Attach a histogram recorder for per-event Prometheus observations.
When set, the agent records individual LLM call, turn, and tool execution
latencies into the provided recorder. The recorder must be Send + Sync
and is shared across the agent loop via Arc.
Pass None to disable histogram recording (the default).
Sourcepub fn with_orchestration(
self,
config: OrchestrationConfig,
subagent_config: SubAgentConfig,
manager: SubAgentManager,
) -> Self
pub fn with_orchestration( self, config: OrchestrationConfig, subagent_config: SubAgentConfig, manager: SubAgentManager, ) -> Self
Configure orchestration, subagent management, and experiment baseline in a single call.
Replaces the former with_orchestration_config, with_subagent_manager, and
with_subagent_config methods. All three are always configured together at the
call site in runner.rs, so they are grouped here to reduce boilerplate.
Sourcepub fn with_adversarial_policy_info(self, info: AdversarialPolicyInfo) -> Self
pub fn with_adversarial_policy_info(self, info: AdversarialPolicyInfo) -> Self
Store adversarial policy gate info for /status display.
Sourcepub fn with_experiment(
self,
config: ExperimentConfig,
baseline: ConfigSnapshot,
) -> Self
pub fn with_experiment( self, config: ExperimentConfig, baseline: ConfigSnapshot, ) -> Self
Set the experiment configuration and baseline config snapshot together.
Replaces the former with_experiment_config and with_experiment_baseline methods.
Both are always set together at the call site, so they are grouped here to reduce
boilerplate.
baseline should be built via ConfigSnapshot::from_config(&config) so the experiment
engine uses actual runtime config values (temperature, memory params, etc.) rather than
hardcoded defaults.
Sourcepub fn with_learning(self, config: LearningConfig) -> Self
pub fn with_learning(self, config: LearningConfig) -> Self
Apply the learning configuration (correction detection, RL routing, classifier mode).
Sourcepub fn with_llm_classifier(self, classifier: LlmClassifier) -> Self
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).
Sourcepub fn with_channel_skills(self, config: ChannelSkillsConfig) -> Self
pub fn with_channel_skills(self, config: ChannelSkillsConfig) -> Self
Configure the per-channel skill overrides (channel-specific skill resolution).
Sourcepub fn apply_session_config(self, cfg: AgentSessionConfig) -> Self
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.
Sourcepub fn with_instruction_blocks(self, blocks: Vec<InstructionBlock>) -> Self
pub fn with_instruction_blocks(self, blocks: Vec<InstructionBlock>) -> Self
Configure instruction block hot-reload.
Sourcepub fn with_instruction_reload(
self,
rx: Receiver<InstructionEvent>,
state: InstructionReloadState,
) -> Self
pub fn with_instruction_reload( self, rx: Receiver<InstructionEvent>, state: InstructionReloadState, ) -> Self
Attach the instruction reload event stream.
Sourcepub fn with_status_tx(self, tx: UnboundedSender<String>) -> Self
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§impl<C: Channel> Agent<C>
impl<C: Channel> Agent<C>
Sourcepub async fn init_semantic_index(&mut self)
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>
impl<C: Channel> Agent<C>
Sourcepub async fn load_history(&mut self) -> Result<(), AgentError>
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>
impl<C: Channel> Agent<C>
Sourcepub fn sync_community_detection_failures(&self)
pub fn sync_community_detection_failures(&self)
Read the community-detection failure counter from SemanticMemory and update metrics.
Sourcepub fn sync_graph_extraction_metrics(&self)
pub fn sync_graph_extraction_metrics(&self)
Sync all graph counters (extraction count/failures) from SemanticMemory to metrics.
Sourcepub async fn sync_graph_counts(&self)
pub async fn sync_graph_counts(&self)
Fetch entity/edge/community counts from the graph store and write to metrics.
Sourcepub async fn check_vector_store_health(&self, backend_name: &str)
pub async fn check_vector_store_health(&self, backend_name: &str)
Perform a real health check on the vector store and update metrics.
Sourcepub async fn sync_guidelines_status(&self)
pub async fn sync_guidelines_status(&self)
Fetch compression-guidelines metadata from SQLite and write to metrics.
Only fetches version and created_at; does not load the full guidelines text.
Feature-gated: compiled only when compression-guidelines is enabled.
Sourcepub fn inject_code_context(&mut self, text: &str)
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.
pub fn context_messages(&self) -> &[Message]
Source§impl<C: Channel> Agent<C>
impl<C: Channel> Agent<C>
Sourcepub fn new(
provider: AnyProvider,
channel: C,
registry: SkillRegistry,
matcher: Option<SkillMatcherBackend>,
max_active_skills: usize,
tool_executor: impl ToolExecutor + 'static,
) -> Self
pub fn new( provider: AnyProvider, channel: C, registry: SkillRegistry, matcher: Option<SkillMatcherBackend>, max_active_skills: usize, tool_executor: impl ToolExecutor + 'static, ) -> Self
Create a new agent instance with the given LLM provider, I/O channel, and subsystems.
§Arguments
provider— Multi-model LLM provider (Claude,OpenAI, Ollama, Candle)channel— I/O abstraction for user interaction (CLI, Telegram, TUI, etc.)registry— Skill registry; moved into an internalArc<RwLock<_>>for sharingmatcher— Optional semantic skill matcher (e.g., Qdrant, BM25). IfNone, skills are matched by exact name onlymax_active_skills— Max concurrent skills in execution (must be > 0)tool_executor— Trait object for executing shell, web, and custom tools
§Initialization
The constructor:
- Wraps the skill registry into
Arc<RwLock<_>>internally - Builds the system prompt from registered skills
- Initializes all subsystems (memory, context manager, metrics, security)
- Returns a ready-to-run agent
§Panics
Panics if max_active_skills is 0.
Sourcepub fn new_with_registry_arc(
provider: AnyProvider,
embedding_provider: AnyProvider,
channel: C,
registry: Arc<RwLock<SkillRegistry>>,
matcher: Option<SkillMatcherBackend>,
max_active_skills: usize,
tool_executor: impl ToolExecutor + 'static,
) -> Self
pub fn new_with_registry_arc( provider: AnyProvider, embedding_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.
Sourcepub async fn poll_subagents(&mut self) -> Vec<(String, String)>
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.
Sourcepub async fn shutdown(&mut self)
pub async fn shutdown(&mut self)
Gracefully shut down the agent and persist state.
Performs the following cleanup:
- Message persistence — Deferred database writes (hide/summary operations) are flushed to memory or disk
- Provider state — LLM router state (e.g., Thompson sampling counters) is saved to the vault
- Sub-agents — All active sub-agent tasks are terminated
- MCP servers — All connected Model Context Protocol servers are shut down
- Metrics finalization — Compaction metrics and session metrics are recorded
- Memory finalization — Vector stores and semantic indices are flushed
- Skill state — Self-learning engine saves evolved skill definitions
Call this before dropping the agent to ensure no data loss.
Trait Implementations§
Source§impl<C: Channel + Send + 'static> AgentAccess for Agent<C>
impl<C: Channel + Send + 'static> AgentAccess for Agent<C>
Source§fn memory_tiers<'a>(
&'a mut self,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn memory_tiers<'a>( &'a mut self, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
Source§fn memory_promote<'a>(
&'a mut self,
ids_str: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn memory_promote<'a>( &'a mut self, ids_str: &'a str, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
Source§fn graph_stats<'a>(
&'a mut self,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn graph_stats<'a>( &'a mut self, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
Source§fn graph_entities<'a>(
&'a mut self,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn graph_entities<'a>( &'a mut self, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
Source§fn graph_facts<'a>(
&'a mut self,
name: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn graph_facts<'a>( &'a mut self, name: &'a str, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
name. Read moreSource§fn graph_history<'a>(
&'a mut self,
name: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn graph_history<'a>( &'a mut self, name: &'a str, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
name. Read moreSource§fn graph_communities<'a>(
&'a mut self,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn graph_communities<'a>( &'a mut self, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
Source§fn graph_backfill<'a>(
&'a mut self,
limit: Option<usize>,
progress_cb: &'a mut (dyn FnMut(String) + Send),
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn graph_backfill<'a>( &'a mut self, limit: Option<usize>, progress_cb: &'a mut (dyn FnMut(String) + Send), ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
progress_cb for each progress update. Read moreSource§fn guidelines<'a>(
&'a mut self,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn guidelines<'a>( &'a mut self, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
Source§fn handle_model<'a>(
&'a mut self,
arg: &'a str,
) -> Pin<Box<dyn Future<Output = String> + Send + 'a>>
fn handle_model<'a>( &'a mut self, arg: &'a str, ) -> Pin<Box<dyn Future<Output = String> + Send + 'a>>
/model [arg] and return a user-visible result.Source§fn handle_provider<'a>(
&'a mut self,
arg: &'a str,
) -> Pin<Box<dyn Future<Output = String> + Send + 'a>>
fn handle_provider<'a>( &'a mut self, arg: &'a str, ) -> Pin<Box<dyn Future<Output = String> + Send + 'a>>
/provider [arg] and return a user-visible result.Source§fn handle_policy<'a>(
&'a mut self,
args: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn handle_policy<'a>( &'a mut self, args: &'a str, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
/policy [status|check ...] and return a user-visible result. Read moreSource§fn list_scheduled_tasks<'a>(
&'a mut self,
) -> Pin<Box<dyn Future<Output = Result<Option<String>, CommandError>> + Send + 'a>>
fn list_scheduled_tasks<'a>( &'a mut self, ) -> Pin<Box<dyn Future<Output = Result<Option<String>, CommandError>> + Send + 'a>>
Source§fn lsp_status<'a>(
&'a mut self,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn lsp_status<'a>( &'a mut self, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
Source§fn compact_context<'a>(
&'a mut self,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn compact_context<'a>( &'a mut self, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
Source§fn reset_conversation<'a>(
&'a mut self,
keep_plan: bool,
no_digest: bool,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn reset_conversation<'a>( &'a mut self, keep_plan: bool, no_digest: bool, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
Source§fn cache_stats(&self) -> String
fn cache_stats(&self) -> String
Source§fn session_status<'a>(
&'a mut self,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn session_status<'a>( &'a mut self, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
Source§fn guardrail_status(&self) -> String
fn guardrail_status(&self) -> String
Source§fn focus_status(&self) -> String
fn focus_status(&self) -> String
Source§fn sidequest_status(&self) -> String
fn sidequest_status(&self) -> String
SideQuest eviction stats.Source§fn load_image<'a>(
&'a mut self,
path: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn load_image<'a>( &'a mut self, path: &'a str, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
path and enqueue it for the next message. Read moreSource§fn handle_mcp<'a>(
&'a mut self,
args: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn handle_mcp<'a>( &'a mut self, args: &'a str, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
/mcp [add|list|tools|remove] and send output via the agent channel. Read moreSource§fn handle_skill<'a>(
&'a mut self,
args: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn handle_skill<'a>( &'a mut self, args: &'a str, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
/skill [subcommand] and return a user-visible result. Read moreSource§fn handle_skills<'a>(
&'a mut self,
args: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn handle_skills<'a>( &'a mut self, args: &'a str, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
/skills [subcommand] and return a user-visible result. Read moreSource§fn handle_feedback_command<'a>(
&'a mut self,
args: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn handle_feedback_command<'a>( &'a mut self, args: &'a str, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
/feedback <skill_name> <message> and return a user-visible result. Read moreSource§fn handle_plan<'a>(
&'a mut self,
_input: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
fn handle_plan<'a>( &'a mut self, _input: &'a str, ) -> Pin<Box<dyn Future<Output = Result<String, CommandError>> + Send + 'a>>
/plan command and send output via the agent channel. Read moreAuto 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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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 moreSource§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
Source§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request