zeph-tools 0.22.4

Tool executor trait with shell, web scrape, and composite executors 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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::LazyLock;
use std::time::{Duration, Instant};

use zeph_common::ToolName;

use crate::executor::ToolOutput;

/// Tools that must never have their results cached due to side effects.
///
/// Any tool with side effects (writes, state mutations, external actions) MUST be listed here.
/// MCP-origin tools are non-cacheable by default — they are third-party and opaque — see
/// `is_cacheable`'s `is_mcp` parameter. `memory_search` is excluded to avoid stale results
/// after `memory_save` calls.
static NON_CACHEABLE_TOOLS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
    HashSet::from([
        "bash",          // shell commands have side effects and depend on mutable state
        "memory_save",   // writes to memory store
        "memory_search", // results may change after memory_save; consistency > performance
        "scheduler",     // creates/modifies scheduled tasks
        "write",         // writes files
    ])
});

/// Returns `true` if the tool's results can be safely cached.
///
/// `is_mcp` must be resolved by the caller via
/// [`ToolDef::is_mcp_tool`](crate::registry::ToolDef::is_mcp_tool) (`server_id.is_some()`).
/// Real MCP tool ids are `{server_id}_{name}` (`McpTool::sanitized_id`) and carry no reliable
/// string prefix to pattern-match on here (#5712, #5733), so this function cannot infer MCP
/// origin from `tool_name` alone. MCP-origin tools are always non-cacheable by default since
/// they are third-party and may have unknown side effects.
#[must_use]
pub fn is_cacheable(tool_name: &str, is_mcp: bool) -> bool {
    if is_mcp {
        return false;
    }
    !NON_CACHEABLE_TOOLS.contains(tool_name)
}

/// Composite key identifying a unique tool invocation.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CacheKey {
    pub tool_name: ToolName,
    pub args_hash: u64,
}

impl CacheKey {
    #[must_use]
    pub fn new(tool_name: impl Into<ToolName>, args_hash: u64) -> Self {
        Self {
            tool_name: tool_name.into(),
            args_hash,
        }
    }
}

/// A single cached tool result with insertion timestamp.
#[derive(Debug, Clone)]
pub struct CacheEntry {
    pub output: ToolOutput,
    pub inserted_at: Instant,
}

impl CacheEntry {
    fn is_expired(&self, ttl: Duration) -> bool {
        self.inserted_at.elapsed() > ttl
    }
}

/// Maximum number of entries retained in the cache at any time.
///
/// Long sessions accumulate tool results indefinitely without a cap, leading to unbounded memory
/// growth. 512 entries covers typical session breadth with negligible overhead while bounding
/// worst-case memory for long-running TUI sessions.
const MAX_CACHE_ENTRIES: usize = 512;

/// In-memory, session-scoped cache for tool results.
///
/// # Design
/// - `ttl = None` means entries never expire (useful for batch/scripted sessions).
/// - `ttl = Some(d)` means entries expire after duration `d`.
/// - Lazy eviction: expired entries are removed on `get()`.
/// - LRU eviction: when the entry count reaches `MAX_CACHE_ENTRIES`, the least-recently-inserted
///   entry is evicted to bound memory growth in long sessions.
/// - Not `Send + Sync` by design — accessed only from the agent's single-threaded loop.
#[derive(Debug)]
pub struct ToolResultCache {
    entries: HashMap<CacheKey, CacheEntry>,
    /// Insertion-order key list for LRU eviction (front = oldest).
    insertion_order: VecDeque<CacheKey>,
    /// `None` = never expire. `Some(d)` = expire after `d`.
    ttl: Option<Duration>,
    enabled: bool,
    hits: u64,
    misses: u64,
}

impl ToolResultCache {
    /// Create a new cache with the given TTL and enabled state.
    ///
    /// `ttl = None` means entries never expire.
    #[must_use]
    pub fn new(enabled: bool, ttl: Option<Duration>) -> Self {
        Self {
            entries: HashMap::new(),
            insertion_order: VecDeque::new(),
            ttl,
            enabled,
            hits: 0,
            misses: 0,
        }
    }

    /// Look up a cached result. Returns `None` on miss or if expired.
    ///
    /// Expired entries are removed lazily on access.
    pub fn get(&mut self, key: &CacheKey) -> Option<ToolOutput> {
        if !self.enabled {
            return None;
        }
        if let Some(entry) = self.entries.get(key) {
            if self.ttl.is_some_and(|ttl| entry.is_expired(ttl)) {
                self.entries.remove(key);
                return None;
            }
            let output = entry.output.clone();
            self.hits += 1;
            return Some(output);
        }
        self.misses += 1;
        None
    }

