zeph_core/agent/state/mod.rs
1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Sub-struct definitions for the `Agent` struct.
5//!
6//! Each struct groups a related cluster of `Agent` fields.
7//! All types are `pub(crate)` — visible only within the `zeph-core` crate.
8//!
9//! `MemoryState` is decomposed into four concern-separated sub-structs, each in its own file:
10//!
11//! - [`MemoryPersistenceState`] — `SQLite` handles, conversation IDs, recall budgets, autosave
12//! - [`MemoryCompactionState`] — summarization thresholds, shutdown summary, digest, strategy
13//! - [`MemoryExtractionState`] — graph config, RPE router, document config, semantic labels
14//! - [`MemorySubsystemState`] — `TiMem`, `autoDream`, `MagicDocs`, microcompact
15
16pub(crate) mod compaction;
17pub(crate) mod extraction;
18pub(crate) mod persistence;
19pub(crate) mod runtime;
20pub(crate) mod services;
21pub(crate) mod subsystems;
22
23pub(crate) use self::compaction::MemoryCompactionState;
24pub(crate) use self::extraction::MemoryExtractionState;
25pub(crate) use self::persistence::MemoryPersistenceState;
26pub(crate) use self::runtime::AgentRuntime;
27pub(crate) use self::services::Services;
28pub(crate) use self::subsystems::MemorySubsystemState;
29
30use std::collections::{HashMap, HashSet, VecDeque};
31use std::path::PathBuf;
32use std::sync::Arc;
33
34use parking_lot::RwLock;
35use std::time::Instant;
36
37use tokio::sync::{Notify, mpsc, watch};
38use tokio::time::Interval;
39use tokio_util::sync::CancellationToken;
40use zeph_llm::any::AnyProvider;
41use zeph_llm::provider::Message;
42use zeph_llm::stt::SpeechToText;
43
44use crate::config::{ProviderEntry, SecurityConfig, SkillPromptMode, TimeoutConfig};
45use crate::config_watcher::ConfigEvent;
46use crate::context::EnvironmentContext;
47use crate::cost::CostTracker;
48use crate::file_watcher::FileChangedEvent;
49use crate::instructions::{InstructionBlock, InstructionEvent, InstructionReloadState};
50use crate::metrics::MetricsSnapshot;
51use crate::vault::Secret;
52use zeph_config;
53use zeph_memory::TokenCounter;
54use zeph_sanitizer::ContentSanitizer;
55use zeph_sanitizer::quarantine::QuarantinedSummarizer;
56use zeph_skills::matcher::SkillMatcherBackend;
57use zeph_skills::registry::SkillRegistry;
58use zeph_skills::watcher::SkillEvent;
59use zeroize::Zeroizing;
60
61use super::message_queue::QueuedMessage;
62
63/// Coordinator struct holding four concern-separated sub-structs for memory management.
64///
65/// Each sub-struct groups fields by a single concern:
66/// - [`persistence`](MemoryPersistenceState) — `SQLite` handles, conversation IDs, recall budgets
67/// - [`compaction`](MemoryCompactionState) — summarization thresholds, shutdown summary, digest
68/// - [`extraction`](MemoryExtractionState) — graph config, RPE router, semantic labels
69/// - [`subsystems`](MemorySubsystemState) — `TiMem`, `autoDream`, `MagicDocs`, microcompact
70#[derive(Default)]
71pub(crate) struct MemoryState {
72 /// `SQLite` handles, conversation IDs, recall budgets, and autosave policy.
73 pub(crate) persistence: MemoryPersistenceState,
74 /// Summarization thresholds, shutdown summary, digest config, and context strategy.
75 pub(crate) compaction: MemoryCompactionState,
76 /// Graph extraction config, RPE router, document config, and semantic label configs.
77 pub(crate) extraction: MemoryExtractionState,
78 /// `TiMem`, `autoDream`, `MagicDocs`, and microcompact subsystem state.
79 pub(crate) subsystems: MemorySubsystemState,
80}
81
82pub(crate) struct SkillState {
83 pub(crate) registry: Arc<RwLock<SkillRegistry>>,
84 /// Per-turn trust snapshot written by `prepare_context` after `build_skill_trust_map`.
85 /// Shared with `SkillInvokeExecutor` so it can resolve trust without hitting `SQLite`
86 /// on every tool call. Refreshed once per turn — stale by at most one turn.
87 /// Carries full `SkillTrustSnapshot` (level + `requires_trust_check` + `blake3_hash`) so
88 /// `SkillInvokeExecutor` can perform per-invocation re-hash when the flag is set.
89 pub(crate) trust_snapshot:
90 Arc<RwLock<HashMap<String, crate::skill_invoker::SkillTrustSnapshot>>>,
91 pub(crate) skill_paths: Vec<PathBuf>,
92 pub(crate) managed_dir: Option<PathBuf>,
93 pub(crate) trust_config: crate::config::TrustConfig,
94 pub(crate) matcher: Option<SkillMatcherBackend>,
95 pub(crate) max_active_skills: usize,
96 pub(crate) disambiguation_threshold: f32,
97 pub(crate) min_injection_score: f32,
98 pub(crate) embedding_model: String,
99 pub(crate) skill_reload_rx: Option<mpsc::Receiver<SkillEvent>>,
100 /// Resolves the current set of per-plugin skill dirs at reload time.
101 ///
102 /// Called inside `reload_skills()` so that plugins installed via `/plugins add` after
103 /// startup are discovered on the next watcher event without restarting the agent.
104 pub(crate) plugin_dirs_supplier: Option<Arc<dyn Fn() -> Vec<PathBuf> + Send + Sync>>,
105 pub(crate) active_skill_names: Vec<String>,
106 pub(crate) last_skills_prompt: String,
107 pub(crate) prompt_mode: SkillPromptMode,
108 /// Custom secrets available at runtime: key=hyphenated name, value=secret.
109 pub(crate) available_custom_secrets: HashMap<String, Secret>,
110 pub(crate) cosine_weight: f32,
111 pub(crate) hybrid_search: bool,
112 pub(crate) bm25_index: Option<zeph_skills::bm25::Bm25Index>,
113 pub(crate) two_stage_matching: bool,
114 /// Threshold for confusability warnings (0.0 = disabled).
115 pub(crate) confusability_threshold: f32,
116 /// `SkillOrchestra` RL routing head. `Some` when `rl_routing_enabled = true` and
117 /// weights are loaded or initialized. `None` when RL routing is disabled.
118 pub(crate) rl_head: Option<zeph_skills::rl_head::RoutingHead>,
119 /// Blend weight for RL routing: `final = (1-rl_weight)*cosine + rl_weight*rl_score`.
120 pub(crate) rl_weight: f32,
121 /// Skip RL blending for the first N updates (cold-start warmup).
122 pub(crate) rl_warmup_updates: u32,
123 /// Directory where `/skill create` writes generated skills.
124 /// Defaults to `managed_dir` if `None`.
125 pub(crate) generation_output_dir: Option<std::path::PathBuf>,
126 /// Provider name for `/skill create` generation. Empty = primary.
127 pub(crate) generation_provider_name: String,
128 /// Provider name for skill disambiguation LLM calls. Empty = primary.
129 pub(crate) disambiguate_provider_name: String,
130 /// Timeout in milliseconds for `/skill create` LLM generation. Default: 60 000.
131 pub(crate) generation_timeout_ms: u64,
132 /// Optional quality-gate evaluator for generated SKILL.md files (#3319).
133 ///
134 /// When `Some`, the evaluator is attached to every `SkillGenerator` instance so that
135 /// generated skills are scored before being written to disk.
136 pub(crate) skill_evaluator: Option<std::sync::Arc<zeph_skills::evaluator::SkillEvaluator>>,
137 /// Weights for the evaluator composite score — forwarded to `SkillGenerator::with_evaluator`.
138 pub(crate) eval_weights: zeph_skills::evaluator::EvaluationWeights,
139 /// Minimum composite score required to accept a generated skill (forwarded to the generator).
140 pub(crate) eval_threshold: f32,
141}
142
143pub(crate) struct McpState {
144 pub(crate) tools: Vec<zeph_mcp::McpTool>,
145 pub(crate) registry: Option<zeph_mcp::McpToolRegistry>,
146 pub(crate) manager: Option<std::sync::Arc<zeph_mcp::McpManager>>,
147 pub(crate) allowed_commands: Vec<String>,
148 pub(crate) max_dynamic: usize,
149 /// Receives elicitation requests from MCP server handlers during tool execution.
150 /// When `Some`, the agent loop must process these concurrently with tool result awaiting
151 /// to avoid deadlock (tool result waits for elicitation, elicitation waits for agent loop).
152 pub(crate) elicitation_rx: Option<tokio::sync::mpsc::Receiver<zeph_mcp::ElicitationEvent>>,
153 /// Shared with `McpToolExecutor` so native `tool_use` sees the current tool list.
154 ///
155 /// Two methods write to this `RwLock` — ordering matters:
156 /// - `sync_executor_tools()`: writes the **full** `self.tools` set.
157 /// - `apply_pruned_tools()`: writes the **pruned** subset (used after pruning).
158 ///
159 /// Within a turn, `sync_executor_tools` must always run **before**
160 /// `apply_pruned_tools`. The normal call order guarantees this: tool-list
161 /// change events call `sync_executor_tools` (inside `check_tool_refresh`,
162 /// `handle_mcp_add`, `handle_mcp_remove`), and pruning runs later inside
163 /// `rebuild_system_prompt`. See also: `apply_pruned_tools`.
164 pub(crate) shared_tools: Option<Arc<RwLock<Vec<zeph_mcp::McpTool>>>>,
165 /// Receives full flattened tool list after any `tools/list_changed` notification.
166 pub(crate) tool_rx: Option<tokio::sync::watch::Receiver<Vec<zeph_mcp::McpTool>>>,
167 /// Per-server connection outcomes from the initial `connect_all()` call.
168 pub(crate) server_outcomes: Vec<zeph_mcp::ServerConnectOutcome>,
169 /// Per-message cache for MCP tool pruning results (#2298).
170 ///
171 /// Reset at the start of each user turn and whenever the MCP tool list
172 /// changes (via `tools/list_changed`, `/mcp add`, or `/mcp remove`).
173 pub(crate) pruning_cache: zeph_mcp::PruningCache,
174 /// Dedicated provider for MCP tool pruning LLM calls.
175 ///
176 /// `None` means fall back to the agent's primary provider.
177 /// Resolved from `[[llm.providers]]` at build time using `pruning_provider`
178 /// from `ToolPruningConfig`.
179 pub(crate) pruning_provider: Option<zeph_llm::any::AnyProvider>,
180 /// Whether MCP tool pruning is enabled. Mirrors `ToolPruningConfig::enabled`.
181 pub(crate) pruning_enabled: bool,
182 /// Pruning parameters snapshot. Derived from `ToolPruningConfig` at build time.
183 pub(crate) pruning_params: zeph_mcp::PruningParams,
184 /// Pre-computed semantic tool index for embedding-based discovery (#2321).
185 ///
186 /// Built at connect time via `rebuild_semantic_index()`, rebuilt on tool list change.
187 /// `None` when strategy is not `Embedding` or when build failed (fallback to all tools).
188 pub(crate) semantic_index: Option<zeph_mcp::SemanticToolIndex>,
189 /// Active discovery strategy and parameters. Derived from `ToolDiscoveryConfig`.
190 pub(crate) discovery_strategy: zeph_mcp::ToolDiscoveryStrategy,
191 /// Discovery parameters snapshot. Derived from `ToolDiscoveryConfig` at build time.
192 pub(crate) discovery_params: zeph_mcp::DiscoveryParams,
193 /// Dedicated embedding provider for tool discovery. `None` = fall back to the
194 /// agent's primary embedding provider.
195 pub(crate) discovery_provider: Option<zeph_llm::any::AnyProvider>,
196 /// When `true`, show a security warning before prompting for fields whose names
197 /// match sensitive patterns (password, token, secret, key, credential, etc.).
198 pub(crate) elicitation_warn_sensitive_fields: bool,
199 /// When `true`, semantic index and registry need to be rebuilt at the next opportunity.
200 ///
201 /// Set after `/mcp add` or `/mcp remove` when called via `AgentAccess::handle_mcp`,
202 /// which cannot call `rebuild_semantic_index` and `sync_mcp_registry` directly because
203 /// those are `async fn(&mut self)` and their futures are `!Send` (they hold `&mut Agent<C>`
204 /// across `.await`). The rebuild is deferred to `check_tool_refresh`, which runs at the
205 /// start of each turn without the `Box<dyn Future + Send>` constraint.
206 pub(crate) pending_semantic_rebuild: bool,
207}
208
209pub(crate) struct IndexState {
210 pub(crate) retriever: Option<std::sync::Arc<zeph_index::retriever::CodeRetriever>>,
211 pub(crate) repo_map_tokens: usize,
212 pub(crate) cached_repo_map: Option<(String, std::time::Instant)>,
213 pub(crate) repo_map_ttl: std::time::Duration,
214}
215
216/// Snapshot of adversarial policy gate configuration for status display.
217#[derive(Debug, Clone)]
218pub struct AdversarialPolicyInfo {
219 pub provider: String,
220 pub policy_count: usize,
221 pub fail_open: bool,
222}
223
224#[allow(clippy::struct_excessive_bools)] // independent boolean flags; bitflags or enum would obscure semantics without reducing complexity
225pub(crate) struct RuntimeConfig {
226 pub(crate) security: SecurityConfig,
227 pub(crate) timeouts: TimeoutConfig,
228 pub(crate) model_name: String,
229 /// Configured name from `[[llm.providers]]` (the `name` field), set at startup and on
230 /// `/provider` switch. Falls back to the provider type string when empty.
231 pub(crate) active_provider_name: String,
232 pub(crate) permission_policy: zeph_tools::PermissionPolicy,
233 pub(crate) redact_credentials: bool,
234 pub(crate) rate_limiter: super::rate_limiter::ToolRateLimiter,
235 pub(crate) semantic_cache_enabled: bool,
236 pub(crate) semantic_cache_threshold: f32,
237 pub(crate) semantic_cache_max_candidates: u32,
238 /// Dependency config snapshot stored for per-turn boost parameters.
239 pub(crate) dependency_config: zeph_tools::DependencyConfig,
240 /// Adversarial policy gate runtime info for /status display.
241 pub(crate) adversarial_policy_info: Option<AdversarialPolicyInfo>,
242 /// Current spawn depth of this agent instance (0 = top-level, 1 = first sub-agent, etc.).
243 /// Used by `build_spawn_context()` to propagate depth to children.
244 pub(crate) spawn_depth: u32,
245 /// Inject `<budget>` XML into the volatile system prompt section (#2267).
246 pub(crate) budget_hint_enabled: bool,
247 /// Per-channel skill allowlist. Skills not matching the allowlist are excluded from the
248 /// prompt. An empty `allowed` list means all skills are permitted (default).
249 pub(crate) channel_skills: zeph_config::ChannelSkillsConfig,
250 /// Per-channel tool allowlist. `None` = no restriction. `Some` = only listed tools permitted.
251 /// Populated from the active channel's `allowed_tools` config at agent build time.
252 pub(crate) channel_tool_allowlist: Option<Vec<String>>,
253 /// Minimum allowed interval for `/loop` ticks (seconds). Sourced from `[cli.loop] min_interval_secs`.
254 pub(crate) loop_min_interval_secs: u64,
255 /// Runtime middleware layers for LLM calls and tool dispatch (#2286).
256 ///
257 /// Default: empty vec (zero-cost — loops never iterate).
258 pub(crate) layers: Vec<std::sync::Arc<dyn crate::runtime_layer::RuntimeLayer>>,
259 /// Background supervisor config snapshot for turn-boundary abort logic.
260 pub(crate) supervisor_config: crate::config::TaskSupervisorConfig,
261 /// Session recap config (#3064).
262 pub(crate) recap_config: zeph_config::RecapConfig,
263 /// ACP server configuration snapshot for `/acp` slash-command display.
264 pub(crate) acp_config: zeph_config::AcpConfig,
265 /// Set to `true` after the auto-recap is emitted at session resume (#3144).
266 ///
267 /// Used by `/recap` to skip a redundant LLM call when no new messages have
268 /// been added since the auto-recap was shown.
269 pub(crate) auto_recap_shown: bool,
270 /// Number of non-system messages present when the session was resumed (#3144).
271 ///
272 /// Combined with `auto_recap_shown` to detect whether the user has added new
273 /// messages after the auto-recap was shown.
274 pub(crate) msg_count_at_resume: usize,
275 /// Callback that spawns an external ACP sub-agent process by shell command (#3302).
276 ///
277 /// Injected by the binary crate when the `acp` feature is enabled.
278 /// `None` in bare / non-ACP mode; callers must degrade gracefully.
279 pub(crate) acp_subagent_spawn_fn: Option<zeph_subagent::AcpSubagentSpawnFn>,
280 /// Channel type string used as part of the `(channel_type, channel_id)` persistence key.
281 ///
282 /// Set at build time from the active I/O channel (e.g. `"cli"`, `"tui"`, `"telegram"`).
283 /// Empty when channel identity has not been configured (persistence is skipped).
284 pub(crate) channel_type: String,
285 /// Whether provider preference persistence is enabled for this session (#3308).
286 ///
287 /// Controlled by `[session] provider_persistence = true` (the default). When `false`,
288 /// the stored provider preference is never read or written.
289 pub(crate) provider_persistence_enabled: bool,
290 /// Goal lifecycle feature configuration.
291 pub(crate) goals: GoalRuntimeConfig,
292}
293
294/// Groups feedback detection subsystems: correction detector, judge detector, and LLM classifier.
295pub(crate) struct FeedbackState {
296 pub(crate) detector: zeph_agent_feedback::FeedbackDetector,
297 pub(crate) judge: Option<zeph_agent_feedback::JudgeDetector>,
298 /// LLM-backed zero-shot classifier for `DetectorMode::Model`.
299 /// When `Some`, `spawn_judge_correction_check` uses this instead of `JudgeDetector`.
300 pub(crate) llm_classifier: Option<zeph_llm::classifier::llm::LlmClassifier>,
301}
302
303/// Groups security-related subsystems (sanitizer, quarantine, exfiltration guard).
304pub(crate) struct SecurityState {
305 pub(crate) sanitizer: ContentSanitizer,
306 pub(crate) quarantine_summarizer: Option<QuarantinedSummarizer>,
307 /// Whether this agent session is serving an ACP client.
308 /// When `true` and `mcp_to_acp_boundary` is enabled, MCP tool results
309 /// receive unconditional quarantine and cross-boundary audit logging.
310 pub(crate) is_acp_session: bool,
311 pub(crate) exfiltration_guard: zeph_sanitizer::exfiltration::ExfiltrationGuard,
312 pub(crate) flagged_urls: HashSet<String>,
313 /// URLs explicitly provided by the user across all turns in this session.
314 /// Populated from raw user message text; cleared on `/clear`.
315 /// Shared with `UrlGroundingVerifier` to check `fetch`/`web_scrape` calls at dispatch time.
316 pub(crate) user_provided_urls: Arc<RwLock<HashSet<String>>>,
317 pub(crate) pii_filter: zeph_sanitizer::pii::PiiFilter,
318 /// NER classifier for PII detection (`classifiers.ner_model`). When `Some`, the PII path
319 /// runs both regex (`pii_filter`) and NER, then merges spans before redaction.
320 /// `None` when `classifiers` feature is disabled or `classifiers.enabled = false`.
321 #[cfg(feature = "classifiers")]
322 pub(crate) pii_ner_backend: Option<std::sync::Arc<dyn zeph_llm::classifier::ClassifierBackend>>,
323 /// Per-call timeout for the NER PII classifier in milliseconds.
324 #[cfg(feature = "classifiers")]
325 pub(crate) pii_ner_timeout_ms: u64,
326 /// Maximum number of bytes passed to the NER PII classifier per call.
327 ///
328 /// Large tool outputs (e.g. `search_code`) can produce 150+ `DeBERTa` chunks and exceed
329 /// the per-call timeout. Input is truncated at a valid UTF-8 boundary before classification.
330 #[cfg(feature = "classifiers")]
331 pub(crate) pii_ner_max_chars: usize,
332 /// Circuit-breaker threshold: number of consecutive timeouts before NER is disabled.
333 /// `0` means the circuit breaker is disabled (NER is always attempted).
334 #[cfg(feature = "classifiers")]
335 pub(crate) pii_ner_circuit_breaker_threshold: u32,
336 /// Number of consecutive NER timeouts observed since the last successful call.
337 #[cfg(feature = "classifiers")]
338 pub(crate) pii_ner_consecutive_timeouts: u32,
339 /// Set to `true` when the circuit breaker trips. NER is skipped for the rest of the session.
340 #[cfg(feature = "classifiers")]
341 pub(crate) pii_ner_tripped: bool,
342 pub(crate) memory_validator: zeph_sanitizer::memory_validation::MemoryWriteValidator,
343 /// LLM-based prompt injection pre-screener (opt-in).
344 pub(crate) guardrail: Option<zeph_sanitizer::guardrail::GuardrailFilter>,
345 /// Post-LLM response verification layer.
346 pub(crate) response_verifier: zeph_sanitizer::response_verifier::ResponseVerifier,
347 /// Temporal causal IPI analyzer (opt-in, disabled when `None`).
348 pub(crate) causal_analyzer: Option<zeph_sanitizer::causal_ipi::TurnCausalAnalyzer>,
349 /// VIGIL pre-sanitizer gate. `None` for subagent sessions (subagents are exempt).
350 /// Set at agent build time for top-level agents; skipped for subagents (high FP rate).
351 pub(crate) vigil: Option<crate::agent::vigil::VigilGate>,
352 /// Cross-turn risk accumulator (spec 050 Phase 1).
353 ///
354 /// `advance_turn()` MUST be called once per turn, before `PolicyGateExecutor::check_policy`.
355 /// Never expose score, level, or alerts to any LLM-callable surface.
356 pub(crate) trajectory: crate::agent::trajectory::TrajectorySentinel,
357 /// Shared risk-level slot for `PolicyGateExecutor` (spec 050).
358 ///
359 /// Written by the agent loop after each turn's `sentinel.current_risk()` call.
360 /// `PolicyGateExecutor::check_policy` reads it to downgrade `Allow` at `Critical`.
361 /// `u8` encoding: 0=Calm, 1=Elevated, 2=High, 3=Critical.
362 pub(crate) trajectory_risk_slot: zeph_tools::TrajectoryRiskSlot,
363 /// Pending risk signals from executor layers (spec 050 §2).
364 ///
365 /// `PolicyGateExecutor` and `ScopedToolExecutor` push signal codes here.
366 /// `begin_turn()` drains this queue into `trajectory.record()`.
367 pub(crate) trajectory_signal_queue: zeph_tools::RiskSignalQueue,
368 /// Persistent safety stream + LLM pre-execution probe (spec 050 Phase 2).
369 ///
370 /// `None` when `security.shadow_sentinel.enabled = false` (default).
371 /// When `Some`, `begin_turn()` calls `advance_turn()` to reset the per-turn probe counter.
372 pub(crate) shadow_sentinel:
373 Option<std::sync::Arc<crate::agent::shadow_sentinel::ShadowSentinel>>,
374 /// Per-turn multi-step attack chain accumulator.
375 ///
376 /// `None` by default. When `Some`, `begin_turn()` calls `reset()` to clear per-turn state.
377 /// The same `Arc` must be passed to `ShellExecutor::with_risk_chain` at build time.
378 pub(crate) risk_chain_accumulator: Option<std::sync::Arc<zeph_tools::RiskChainAccumulator>>,
379}
380
381/// Groups debug/diagnostics subsystems (dumper, trace collector, anomaly detector, logging config).
382pub(crate) struct DebugState {
383 pub(crate) debug_dumper: Option<crate::debug_dump::DebugDumper>,
384 pub(crate) dump_format: crate::debug_dump::DumpFormat,
385 pub(crate) trace_collector: Option<crate::debug_dump::trace::TracingCollector>,
386 /// Monotonically increasing counter for `process_user_message` calls.
387 /// Used to key spans in `trace_collector.active_iterations`.
388 pub(crate) iteration_counter: usize,
389 pub(crate) anomaly_detector: Option<zeph_tools::AnomalyDetector>,
390 /// Whether to emit `reasoning_amplification` warnings for quality failures from reasoning
391 /// models. Mirrors `AnomalyConfig::reasoning_model_warning`. Default: `true`.
392 pub(crate) reasoning_model_warning: bool,
393 pub(crate) logging_config: crate::config::LoggingConfig,
394 /// Base dump directory — stored so `/dump-format trace` can create a `TracingCollector` (CR-04).
395 pub(crate) dump_dir: Option<PathBuf>,
396 /// Service name for `TracingCollector` created via runtime format switch (CR-04).
397 pub(crate) trace_service_name: String,
398 /// Whether to redact in `TracingCollector` created via runtime format switch (CR-04).
399 pub(crate) trace_redact: bool,
400 /// User-defined resource attributes forwarded to `TracingCollector` (from `telemetry.trace_metadata`).
401 pub(crate) trace_metadata: std::collections::HashMap<String, String>,
402 /// Span ID of the currently executing iteration — used by LLM/tool span wiring (CR-01).
403 /// Set to `Some` at the start of `process_user_message`, cleared at end.
404 pub(crate) current_iteration_span_id: Option<[u8; 8]>,
405}
406
407/// Snapshot of the shell-level overlay baked in at startup.
408///
409/// Used in `reload_config` to detect when a hot-reload would produce a different shell
410/// restriction set than the one baked into the live `ShellExecutor` (M4 warn-on-divergence).
411#[derive(Debug, Clone, Default, PartialEq, Eq)]
412pub struct ShellOverlaySnapshot {
413 /// Sorted `blocked_commands` contributed by plugins.
414 pub blocked: Vec<String>,
415 /// Sorted `allowed_commands` after plugin intersection (empty if base was empty).
416 pub allowed: Vec<String>,
417}
418
419/// Runtime state for an active `/loop` session.
420///
421/// At most one loop is active at a time; `LifecycleState::user_loop` holds `Some` while
422/// the loop is running and `None` otherwise.
423pub(crate) struct LoopState {
424 /// The prompt text injected on each tick.
425 pub(crate) prompt: String,
426 /// Number of ticks fired so far.
427 pub(crate) iteration: u64,
428 /// Tick interval. `MissedTickBehavior::Skip` prevents burst catch-up.
429 pub(crate) interval: Interval,
430 /// Cancel handle. Dropped (and token cancelled) when loop is stopped.
431 pub(crate) cancel_tx: CancellationToken,
432}
433
434/// Groups agent lifecycle state: shutdown signaling, timing, and I/O notification channels.
435pub(crate) struct LifecycleState {
436 pub(crate) shutdown: watch::Receiver<bool>,
437 pub(crate) start_time: Instant,
438 pub(crate) cancel_signal: Arc<Notify>,
439 pub(crate) cancel_token: CancellationToken,
440 /// Handle to the cancel bridge task spawned each turn. Aborted before a new one is created
441 /// to prevent unbounded task accumulation across turns.
442 pub(crate) cancel_bridge_handle: Option<zeph_common::task_supervisor::BlockingHandle<()>>,
443 pub(crate) config_path: Option<PathBuf>,
444 pub(crate) config_reload_rx: Option<mpsc::Receiver<ConfigEvent>>,
445 /// Path to the plugins directory; used to re-apply overlays on hot-reload.
446 pub(crate) plugins_dir: PathBuf,
447 /// Shell overlay snapshot baked in at startup. Used to detect divergence on hot-reload.
448 pub(crate) startup_shell_overlay: ShellOverlaySnapshot,
449 /// Handle for live-rebuilding the `ShellExecutor`'s `blocked_commands` policy on hot-reload.
450 /// `None` when no `ShellExecutor` is in the executor chain (test harnesses, daemon-only modes).
451 pub(crate) shell_policy_handle: Option<zeph_tools::ShellPolicyHandle>,
452 pub(crate) warmup_ready: Option<watch::Receiver<bool>>,
453 pub(crate) update_notify_rx: Option<mpsc::Receiver<String>>,
454 pub(crate) custom_task_rx: Option<mpsc::Receiver<String>>,
455 /// Active `/loop` state. `None` when no loop is running.
456 pub(crate) user_loop: Option<LoopState>,
457 /// Last known process cwd. Compared after each tool call to detect changes.
458 pub(crate) last_known_cwd: PathBuf,
459 /// Receiver for file-change events from `FileChangeWatcher`. `None` when no paths configured.
460 pub(crate) file_changed_rx: Option<mpsc::Receiver<FileChangedEvent>>,
461 /// Keeps the `FileChangeWatcher` alive for the agent's lifetime. Dropping it aborts the watcher task.
462 pub(crate) file_watcher: Option<crate::file_watcher::FileChangeWatcher>,
463 /// Supervised background task manager. Owned by the agent; call `reap()` between turns
464 /// and `abort_all()` on shutdown.
465 pub(crate) supervisor: super::agent_supervisor::BackgroundSupervisor,
466 /// Per-turn completion notifier. `None` when `notifications.enabled = false`.
467 pub(crate) notifier: Option<crate::notifications::Notifier>,
468 /// Per-turn LLM request counter. Incremented by `process_response`; reset at turn start.
469 pub(crate) turn_llm_requests: u32,
470 /// Timestamp of the last turn that ended with `LlmError::NoProviders`.
471 ///
472 /// Used to gate `advance_context_lifecycle`: when all providers are down, context preparation
473 /// is skipped (degraded mode) until `no_providers_backoff_secs` has elapsed.
474 pub(crate) last_no_providers_at: Option<Instant>,
475 /// Completions from background shell runs waiting to be injected into the next turn.
476 ///
477 /// Drained at the top of `process_user_message_inner` after `supervisor.reap()`.
478 /// All pending completions and the real user message are merged into a **single**
479 /// user-role block to satisfy strict alternation requirements (Anthropic Messages API).
480 ///
481 /// Capacity is capped at `BACKGROUND_COMPLETION_BUFFER_CAP`. On overflow the oldest
482 /// entry is dropped and a placeholder is substituted so the LLM learns results were lost.
483 pub(crate) pending_background_completions:
484 VecDeque<zeph_tools::shell::background::BackgroundCompletion>,
485 /// Receiver end of the dedicated background-completion channel created alongside the
486 /// `ShellExecutor`. Polled at the top of each turn to drain completions into
487 /// `pending_background_completions`. `None` when no `ShellExecutor` is configured.
488 pub(crate) background_completion_rx:
489 Option<tokio::sync::mpsc::Receiver<zeph_tools::BackgroundCompletion>>,
490 /// Shared reference to the `ShellExecutor` used to query in-flight background run snapshots
491 /// for TUI metrics display. `None` when no `ShellExecutor` is wired (test harnesses, etc.).
492 pub(crate) shell_executor_handle: Option<std::sync::Arc<zeph_tools::ShellExecutor>>,
493 /// Session-level task supervisor, shared with bootstrap and TUI. Used to register
494 /// background agent tasks (cancel bridge, compaction, sidequest eviction) for
495 /// observability and graceful shutdown.
496 ///
497 /// Created with a fresh [`CancellationToken`] in `LifecycleState::new()` for test
498 /// harnesses; production code overwrites it via `Agent::with_task_supervisor`.
499 pub(crate) task_supervisor: Arc<zeph_common::TaskSupervisor>,
500}
501
502/// Minimal config snapshot needed to reconstruct a provider at runtime via `/provider <name>`.
503///
504/// Secrets are stored as plain strings because [`Secret`] intentionally does not implement
505/// `Clone`. They are re-wrapped in `Secret` when passed to `build_provider_for_switch`.
506pub struct ProviderConfigSnapshot {
507 pub claude_api_key: Option<String>,
508 pub openai_api_key: Option<String>,
509 pub gemini_api_key: Option<String>,
510 pub compatible_api_keys: std::collections::HashMap<String, String>,
511 pub llm_request_timeout_secs: u64,
512 pub embedding_model: String,
513 pub gonka_private_key: Option<Zeroizing<String>>,
514 pub gonka_address: Option<String>,
515 pub cocoon_access_hash: Option<String>,
516}
517
518/// Groups provider-related state: alternate providers, runtime switching, and compaction flags.
519pub(crate) struct ProviderState {
520 pub(crate) summary_provider: Option<AnyProvider>,
521 /// Shared slot for runtime model switching; set by external caller (e.g. ACP).
522 pub(crate) provider_override: Option<Arc<RwLock<Option<AnyProvider>>>>,
523 pub(crate) judge_provider: Option<AnyProvider>,
524 /// Dedicated provider for compaction probe LLM calls. Falls back to `summary_provider`
525 /// (or primary) when `None`.
526 pub(crate) probe_provider: Option<AnyProvider>,
527 /// Dedicated provider for `compress_context` LLM calls (#2356).
528 /// Falls back to the primary provider when `None`.
529 pub(crate) compress_provider: Option<AnyProvider>,
530 pub(crate) cached_prompt_tokens: u64,
531 /// Whether the active provider has server-side compaction enabled (Claude compact-2026-01-12).
532 /// When true, client-side compaction is skipped.
533 pub(crate) server_compaction_active: bool,
534 pub(crate) stt: Option<Box<dyn SpeechToText>>,
535 /// Snapshot of `[[llm.providers]]` entries for runtime `/provider` switching.
536 pub(crate) provider_pool: Vec<ProviderEntry>,
537 /// Resolved secrets and timeout settings needed to reconstruct providers at runtime.
538 pub(crate) provider_config_snapshot: Option<ProviderConfigSnapshot>,
539}
540
541/// Groups metrics and cost tracking state.
542pub(crate) struct MetricsState {
543 pub(crate) metrics_tx: Option<watch::Sender<MetricsSnapshot>>,
544 pub(crate) cost_tracker: Option<CostTracker>,
545 pub(crate) token_counter: Arc<TokenCounter>,
546 /// Set to `true` when Claude extended context (`enable_extended_context = true`) is active.
547 /// Read from config at build time, not derived from provider internals.
548 pub(crate) extended_context: bool,
549 /// Shared classifier latency ring buffer. Populated by `ContentSanitizer` (injection, PII)
550 /// and `LlmClassifier` (feedback). `None` when classifiers are not configured.
551 pub(crate) classifier_metrics: Option<Arc<zeph_llm::ClassifierMetrics>>,
552 /// Rolling window of per-turn latency samples (last 10 turns).
553 pub(crate) timing_window: std::collections::VecDeque<crate::metrics::TurnTimings>,
554 /// Accumulator for the current turn's timings. Flushed at turn end via `flush_turn_timings`.
555 pub(crate) pending_timings: crate::metrics::TurnTimings,
556 /// Optional histogram recorder for per-event Prometheus observations.
557 /// `None` when the `prometheus` feature is disabled or metrics are not enabled.
558 pub(crate) histogram_recorder: Option<std::sync::Arc<dyn crate::metrics::HistogramRecorder>>,
559}
560
561/// Groups task orchestration and subagent state.
562#[derive(Default)]
563pub(crate) struct OrchestrationState {
564 /// On `OrchestrationState` (not `ProviderState`) because this provider is used exclusively
565 /// by `LlmPlanner` during orchestration, not shared across subsystems.
566 pub(crate) planner_provider: Option<AnyProvider>,
567 /// Provider for `PlanVerifier` LLM calls. `None` falls back to `orchestrator_provider`
568 /// then the primary provider.
569 pub(crate) verify_provider: Option<AnyProvider>,
570 /// Provider for scheduling-tier LLM calls (aggregation, predicate evaluation, verification
571 /// fallback). `None` falls back to the primary provider.
572 /// Set from `config.orchestration.orchestrator_provider` at startup.
573 pub(crate) orchestrator_provider: Option<AnyProvider>,
574 /// Provider for predicate gate evaluation. `None` falls back to `orchestrator_provider`
575 /// then `verify_provider` then primary.
576 pub(crate) predicate_provider: Option<AnyProvider>,
577 /// Graph waiting for `/plan confirm` before execution starts.
578 pub(crate) pending_graph: Option<zeph_orchestration::TaskGraph>,
579 /// Cancellation token for the currently executing plan. `None` when no plan is running.
580 /// Created fresh in `handle_plan_confirm()`, cancelled in `handle_plan_cancel()`.
581 ///
582 /// # Known limitation
583 ///
584 /// Token plumbing is ready; the delivery path requires the agent message loop to be
585 /// restructured so `/plan cancel` can be received while `run_scheduler_loop` holds
586 /// `&mut self`. See follow-up issue #1603 (SEC-M34-002).
587 pub(crate) plan_cancel_token: Option<CancellationToken>,
588 /// Manages spawned sub-agents.
589 pub(crate) subagent_manager: Option<zeph_subagent::SubAgentManager>,
590 pub(crate) subagent_config: crate::config::SubAgentConfig,
591 pub(crate) orchestration_config: crate::config::OrchestrationConfig,
592 /// Lazily initialized plan template cache. `None` until first use or when
593 /// memory (`SQLite`) is unavailable.
594 #[allow(dead_code)]
595 pub(crate) plan_cache: Option<zeph_orchestration::PlanCache>,
596 /// Goal embedding from the most recent `plan_with_cache()` call. Consumed by
597 /// `finalize_plan_execution()` to cache the completed plan template.
598 pub(crate) pending_goal_embedding: Option<Vec<f32>>,
599 /// `AdaptOrch` topology advisor — `None` when `[orchestration.adaptorch]` is disabled.
600 pub(crate) topology_advisor: Option<std::sync::Arc<zeph_orchestration::TopologyAdvisor>>,
601 /// Last `AdaptOrch` verdict; carried from `handle_plan_goal_as_string` to scheduler loop
602 /// for `record_outcome`.
603 #[allow(dead_code)] // read via .take() in plan.rs; clippy false positive
604 pub(crate) last_advisor_verdict: Option<zeph_orchestration::AdvisorVerdict>,
605 /// Task graph persistence handle. `None` when no `SemanticMemory` was
606 /// attached via `with_memory`, or when
607 /// `OrchestrationConfig::persistence_enabled` is `false`. When `Some`, the
608 /// scheduler loop snapshots the graph once per tick and `/plan resume <id>`
609 /// rehydrates from disk.
610 pub(crate) graph_persistence: Option<
611 zeph_orchestration::GraphPersistence<zeph_memory::store::graph_store::TaskGraphStore>,
612 >,
613 /// Named execution environment for the current orchestration task.
614 ///
615 /// Set by the scheduler when dispatching a `TaskNode` that has
616 /// `execution_environment: Some(name)`. Cleared between tasks. When `Some`,
617 /// `prepare_tool_dispatch` injects an [`ExecutionContext`] named `name` into
618 /// every `ToolCall` so that `ShellExecutor::resolve_context` uses the right env.
619 pub(crate) task_execution_env: Option<String>,
620}
621
622/// Groups instruction hot-reload state.
623#[derive(Default)]
624pub(crate) struct InstructionState {
625 pub(crate) blocks: Vec<InstructionBlock>,
626 pub(crate) reload_rx: Option<mpsc::Receiver<InstructionEvent>>,
627 pub(crate) reload_state: Option<InstructionReloadState>,
628}
629
630/// Groups experiment feature state (gated behind `experiments` feature flag).
631pub(crate) struct ExperimentState {
632 pub(crate) config: crate::config::ExperimentConfig,
633 /// Cancellation token for a running experiment session. `Some` means an experiment is active.
634 pub(crate) cancel: Option<tokio_util::sync::CancellationToken>,
635 /// `JoinHandle` for the background experiment task. Stored so shutdown can abort it if the
636 /// `CancellationToken` signal is not observed in time (e.g. the task is blocked on I/O).
637 pub(crate) handle: Option<tokio::task::JoinHandle<()>>,
638 /// Pre-built config snapshot used as the experiment baseline (agent path).
639 pub(crate) baseline: zeph_experiments::ConfigSnapshot,
640 /// Dedicated judge provider for evaluation. When `Some`, the evaluator uses this provider
641 /// instead of the agent's primary provider, eliminating self-judge bias.
642 pub(crate) eval_provider: Option<AnyProvider>,
643 /// Receives completion/error messages from the background experiment engine task.
644 /// Always present so the select! branch compiles unconditionally.
645 pub(crate) notify_rx: Option<tokio::sync::mpsc::Receiver<String>>,
646 /// Sender end paired with `experiment_notify_rx`. Cloned into the background task.
647 pub(crate) notify_tx: tokio::sync::mpsc::Sender<String>,
648}
649
650/// Groups context-compression feature state (gated behind `context-compression` feature flag).
651#[derive(Default)]
652pub(crate) struct CompressionState {
653 /// Cached task goal for TaskAware/MIG pruning. Set by `maybe_compact()`,
654 /// invalidated when the last user message hash changes.
655 pub(crate) current_task_goal: Option<String>,
656 /// Hash of the last user message when `current_task_goal` was populated.
657 pub(crate) task_goal_user_msg_hash: Option<u64>,
658 /// Pending background task for goal extraction. Spawned when the user message hash changes;
659 /// result applied at the start of the next Soft compaction (#1909).
660 pub(crate) pending_task_goal:
661 Option<zeph_common::task_supervisor::BlockingHandle<Option<String>>>,
662 /// Pending `SideQuest` eviction result from the background LLM call spawned last turn.
663 /// Applied at the START of the next turn before compaction (PERF-1 fix).
664 pub(crate) pending_sidequest_result:
665 Option<zeph_common::task_supervisor::BlockingHandle<Option<Vec<usize>>>>,
666 /// In-memory subgoal registry for `Subgoal`/`SubgoalMig` pruning strategies (#2022).
667 pub(crate) subgoal_registry: zeph_agent_context::SubgoalRegistry,
668 /// Pending background subgoal extraction task.
669 pub(crate) pending_subgoal: Option<
670 zeph_common::task_supervisor::BlockingHandle<
671 Option<zeph_agent_context::SubgoalExtractionResult>,
672 >,
673 >,
674 /// Hash of the last user message when subgoal extraction was scheduled.
675 pub(crate) subgoal_user_msg_hash: Option<u64>,
676 /// Shared typed-page state (#3630). `None` when `typed_pages.enabled = false`.
677 pub(crate) typed_pages_state: Option<Arc<zeph_context::typed_page::TypedPagesState>>,
678}
679
680/// Groups runtime tool filtering, dependency tracking, and iteration bookkeeping.
681#[derive(Default)]
682pub(crate) struct ToolState {
683 /// Dynamic tool schema filter: pre-computed tool embeddings for per-turn filtering (#2020).
684 pub(crate) tool_schema_filter: Option<zeph_tools::ToolSchemaFilter>,
685 /// Cached filtered tool IDs for the current user turn.
686 pub(crate) cached_filtered_tool_ids: Option<HashSet<String>>,
687 /// Tool dependency graph for sequential tool availability (#2024).
688 pub(crate) dependency_graph: Option<zeph_tools::ToolDependencyGraph>,
689 /// Always-on tool IDs, mirrored from the tool schema filter for dependency gate bypass.
690 pub(crate) dependency_always_on: HashSet<String>,
691 /// Tool IDs that completed successfully in the current session.
692 pub(crate) completed_tool_ids: HashSet<String>,
693 /// Current tool loop iteration index within the active user turn.
694 pub(crate) current_tool_iteration: usize,
695 /// PASTE pattern store for tool invocation history and prediction (#3642).
696 ///
697 /// `Some` only when `config.tools.speculative.mode` is `Pattern` or `Both`.
698 pub(crate) pattern_store: Option<Arc<crate::agent::speculative::paste::PatternStore>>,
699 /// Per-turn mapping from tool name to `(skill_name, skill_hash)`, populated at skill
700 /// activation and used by `observe()` to attribute tool completions to their owning skill.
701 pub(crate) tool_to_skill: HashMap<String, (String, String)>,
702 /// Last tool executed per skill in the current turn, keyed by skill name.
703 /// Used as `prev_tool` for PASTE pattern transition recording.
704 pub(crate) last_tool_per_skill: HashMap<String, String>,
705}
706
707/// Groups per-session I/O and policy state.
708pub(crate) struct SessionState {
709 pub(crate) env_context: EnvironmentContext,
710 /// Timestamp of the last assistant message appended to context.
711 /// Used by time-based microcompact to compute session idle gap (#2699).
712 /// `None` before the first assistant response.
713 pub(crate) last_assistant_at: Option<Instant>,
714 pub(crate) response_cache: Option<std::sync::Arc<zeph_memory::ResponseCache>>,
715 /// Parent tool call ID when this agent runs as a subagent inside another agent session.
716 /// Propagated into every `LoopbackEvent::ToolStart` / `ToolOutput` so the IDE can build
717 /// a subagent hierarchy.
718 pub(crate) parent_tool_use_id: Option<String>,
719 /// Current-turn intent snapshot for VIGIL. `None` between turns.
720 ///
721 /// Set at the top of `process_user_message` (before any tool call) to the first 1024 chars
722 /// of the user message. Cleared at `end_turn`, on `/clear`, and on any turn-abort path.
723 /// Never shared across turns or propagated into subagents.
724 pub(crate) current_turn_intent: Option<String>,
725 /// Optional status channel for sending spinner/status messages to TUI or stderr.
726 pub(crate) status_tx: Option<tokio::sync::mpsc::UnboundedSender<String>>,
727 /// LSP context injection hooks. Fires after native tool execution, injects
728 /// diagnostics/hover notes as `Role::System` messages before the next LLM call.
729 pub(crate) lsp_hooks: Option<crate::lsp_hooks::LspHookRunner>,
730 /// Snapshot of the policy config for `/policy` command inspection.
731 pub(crate) policy_config: Option<zeph_tools::PolicyConfig>,
732 /// `CwdChanged` hook definitions extracted from `[hooks]` config.
733 pub(crate) hooks_config: HooksConfigSnapshot,
734 /// Whether the current turn originates from a Telegram guest query (`guest_message` update).
735 ///
736 /// When `true`, the agent prompt includes a brief guest-context annotation, and the response
737 /// is delivered via `answerGuestQuery` instead of `sendMessage`.
738 pub(crate) is_guest_context: bool,
739}
740
741/// Extracted hook lists from `[hooks]` config, stored in `SessionState`.
742#[derive(Default)]
743pub(crate) struct HooksConfigSnapshot {
744 /// Hooks fired when working directory changes.
745 pub(crate) cwd_changed: Vec<zeph_config::HookDef>,
746 /// Hooks fired when a watched file changes.
747 pub(crate) file_changed_hooks: Vec<zeph_config::HookDef>,
748 /// Hooks fired when a tool execution is blocked by a `RuntimeLayer::before_tool` check.
749 pub(crate) permission_denied: Vec<zeph_config::HookDef>,
750 /// Hooks fired after each agent turn completes (#3327).
751 ///
752 /// Populated from `HooksConfig::turn_complete` at session construction. Shares the
753 /// `Notifier::should_fire` gate when a notifier is configured; fires on every completion
754 /// when no notifier is present.
755 pub(crate) turn_complete: Vec<zeph_config::HookDef>,
756 /// Hooks fired before each tool execution, matched by tool name pattern.
757 pub(crate) pre_tool_use: Vec<zeph_config::HookMatcher>,
758 /// Hooks fired after each tool execution completes, matched by tool name pattern.
759 pub(crate) post_tool_use: Vec<zeph_config::HookMatcher>,
760}
761
762// Groups message buffering and image staging state.
763pub(crate) struct MessageState {
764 pub(crate) messages: Vec<Message>,
765 // QueuedMessage is pub(super) in message_queue — same visibility as this struct; lint suppressed.
766 #[allow(private_interfaces)]
767 pub(crate) message_queue: VecDeque<QueuedMessage>,
768 /// Image parts staged by `/image` commands, attached to the next user message.
769 pub(crate) pending_image_parts: Vec<zeph_llm::provider::MessagePart>,
770 /// DB row ID of the most recently persisted message. Set by `persist_message`;
771 /// consumed by `push_message` call sites to populate `metadata.db_id` on in-memory messages.
772 pub(crate) last_persisted_message_id: Option<i64>,
773 /// DB message IDs pending hide after deferred tool pair summarization.
774 pub(crate) deferred_db_hide_ids: Vec<i64>,
775 /// Summary texts pending insertion after deferred tool pair summarization.
776 pub(crate) deferred_db_summaries: Vec<String>,
777}
778
779impl McpState {
780 /// Write the **full** `self.tools` set to the shared executor `RwLock`.
781 ///
782 /// This is the first of two writers to `shared_tools`. Within a turn this method must run
783 /// **before** `apply_pruned_tools`, which writes the pruned subset. The normal call order
784 /// guarantees this: tool-list change events call this method, and pruning runs later inside
785 /// `rebuild_system_prompt`. See also: `apply_pruned_tools`.
786 pub(crate) fn sync_executor_tools(&self) {
787 if let Some(ref shared) = self.shared_tools {
788 shared.write().clone_from(&self.tools);
789 }
790 }
791
792 /// Write the **pruned** tool subset to the shared executor `RwLock`.
793 ///
794 /// Must only be called **after** `sync_executor_tools` has established the full tool set for
795 /// the current turn. `self.tools` (the full set) is intentionally **not** modified.
796 ///
797 /// This method must **NOT** call `sync_executor_tools` internally — doing so would overwrite
798 /// the pruned subset with the full set. See also: `sync_executor_tools`.
799 pub(crate) fn apply_pruned_tools(&self, pruned: Vec<zeph_mcp::McpTool>) {
800 debug_assert!(
801 pruned.iter().all(|p| self
802 .tools
803 .iter()
804 .any(|t| t.server_id == p.server_id && t.name == p.name)),
805 "pruned set must be a subset of self.tools"
806 );
807 if let Some(ref shared) = self.shared_tools {
808 *shared.write() = pruned;
809 }
810 }
811
812 #[cfg(test)]
813 pub(crate) fn tool_count(&self) -> usize {
814 self.tools.len()
815 }
816}
817
818impl IndexState {
819 #[tracing::instrument(name = "core.index.fetch_code_rag", skip(self), fields(%query, token_budget))]
820 pub(crate) async fn fetch_code_rag(
821 &self,
822 query: &str,
823 token_budget: usize,
824 ) -> Result<Option<String>, crate::agent::error::AgentError> {
825 let Some(retriever) = &self.retriever else {
826 return Ok(None);
827 };
828 if token_budget == 0 {
829 return Ok(None);
830 }
831
832 let result = retriever
833 .retrieve(query, token_budget)
834 .await
835 .map_err(|e| crate::agent::error::AgentError::ContextError(format!("{e:#}")))?;
836 let context_text = zeph_index::retriever::format_as_context(&result);
837
838 if context_text.is_empty() {
839 Ok(None)
840 } else {
841 tracing::debug!(
842 strategy = ?result.strategy,
843 chunks = result.chunks.len(),
844 tokens = result.total_tokens,
845 "code context fetched"
846 );
847 Ok(Some(context_text))
848 }
849 }
850}
851
852impl DebugState {
853 pub(crate) fn start_iteration_span(&mut self, iteration_index: usize, text: &str) {
854 if let Some(ref mut tc) = self.trace_collector {
855 tc.begin_iteration(iteration_index, text);
856 self.current_iteration_span_id = tc.current_iteration_span_id(iteration_index);
857 }
858 }
859
860 pub(crate) fn end_iteration_span(
861 &mut self,
862 iteration_index: usize,
863 status: crate::debug_dump::trace::SpanStatus,
864 ) {
865 if let Some(ref mut tc) = self.trace_collector {
866 tc.end_iteration(iteration_index, status);
867 }
868 self.current_iteration_span_id = None;
869 }
870
871 pub(crate) fn switch_format(&mut self, new_format: crate::debug_dump::DumpFormat) {
872 let was_trace = self.dump_format == crate::debug_dump::DumpFormat::Trace;
873 let now_trace = new_format == crate::debug_dump::DumpFormat::Trace;
874
875 if now_trace
876 && !was_trace
877 && let Some(ref dump_dir) = self.dump_dir.clone()
878 {
879 let service_name = self.trace_service_name.clone();
880 let redact = self.trace_redact;
881 let trace_metadata = self.trace_metadata.clone();
882 match crate::debug_dump::trace::TracingCollector::new(
883 dump_dir.as_path(),
884 &service_name,
885 trace_metadata,
886 redact,
887 None,
888 ) {
889 Ok(collector) => {
890 self.trace_collector = Some(collector);
891 }
892 Err(e) => {
893 tracing::warn!(error = %e, "failed to create TracingCollector on format switch");
894 }
895 }
896 }
897 if was_trace
898 && !now_trace
899 && let Some(mut tc) = self.trace_collector.take()
900 {
901 tc.finish();
902 }
903
904 self.dump_format = new_format;
905 }
906
907 pub(crate) fn write_chat_debug_dump(
908 &self,
909 dump_id: Option<u32>,
910 result: &zeph_llm::provider::ChatResponse,
911 pii_filter: &zeph_sanitizer::pii::PiiFilter,
912 ) {
913 let Some((d, id)) = self.debug_dumper.as_ref().zip(dump_id) else {
914 return;
915 };
916 let raw = match result {
917 zeph_llm::provider::ChatResponse::Text(t) => t.clone(),
918 zeph_llm::provider::ChatResponse::ToolUse {
919 text, tool_calls, ..
920 } => {
921 let calls = serde_json::to_string_pretty(tool_calls).unwrap_or_default();
922 format!(
923 "{}\n\n---TOOL_CALLS---\n{calls}",
924 text.as_deref().unwrap_or("")
925 )
926 }
927 };
928 let text = if pii_filter.is_enabled() {
929 pii_filter.scrub(&raw).into_owned()
930 } else {
931 raw
932 };
933 d.dump_response(id, &text);
934 }
935}
936
937impl Default for McpState {
938 fn default() -> Self {
939 Self {
940 tools: Vec::new(),
941 registry: None,
942 manager: None,
943 allowed_commands: Vec::new(),
944 max_dynamic: 10,
945 elicitation_rx: None,
946 shared_tools: None,
947 tool_rx: None,
948 server_outcomes: Vec::new(),
949 pruning_cache: zeph_mcp::PruningCache::new(),
950 pruning_provider: None,
951 pruning_enabled: false,
952 pruning_params: zeph_mcp::PruningParams::default(),
953 semantic_index: None,
954 discovery_strategy: zeph_mcp::ToolDiscoveryStrategy::default(),
955 discovery_params: zeph_mcp::DiscoveryParams::default(),
956 discovery_provider: None,
957 elicitation_warn_sensitive_fields: true,
958 pending_semantic_rebuild: false,
959 }
960 }
961}
962
963impl Default for IndexState {
964 fn default() -> Self {
965 Self {
966 retriever: None,
967 repo_map_tokens: 0,
968 cached_repo_map: None,
969 repo_map_ttl: std::time::Duration::from_mins(5),
970 }
971 }
972}
973
974impl Default for DebugState {
975 fn default() -> Self {
976 Self {
977 debug_dumper: None,
978 dump_format: crate::debug_dump::DumpFormat::default(),
979 trace_collector: None,
980 iteration_counter: 0,
981 anomaly_detector: None,
982 reasoning_model_warning: true,
983 logging_config: crate::config::LoggingConfig::default(),
984 dump_dir: None,
985 trace_service_name: String::new(),
986 trace_redact: true,
987 trace_metadata: std::collections::HashMap::new(),
988 current_iteration_span_id: None,
989 }
990 }
991}
992
993impl Default for FeedbackState {
994 fn default() -> Self {
995 Self {
996 detector: zeph_agent_feedback::FeedbackDetector::new(0.6),
997 judge: None,
998 llm_classifier: None,
999 }
1000 }
1001}
1002
1003/// Goal lifecycle feature configuration stored in `RuntimeConfig`.
1004#[derive(Debug, Clone)]
1005pub(crate) struct GoalRuntimeConfig {
1006 /// Whether goal tracking is enabled.
1007 pub(crate) enabled: bool,
1008 /// Maximum allowed length (in Unicode chars) of goal text at creation.
1009 pub(crate) max_text_chars: usize,
1010 /// Default token budget for new goals (`None` = unlimited).
1011 pub(crate) default_token_budget: Option<u64>,
1012 /// Whether to inject the active goal block into the volatile system prompt region.
1013 pub(crate) inject_into_system_prompt: bool,
1014 /// Whether autonomous multi-turn execution is permitted.
1015 pub(crate) autonomous_enabled: bool,
1016 /// Maximum turns per autonomous session.
1017 pub(crate) autonomous_max_turns: u32,
1018 /// Provider name for the supervisor LLM call (`None` = use main provider).
1019 pub(crate) supervisor_provider: Option<zeph_config::ProviderName>,
1020 /// Turns between supervisor verification checks.
1021 pub(crate) verify_interval: u32,
1022 /// Timeout for a single supervisor call in seconds.
1023 pub(crate) supervisor_timeout_secs: u64,
1024 /// Consecutive stuck-detection threshold before aborting.
1025 pub(crate) max_stuck_count: u32,
1026 /// Wall-clock timeout in seconds for a single autonomous LLM turn.
1027 pub(crate) autonomous_turn_timeout_secs: u64,
1028 /// Maximum consecutive supervisor verification failures before pausing the session.
1029 pub(crate) max_supervisor_fail_count: u32,
1030}
1031
1032impl Default for GoalRuntimeConfig {
1033 fn default() -> Self {
1034 Self {
1035 enabled: false,
1036 max_text_chars: 2000,
1037 default_token_budget: None,
1038 inject_into_system_prompt: true,
1039 autonomous_enabled: false,
1040 autonomous_max_turns: 20,
1041 supervisor_provider: None,
1042 verify_interval: 5,
1043 supervisor_timeout_secs: 30,
1044 max_stuck_count: 3,
1045 autonomous_turn_timeout_secs: 300,
1046 max_supervisor_fail_count: 3,
1047 }
1048 }
1049}
1050
1051impl Default for RuntimeConfig {
1052 fn default() -> Self {
1053 Self {
1054 security: SecurityConfig::default(),
1055 timeouts: TimeoutConfig::default(),
1056 model_name: String::new(),
1057 active_provider_name: String::new(),
1058 permission_policy: zeph_tools::PermissionPolicy::default(),
1059 redact_credentials: true,
1060 rate_limiter: super::rate_limiter::ToolRateLimiter::new(
1061 super::rate_limiter::RateLimitConfig::default(),
1062 ),
1063 semantic_cache_enabled: false,
1064 semantic_cache_threshold: 0.95,
1065 semantic_cache_max_candidates: 10,
1066 dependency_config: zeph_tools::DependencyConfig::default(),
1067 adversarial_policy_info: None,
1068 spawn_depth: 0,
1069 budget_hint_enabled: true,
1070 channel_skills: zeph_config::ChannelSkillsConfig::default(),
1071 channel_tool_allowlist: None,
1072 loop_min_interval_secs: 5,
1073 layers: Vec::new(),
1074 supervisor_config: crate::config::TaskSupervisorConfig::default(),
1075 recap_config: zeph_config::RecapConfig::default(),
1076 acp_config: zeph_config::AcpConfig::default(),
1077 auto_recap_shown: false,
1078 msg_count_at_resume: 0,
1079 acp_subagent_spawn_fn: None,
1080 channel_type: String::new(),
1081 provider_persistence_enabled: true,
1082 goals: GoalRuntimeConfig::default(),
1083 }
1084 }
1085}
1086
1087impl SessionState {
1088 pub(crate) fn new() -> Self {
1089 Self {
1090 env_context: EnvironmentContext::gather(""),
1091 last_assistant_at: None,
1092 response_cache: None,
1093 parent_tool_use_id: None,
1094 current_turn_intent: None,
1095 status_tx: None,
1096 lsp_hooks: None,
1097 policy_config: None,
1098 hooks_config: HooksConfigSnapshot::default(),
1099 is_guest_context: false,
1100 }
1101 }
1102}
1103
1104impl SkillState {
1105 pub(crate) fn new(
1106 registry: Arc<RwLock<SkillRegistry>>,
1107 matcher: Option<SkillMatcherBackend>,
1108 max_active_skills: usize,
1109 last_skills_prompt: String,
1110 ) -> Self {
1111 Self {
1112 registry,
1113 trust_snapshot: Arc::new(RwLock::new(HashMap::new())),
1114 skill_paths: Vec::new(),
1115 managed_dir: None,
1116 trust_config: crate::config::TrustConfig::default(),
1117 matcher,
1118 max_active_skills,
1119 disambiguation_threshold: 0.20,
1120 min_injection_score: 0.20,
1121 embedding_model: String::new(),
1122 skill_reload_rx: None,
1123 plugin_dirs_supplier: None,
1124 active_skill_names: Vec::new(),
1125 last_skills_prompt,
1126 prompt_mode: crate::config::SkillPromptMode::Auto,
1127 available_custom_secrets: HashMap::new(),
1128 cosine_weight: 0.7,
1129 hybrid_search: true,
1130 bm25_index: None,
1131 two_stage_matching: false,
1132 confusability_threshold: 0.0,
1133 rl_head: None,
1134 rl_weight: 0.3,
1135 rl_warmup_updates: 50,
1136 generation_output_dir: None,
1137 generation_provider_name: String::new(),
1138 disambiguate_provider_name: String::new(),
1139 generation_timeout_ms: 60_000,
1140 skill_evaluator: None,
1141 eval_weights: zeph_skills::evaluator::EvaluationWeights::default(),
1142 eval_threshold: 0.60,
1143 }
1144 }
1145}
1146
1147impl LifecycleState {
1148 pub(crate) fn new() -> Self {
1149 let (_tx, rx) = watch::channel(false);
1150 Self {
1151 shutdown: rx,
1152 start_time: Instant::now(),
1153 cancel_signal: Arc::new(tokio::sync::Notify::new()),
1154 cancel_token: tokio_util::sync::CancellationToken::new(),
1155 cancel_bridge_handle: None,
1156 config_path: None,
1157 config_reload_rx: None,
1158 plugins_dir: PathBuf::new(),
1159 startup_shell_overlay: ShellOverlaySnapshot::default(),
1160 shell_policy_handle: None,
1161 warmup_ready: None,
1162 update_notify_rx: None,
1163 custom_task_rx: None,
1164 user_loop: None,
1165 last_known_cwd: std::env::current_dir().unwrap_or_default(),
1166 file_changed_rx: None,
1167 file_watcher: None,
1168 supervisor: super::agent_supervisor::BackgroundSupervisor::new(
1169 &crate::config::TaskSupervisorConfig::default(),
1170 None,
1171 ),
1172 notifier: None,
1173 turn_llm_requests: 0,
1174 last_no_providers_at: None,
1175 pending_background_completions: VecDeque::new(),
1176 background_completion_rx: None,
1177 shell_executor_handle: None,
1178 task_supervisor: Arc::new(zeph_common::TaskSupervisor::new(
1179 tokio_util::sync::CancellationToken::new(),
1180 )),
1181 }
1182 }
1183}
1184
1185impl ProviderState {
1186 pub(crate) fn new(initial_prompt_tokens: u64) -> Self {
1187 Self {
1188 summary_provider: None,
1189 provider_override: None,
1190 judge_provider: None,
1191 probe_provider: None,
1192 compress_provider: None,
1193 cached_prompt_tokens: initial_prompt_tokens,
1194 server_compaction_active: false,
1195 stt: None,
1196 provider_pool: Vec::new(),
1197 provider_config_snapshot: None,
1198 }
1199 }
1200}
1201
1202impl MetricsState {
1203 pub(crate) fn new(token_counter: Arc<zeph_memory::TokenCounter>) -> Self {
1204 Self {
1205 metrics_tx: None,
1206 cost_tracker: None,
1207 token_counter,
1208 extended_context: false,
1209 classifier_metrics: None,
1210 timing_window: std::collections::VecDeque::new(),
1211 pending_timings: crate::metrics::TurnTimings::default(),
1212 histogram_recorder: None,
1213 }
1214 }
1215}
1216
1217impl ExperimentState {
1218 pub(crate) fn new() -> Self {
1219 let (notify_tx, notify_rx) = tokio::sync::mpsc::channel::<String>(4);
1220 Self {
1221 config: crate::config::ExperimentConfig::default(),
1222 cancel: None,
1223 handle: None,
1224 baseline: zeph_experiments::ConfigSnapshot::default(),
1225 eval_provider: None,
1226 notify_rx: Some(notify_rx),
1227 notify_tx,
1228 }
1229 }
1230}
1231
1232pub(super) mod security;
1233pub(super) mod skill;
1234
1235#[cfg(test)]
1236mod tests;