zeph-core 0.13.0

Core agent loop, configuration, context builder, metrics, and vault for Zeph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::path::PathBuf;
use std::sync::Arc;

use tokio::sync::{Notify, mpsc, watch};
use zeph_llm::any::AnyProvider;
use zeph_llm::provider::LlmProvider;

use super::Agent;
use crate::channel::Channel;
use crate::config::{LearningConfig, SecurityConfig, TimeoutConfig};
use crate::config_watcher::ConfigEvent;
use crate::context::ContextBudget;
use crate::cost::CostTracker;
use crate::instructions::{InstructionEvent, InstructionReloadState};
use crate::metrics::MetricsSnapshot;
use zeph_memory::semantic::SemanticMemory;
use zeph_skills::watcher::SkillEvent;

impl<C: Channel> Agent<C> {
    #[must_use]
    pub fn with_autosave_config(mut self, autosave_assistant: bool, min_length: usize) -> Self {
        self.memory_state.autosave_assistant = autosave_assistant;
        self.memory_state.autosave_min_length = min_length;
        self
    }

    #[must_use]
    pub fn with_tool_call_cutoff(mut self, cutoff: usize) -> Self {
        self.memory_state.tool_call_cutoff = cutoff;
        self
    }

    #[must_use]
    pub fn with_response_cache(
        mut self,
        cache: std::sync::Arc<zeph_memory::ResponseCache>,
    ) -> Self {
        self.response_cache = Some(cache);
        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.
    #[must_use]
    pub fn with_parent_tool_use_id(mut self, id: impl Into<String>) -> Self {
        self.parent_tool_use_id = Some(id.into());
        self
    }

    #[must_use]
    pub fn with_stt(mut self, stt: Box<dyn zeph_llm::stt::SpeechToText>) -> Self {
        self.stt = Some(stt);
        self
    }

    #[must_use]
    pub fn with_update_notifications(mut self, rx: mpsc::Receiver<String>) -> Self {
        self.update_notify_rx = Some(rx);
        self
    }

    #[must_use]
    pub fn with_custom_task_rx(mut self, rx: mpsc::Receiver<String>) -> Self {
        self.custom_task_rx = Some(rx);
        self
    }

    /// Wrap the current tool executor with an additional executor via `CompositeExecutor`.
    #[must_use]
    pub fn add_tool_executor(
        mut self,
        extra: impl zeph_tools::executor::ToolExecutor + 'static,
    ) -> Self {
        let existing = Arc::clone(&self.tool_executor);
        let combined = zeph_tools::CompositeExecutor::new(zeph_tools::DynExecutor(existing), extra);
        self.tool_executor = Arc::new(combined);
        self
    }

    #[must_use]
    pub fn with_max_tool_iterations(mut self, max: usize) -> Self {
        self.tool_orchestrator.max_iterations = max;
        self
    }

    #[must_use]
    pub fn with_memory(
        mut self,
        memory: Arc<SemanticMemory>,
        conversation_id: zeph_memory::ConversationId,
        history_limit: u32,
        recall_limit: usize,
        summarization_threshold: usize,
    ) -> Self {
        self.memory_state.memory = Some(memory);
        self.memory_state.conversation_id = Some(conversation_id);
        self.memory_state.history_limit = history_limit;
        self.memory_state.recall_limit = recall_limit;
        self.memory_state.summarization_threshold = summarization_threshold;
        self.update_metrics(|m| {
            m.qdrant_available = false;
            m.sqlite_conversation_id = Some(conversation_id);
        });
        self
    }

    #[must_use]
    pub fn with_embedding_model(mut self, model: String) -> Self {
        self.skill_state.embedding_model = model;
        self
    }

    #[must_use]
    pub fn with_disambiguation_threshold(mut self, threshold: f32) -> Self {
        self.skill_state.disambiguation_threshold = threshold;
        self
    }

    #[must_use]
    pub fn with_skill_prompt_mode(mut self, mode: crate::config::SkillPromptMode) -> Self {
        self.skill_state.prompt_mode = mode;
        self
    }

    #[must_use]
    pub fn with_document_config(mut self, config: crate::config::DocumentConfig) -> Self {
        self.memory_state.document_config = config;
        self
    }

    #[must_use]
    pub fn with_anomaly_detector(mut self, detector: zeph_tools::AnomalyDetector) -> Self {
        self.anomaly_detector = Some(detector);
        self
    }

    #[must_use]
    pub fn with_instruction_blocks(
        mut self,
        blocks: Vec<crate::instructions::InstructionBlock>,
    ) -> Self {
        self.instruction_blocks = blocks;
        self
    }

    #[must_use]
    pub fn with_instruction_reload(
        mut self,
        rx: mpsc::Receiver<InstructionEvent>,
        state: InstructionReloadState,
    ) -> Self {
        self.instruction_reload_rx = Some(rx);
        self.instruction_reload_state = Some(state);
        self
    }

    #[must_use]
    pub fn with_shutdown(mut self, rx: watch::Receiver<bool>) -> Self {
        self.shutdown = rx;
        self
    }

    #[must_use]
    pub fn with_skill_reload(
        mut self,
        paths: Vec<PathBuf>,
        rx: mpsc::Receiver<SkillEvent>,
    ) -> Self {
        self.skill_state.skill_paths = paths;
        self.skill_state.skill_reload_rx = Some(rx);
        self
    }

    #[must_use]
    pub fn with_managed_skills_dir(mut self, dir: PathBuf) -> Self {
        self.skill_state.managed_dir = Some(dir);
        self
    }

    #[must_use]
    pub fn with_config_reload(mut self, path: PathBuf, rx: mpsc::Receiver<ConfigEvent>) -> Self {
        self.config_path = Some(path);
        self.config_reload_rx = Some(rx);
        self
    }

    #[must_use]
    pub fn with_available_secrets(
        mut self,
        secrets: impl IntoIterator<Item = (String, crate::vault::Secret)>,
    ) -> Self {
        self.skill_state.available_custom_secrets = secrets.into_iter().collect();
        self
    }

    /// # Panics
    ///
    /// Panics if the registry `RwLock` is poisoned.
    #[must_use]
    pub fn with_hybrid_search(mut self, enabled: bool) -> Self {
        self.skill_state.hybrid_search = enabled;
        if enabled {
            let reg = self
                .skill_state
                .registry
                .read()
                .expect("registry read lock");
            let all_meta = reg.all_meta();
            let descs: Vec<&str> = all_meta.iter().map(|m| m.description.as_str()).collect();
            self.skill_state.bm25_index = Some(zeph_skills::bm25::Bm25Index::build(&descs));
        }
        self
    }

    #[must_use]
    pub fn with_learning(mut self, config: LearningConfig) -> Self {
        if config.correction_detection {
            self.feedback_detector = super::feedback_detector::FeedbackDetector::new(
                config.correction_confidence_threshold,
            );
            if config.detector_mode == crate::config::DetectorMode::Judge {
                self.judge_detector = Some(super::feedback_detector::JudgeDetector::new(
                    config.judge_adaptive_low,
                    config.judge_adaptive_high,
                ));
            }
        }
        self.learning_engine.config = Some(config);
        self
    }

    #[must_use]
    pub fn with_judge_provider(mut self, provider: AnyProvider) -> Self {
        self.judge_provider = Some(provider);
        self
    }

    #[must_use]
    pub fn with_mcp(
        mut self,
        tools: Vec<zeph_mcp::McpTool>,
        registry: Option<zeph_mcp::McpToolRegistry>,
        manager: Option<std::sync::Arc<zeph_mcp::McpManager>>,
        mcp_config: &crate::config::McpConfig,
    ) -> Self {
        self.mcp.tools = tools;
        self.mcp.registry = registry;
        self.mcp.manager = manager;
        self.mcp
            .allowed_commands
            .clone_from(&mcp_config.allowed_commands);
        self.mcp.max_dynamic = mcp_config.max_dynamic_servers;
        self
    }

    #[must_use]
    pub fn with_mcp_shared_tools(
        mut self,
        shared: std::sync::Arc<std::sync::RwLock<Vec<zeph_mcp::McpTool>>>,
    ) -> Self {
        self.mcp.shared_tools = Some(shared);
        self
    }

    #[must_use]
    pub fn with_security(mut self, security: SecurityConfig, timeouts: TimeoutConfig) -> Self {
        self.runtime.security = security;
        self.runtime.timeouts = timeouts;
        self
    }

    #[must_use]
    pub fn with_redact_credentials(mut self, enabled: bool) -> Self {
        self.runtime.redact_credentials = enabled;
        self
    }

    #[must_use]
    pub fn with_tool_summarization(mut self, enabled: bool) -> Self {
        self.tool_orchestrator.summarize_tool_output_enabled = enabled;
        self
    }

    #[must_use]
    pub fn with_overflow_config(mut self, config: zeph_tools::OverflowConfig) -> Self {
        self.tool_orchestrator.overflow_config = config;
        self
    }

    #[must_use]
    pub fn with_summary_provider(mut self, provider: AnyProvider) -> Self {
        self.summary_provider = Some(provider);
        self
    }

    pub(super) fn summary_or_primary_provider(&self) -> &AnyProvider {
        self.summary_provider.as_ref().unwrap_or(&self.provider)
    }

    /// Extract the last assistant message, truncated to 500 chars, for the judge prompt.
    pub(super) fn last_assistant_response(&self) -> String {
        self.messages
            .iter()
            .rev()
            .find(|m| m.role == zeph_llm::provider::Role::Assistant)
            .map(|m| super::context::truncate_chars(&m.content, 500))
            .unwrap_or_default()
    }

    #[must_use]
    pub fn with_permission_policy(mut self, policy: zeph_tools::PermissionPolicy) -> Self {
        self.runtime.permission_policy = policy;
        self
    }

    #[must_use]
    pub fn with_context_budget(
        mut self,
        budget_tokens: usize,
        reserve_ratio: f32,
        compaction_threshold: f32,
        compaction_preserve_tail: usize,
        prune_protect_tokens: usize,
    ) -> Self {
        if budget_tokens > 0 {
            self.context_manager.budget = Some(ContextBudget::new(budget_tokens, reserve_ratio));
        }
        self.context_manager.compaction_threshold = compaction_threshold;
        self.context_manager.compaction_preserve_tail = compaction_preserve_tail;
        self.context_manager.prune_protect_tokens = prune_protect_tokens;
        self
    }

    #[must_use]
    pub fn with_model_name(mut self, name: impl Into<String>) -> Self {
        self.runtime.model_name = name.into();
        self
    }

    #[must_use]
    pub fn with_warmup_ready(mut self, rx: watch::Receiver<bool>) -> Self {
        self.warmup_ready = Some(rx);
        self
    }

    #[must_use]
    pub fn with_cost_tracker(mut self, tracker: CostTracker) -> Self {
        self.cost_tracker = Some(tracker);
        self
    }

    #[cfg(feature = "index")]
    #[must_use]
    pub fn with_code_retriever(
        mut self,
        retriever: std::sync::Arc<zeph_index::retriever::CodeRetriever>,
        repo_map_tokens: usize,
        repo_map_ttl_secs: u64,
    ) -> Self {
        self.index.retriever = Some(retriever);
        self.index.repo_map_tokens = repo_map_tokens;
        self.index.repo_map_ttl = std::time::Duration::from_secs(repo_map_ttl_secs);
        self
    }

    /// # Panics
    ///
    /// Panics if the registry `RwLock` is poisoned.
    #[must_use]
    pub fn with_metrics(mut self, tx: watch::Sender<MetricsSnapshot>) -> Self {
        let provider_name = self.provider.name().to_string();
        let model_name = self.runtime.model_name.clone();
        let total_skills = self
            .skill_state
            .registry
            .read()
            .expect("registry read lock")
            .all_meta()
            .len();
        let qdrant_available = false;
        let conversation_id = self.memory_state.conversation_id;
        let prompt_estimate = self
            .messages
            .first()
            .map_or(0, |m| u64::try_from(m.content.len()).unwrap_or(0) / 4);
        let mcp_tool_count = self.mcp.tools.len();
        let mcp_server_count = self
            .mcp
            .tools
            .iter()
            .map(|t| &t.server_id)
            .collect::<std::collections::HashSet<_>>()
            .len();
        tx.send_modify(|m| {
            m.provider_name = provider_name;
            m.model_name = model_name;
            m.total_skills = total_skills;
            m.qdrant_available = qdrant_available;
            m.sqlite_conversation_id = conversation_id;
            m.context_tokens = prompt_estimate;
            m.prompt_tokens = prompt_estimate;
            m.total_tokens = prompt_estimate;
            m.mcp_tool_count = mcp_tool_count;
            m.mcp_server_count = mcp_server_count;
        });
        self.metrics_tx = Some(tx);
        self
    }

    /// 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.
    #[must_use]
    pub fn cancel_signal(&self) -> Arc<Notify> {
        Arc::clone(&self.cancel_signal)
    }

    /// Inject a shared cancel signal so an external caller (e.g. ACP session) can
    /// interrupt the agent loop by calling `notify_one()`.
    #[must_use]
    pub fn with_cancel_signal(mut self, signal: Arc<Notify>) -> Self {
        self.cancel_signal = signal;
        self
    }

    #[must_use]
    pub fn with_subagent_manager(mut self, manager: crate::subagent::SubAgentManager) -> Self {
        self.subagent_manager = Some(manager);
        self
    }

    #[must_use]
    pub fn with_subagent_config(mut self, config: crate::config::SubAgentConfig) -> Self {
        self.subagent_config = config;
        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.
    #[must_use]
    pub fn with_provider_override(
        mut self,
        slot: Arc<std::sync::RwLock<Option<AnyProvider>>>,
    ) -> Self {
        self.provider_override = Some(slot);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::super::agent_tests::{
        MockChannel, MockToolExecutor, create_test_registry, mock_provider,
    };
    use super::*;

    #[test]
    fn with_cancel_signal_replaces_internal_signal() {
        let agent = Agent::new(
            mock_provider(vec![]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );

        let shared = Arc::new(Notify::new());
        let agent = agent.with_cancel_signal(Arc::clone(&shared));

        // The injected signal and the agent's internal signal must be the same Arc.
        assert!(Arc::ptr_eq(&shared, &agent.cancel_signal()));
    }

    /// Verify that with_managed_skills_dir enables the install/remove commands.
    /// Without a managed dir, `/skill install` sends a "not configured" message.
    /// With a managed dir configured, it proceeds past that guard (and may fail
    /// for other reasons such as the source not existing).
    #[tokio::test]
    async fn with_managed_skills_dir_enables_install_command() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let managed = tempfile::tempdir().unwrap();

        let mut agent_no_dir = Agent::new(
            mock_provider(vec![]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );
        agent_no_dir
            .handle_skill_command("install /some/path")
            .await
            .unwrap();
        let sent_no_dir = agent_no_dir.channel.sent_messages();
        assert!(
            sent_no_dir.iter().any(|s| s.contains("not configured")),
            "without managed dir: {sent_no_dir:?}"
        );

        let _ = (provider, channel, registry, executor);
        let mut agent_with_dir = Agent::new(
            mock_provider(vec![]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        )
        .with_managed_skills_dir(managed.path().to_path_buf());

        agent_with_dir
            .handle_skill_command("install /nonexistent/path")
            .await
            .unwrap();
        let sent_with_dir = agent_with_dir.channel.sent_messages();
        assert!(
            !sent_with_dir.iter().any(|s| s.contains("not configured")),
            "with managed dir should not say not configured: {sent_with_dir:?}"
        );
        assert!(
            sent_with_dir.iter().any(|s| s.contains("Install failed")),
            "with managed dir should fail due to bad path: {sent_with_dir:?}"
        );
    }
}