    /// Store a tool result in the cache.
    ///
    /// When the cache is at capacity (`MAX_CACHE_ENTRIES`), the oldest entry is evicted
    /// before inserting the new one to prevent unbounded memory growth in long sessions.
    pub fn put(&mut self, key: CacheKey, output: ToolOutput) {
        if !self.enabled {
            return;
        }
        if self.entries.len() >= MAX_CACHE_ENTRIES
            && let Some(oldest_key) = self.insertion_order.pop_front()
        {
            self.entries.remove(&oldest_key);
            tracing::debug!(
                tool = %oldest_key.tool_name,
                args_hash = oldest_key.args_hash,
                "tool cache: evicted oldest entry (LRU cap {})",
                MAX_CACHE_ENTRIES
            );
        }
        self.insertion_order.push_back(key.clone());
        self.entries.insert(
            key,
            CacheEntry {
                output,
                inserted_at: Instant::now(),
            },
        );
    }

    /// Remove all entries and reset hit/miss counters.
    pub fn clear(&mut self) {
        self.entries.clear();
        self.insertion_order.clear();
        self.hits = 0;
        self.misses = 0;
    }

    /// Number of entries currently in the cache (including potentially expired ones).
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` if the cache is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Total cache hits since last `clear()`.
    #[must_use]
    pub fn hits(&self) -> u64 {
        self.hits
    }

    /// Total cache misses since last `clear()`.
    #[must_use]
    pub fn misses(&self) -> u64 {
        self.misses
    }

    /// Whether the cache is enabled.
    #[must_use]
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// TTL in seconds for display (0 = never expire).
    #[must_use]
    pub fn ttl_secs(&self) -> u64 {
        self.ttl.map_or(0, |d| d.as_secs())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ToolName;

    fn make_output(summary: &str) -> ToolOutput {
        ToolOutput {
            tool_name: ToolName::new("test"),
            summary: summary.to_owned(),
            blocks_executed: 1,
            filter_stats: None,
            diff: None,
            streamed: false,
            terminal_id: None,
            locations: None,
            raw_response: None,
            claim_source: None,
            ..Default::default()
        }
    }

    fn key(name: &str, hash: u64) -> CacheKey {
        CacheKey::new(name, hash)
    }

    #[test]
    fn miss_on_empty_cache() {
        let mut cache = ToolResultCache::new(true, Some(Duration::from_mins(5)));
        assert!(cache.get(&key("read", 1)).is_none());
        assert_eq!(cache.misses(), 1);
        assert_eq!(cache.hits(), 0);
    }

    #[test]
    fn put_then_get_returns_cached() {
        let mut cache = ToolResultCache::new(true, Some(Duration::from_mins(5)));
        let out = make_output("file contents");
        cache.put(key("read", 42), out.clone());
        let result = cache.get(&key("read", 42));
        assert!(result.is_some());
        assert_eq!(result.unwrap().summary, "file contents");
        assert_eq!(cache.hits(), 1);
        assert_eq!(cache.misses(), 0);
    }

    #[test]
    fn different_hash_is_miss() {
        let mut cache = ToolResultCache::new(true, Some(Duration::from_mins(5)));
        cache.put(key("read", 1), make_output("a"));
        assert!(cache.get(&key("read", 2)).is_none());
    }

    #[test]
    fn different_tool_name_is_miss() {
        let mut cache = ToolResultCache::new(true, Some(Duration::from_mins(5)));
        cache.put(key("read", 1), make_output("a"));
        assert!(cache.get(&key("write", 1)).is_none());
    }

    #[test]
    fn ttl_none_never_expires() {
        let mut cache = ToolResultCache::new(true, None);
        cache.put(key("read", 1), make_output("content"));
        // Without TTL, entry should always be present
        assert!(cache.get(&key("read", 1)).is_some());
        assert_eq!(cache.hits(), 1);
    }

    #[test]
    fn ttl_zero_duration_expires_immediately() {
        // Duration::ZERO → elapsed() > Duration::ZERO is true immediately (any nanosecond suffices).
        // This verifies the behaviour: does not panic, and the entry is gone after get().
        let mut cache = ToolResultCache::new(true, Some(Duration::ZERO));
        cache.put(key("read", 1), make_output("content"));
        let result = cache.get(&key("read", 1));
        // Entry expired on access — None and evicted from map.
        assert!(
            result.is_none(),
            "Duration::ZERO entry must expire on first get()"
        );
        assert_eq!(cache.len(), 0, "expired entry must be removed from map");
    }

    #[test]
    fn ttl_expired_returns_none() {
        let mut cache = ToolResultCache::new(true, Some(Duration::from_millis(1)));
        cache.put(key("read", 1), make_output("content"));
        std::thread::sleep(Duration::from_millis(10));
        assert!(cache.get(&key("read", 1)).is_none());
        // expired entry is evicted, re-query also miss
        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn clear_removes_all_and_resets_counters() {
        let mut cache = ToolResultCache::new(true, Some(Duration::from_mins(5)));
        cache.put(key("read", 1), make_output("a"));
        cache.put(key("web_scrape", 2), make_output("b"));
        // generate some hits/misses
        cache.get(&key("read", 1));
        cache.get(&key("missing", 99));
        assert_eq!(cache.hits(), 1);
        assert_eq!(cache.misses(), 1);

        cache.clear();
        assert_eq!(cache.len(), 0);
        assert_eq!(cache.hits(), 0);
        assert_eq!(cache.misses(), 0);
        assert!(cache.get(&key("read", 1)).is_none());
    }

    #[test]
    fn disabled_cache_always_misses() {
        let mut cache = ToolResultCache::new(false, Some(Duration::from_mins(5)));
        cache.put(key("read", 1), make_output("content"));
        // put is a no-op when disabled
        assert!(cache.get(&key("read", 1)).is_none());
        assert_eq!(cache.len(), 0);
        // misses counter also stays 0 when disabled
        assert_eq!(cache.misses(), 0);
    }

    #[test]
    fn is_cacheable_returns_false_for_deny_list() {
        assert!(!is_cacheable("bash", false));
        assert!(!is_cacheable("memory_save", false));
        assert!(!is_cacheable("memory_search", false));
        assert!(!is_cacheable("scheduler", false));
        assert!(!is_cacheable("write", false));
    }

    /// #5733 regression: MCP origin must be resolved by the caller (`ToolDef::is_mcp_tool`),
    /// not inferred from a `"mcp_"` string prefix — real MCP tool ids are `{server_id}_{name}`
    /// (`McpTool::sanitized_id`) and never carry that prefix, so the old check silently never
    /// matched and MCP results WERE being cached, the opposite of the intended behavior.
    #[test]
    fn is_cacheable_returns_false_for_mcp_origin() {
        assert!(!is_cacheable("github_list_issues", true));
        assert!(!is_cacheable("send_email", true));
        // A non-deny-listed, non-MCP tool with the exact same real-world id shape is cacheable.
        assert!(is_cacheable("github_list_issues", false));
    }

    #[test]
    fn is_cacheable_returns_true_for_read_only_tools() {
        assert!(is_cacheable("read", false));
        assert!(is_cacheable("web_scrape", false));
        assert!(is_cacheable("search_code", false));
        assert!(is_cacheable("load_skill", false));
        assert!(is_cacheable("diagnostics", false));
    }

    #[test]
    fn counter_increments_correctly() {
        let mut cache = ToolResultCache::new(true, Some(Duration::from_mins(5)));
        cache.put(key("read", 1), make_output("a"));
        cache.put(key("read", 2), make_output("b"));

        cache.get(&key("read", 1)); // hit
        cache.get(&key("read", 1)); // hit
        cache.get(&key("read", 99)); // miss

        assert_eq!(cache.hits(), 2);
        assert_eq!(cache.misses(), 1);
    }

    #[test]
    fn ttl_secs_returns_zero_for_none() {
        let cache = ToolResultCache::new(true, None);
        assert_eq!(cache.ttl_secs(), 0);
    }

    #[test]
    fn ttl_secs_returns_seconds_for_some() {
        let cache = ToolResultCache::new(true, Some(Duration::from_mins(5)));
        assert_eq!(cache.ttl_secs(), 300);
    }

    #[test]
    fn lru_eviction_at_capacity() {
        let mut cache = ToolResultCache::new(true, None);
        // Fill to capacity.
        for i in 0..MAX_CACHE_ENTRIES {
            cache.put(key("read", i as u64), make_output("v"));
        }
        assert_eq!(cache.len(), MAX_CACHE_ENTRIES);
        // Inserting one more should evict the oldest (hash=0).
        cache.put(key("read", MAX_CACHE_ENTRIES as u64), make_output("new"));
        assert_eq!(cache.len(), MAX_CACHE_ENTRIES, "size must stay at cap");
        assert!(
            cache.get(&key("read", 0)).is_none(),
            "oldest entry must be evicted"
        );
        assert!(
            cache.get(&key("read", MAX_CACHE_ENTRIES as u64)).is_some(),
            "new entry must be present"
        );
    }
}