Skip to main content

zeph_core/
overflow_tools.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use std::sync::Arc;
5
6use zeph_memory::store::SqliteStore;
7use zeph_tools::executor::{ToolCall, ToolError, ToolExecutor, ToolOutput, deserialize_params};
8use zeph_tools::registry::{InvocationHint, ToolDef};
9
10#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
11struct ReadOverflowParams {
12    /// The bare UUID from the overflow notice. The `overflow:` prefix is accepted but stripped automatically.
13    id: String,
14}
15
16pub struct OverflowToolExecutor {
17    sqlite: Arc<SqliteStore>,
18    conversation_id: Option<i64>,
19}
20
21impl OverflowToolExecutor {
22    pub const TOOL_NAME: &'static str = "read_overflow";
23
24    #[must_use]
25    pub fn new(sqlite: Arc<SqliteStore>) -> Self {
26        Self {
27            sqlite,
28            conversation_id: None,
29        }
30    }
31
32    #[must_use]
33    pub fn with_conversation(mut self, conversation_id: i64) -> Self {
34        self.conversation_id = Some(conversation_id);
35        self
36    }
37}
38
39impl ToolExecutor for OverflowToolExecutor {
40    fn tool_definitions(&self) -> Vec<ToolDef> {
41        vec![ToolDef {
42            id: Self::TOOL_NAME.into(),
43            description: "Retrieve the full content of a tool output that was truncated due to \
44                size. Use when a previous tool result contains an overflow notice. \
45                Parameters: id (string, required) — the bare UUID from the notice \
46                (e.g. '550e8400-e29b-41d4-a716-446655440000'). \
47                Returns: full original tool output text. Errors: NotFound if the \
48                overflow entry has expired or does not exist."
49                .into(),
50            schema: schemars::schema_for!(ReadOverflowParams),
51            invocation: InvocationHint::ToolCall,
52        }]
53    }
54
55    async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
56        Ok(None)
57    }
58
59    async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
60        if call.tool_id != Self::TOOL_NAME {
61            return Ok(None);
62        }
63        let params: ReadOverflowParams = deserialize_params(&call.params)?;
64
65        let id = params.id.strip_prefix("overflow:").unwrap_or(&params.id);
66
67        if uuid::Uuid::parse_str(id).is_err() {
68            return Err(ToolError::InvalidParams {
69                message: "id must be a valid UUID".to_owned(),
70            });
71        }
72
73        let Some(conv_id) = self.conversation_id else {
74            return Err(ToolError::Execution(std::io::Error::other(
75                "overflow entry not found or expired",
76            )));
77        };
78
79        match self.sqlite.load_overflow(id, conv_id).await {
80            Ok(Some(bytes)) => {
81                let text = String::from_utf8_lossy(&bytes).into_owned();
82                Ok(Some(ToolOutput {
83                    tool_name: Self::TOOL_NAME.to_owned(),
84                    summary: text,
85                    blocks_executed: 1,
86                    filter_stats: None,
87                    diff: None,
88                    streamed: false,
89                    terminal_id: None,
90                    locations: None,
91                    raw_response: None,
92                    claim_source: None,
93                }))
94            }
95            Ok(None) => Err(ToolError::Execution(std::io::Error::other(
96                "overflow entry not found or expired",
97            ))),
98            Err(e) => Err(ToolError::Execution(std::io::Error::other(format!(
99                "failed to load overflow: {e}"
100            )))),
101        }
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108    use zeph_memory::store::SqliteStore;
109
110    async fn make_store_with_conv() -> (Arc<SqliteStore>, i64) {
111        let store = SqliteStore::new(":memory:")
112            .await
113            .expect("SqliteStore::new");
114        let cid = store
115            .create_conversation()
116            .await
117            .expect("create_conversation");
118        (Arc::new(store), cid.0)
119    }
120
121    fn make_call(id: &str) -> ToolCall {
122        let mut params = serde_json::Map::new();
123        params.insert("id".into(), serde_json::Value::String(id.to_owned()));
124        ToolCall {
125            tool_id: "read_overflow".to_owned(),
126            params,
127        }
128    }
129
130    #[tokio::test]
131    async fn tool_definitions_returns_one_tool() {
132        let (store, _) = make_store_with_conv().await;
133        let exec = OverflowToolExecutor::new(store);
134        let defs = exec.tool_definitions();
135        assert_eq!(defs.len(), 1);
136        assert_eq!(defs[0].id.as_ref(), OverflowToolExecutor::TOOL_NAME);
137    }
138
139    #[tokio::test]
140    async fn execute_always_returns_none() {
141        let (store, _) = make_store_with_conv().await;
142        let exec = OverflowToolExecutor::new(store);
143        let result = exec.execute("anything").await.unwrap();
144        assert!(result.is_none());
145    }
146
147    #[tokio::test]
148    async fn unknown_tool_returns_none() {
149        let (store, _) = make_store_with_conv().await;
150        let exec = OverflowToolExecutor::new(store);
151        let call = ToolCall {
152            tool_id: "other_tool".to_owned(),
153            params: serde_json::Map::new(),
154        };
155        let result = exec.execute_tool_call(&call).await.unwrap();
156        assert!(result.is_none());
157    }
158
159    #[tokio::test]
160    async fn invalid_uuid_returns_error() {
161        let (store, cid) = make_store_with_conv().await;
162        let exec = OverflowToolExecutor::new(store).with_conversation(cid);
163        let call = make_call("not-a-uuid");
164        let err = exec.execute_tool_call(&call).await.unwrap_err();
165        assert!(matches!(err, ToolError::InvalidParams { .. }));
166    }
167
168    #[tokio::test]
169    async fn overflow_prefix_accepted_and_stripped() {
170        let (store, cid) = make_store_with_conv().await;
171        let content = b"prefixed overflow content";
172        let uuid = store
173            .save_overflow(cid, content)
174            .await
175            .expect("save_overflow");
176
177        let exec = OverflowToolExecutor::new(Arc::clone(&store)).with_conversation(cid);
178        let call = make_call(&format!("overflow:{uuid}"));
179        let result = exec.execute_tool_call(&call).await.unwrap().unwrap();
180        assert_eq!(result.summary.as_bytes(), content);
181    }
182
183    #[tokio::test]
184    async fn bare_uuid_still_accepted() {
185        let (store, cid) = make_store_with_conv().await;
186        let content = b"bare uuid content";
187        let uuid = store
188            .save_overflow(cid, content)
189            .await
190            .expect("save_overflow");
191
192        let exec = OverflowToolExecutor::new(Arc::clone(&store)).with_conversation(cid);
193        let call = make_call(&uuid);
194        let result = exec.execute_tool_call(&call).await.unwrap().unwrap();
195        assert_eq!(result.summary.as_bytes(), content);
196    }
197
198    #[tokio::test]
199    async fn invalid_uuid_with_overflow_prefix_returns_error() {
200        let (store, cid) = make_store_with_conv().await;
201        let exec = OverflowToolExecutor::new(store).with_conversation(cid);
202        let call = make_call("overflow:not-a-uuid");
203        let err = exec.execute_tool_call(&call).await.unwrap_err();
204        assert!(matches!(err, ToolError::InvalidParams { .. }));
205    }
206
207    #[tokio::test]
208    async fn missing_entry_returns_error() {
209        let (store, cid) = make_store_with_conv().await;
210        let exec = OverflowToolExecutor::new(store).with_conversation(cid);
211        let call = make_call("00000000-0000-0000-0000-000000000000");
212        let err = exec.execute_tool_call(&call).await.unwrap_err();
213        assert!(matches!(err, ToolError::Execution(_)));
214    }
215
216    #[tokio::test]
217    async fn no_conversation_returns_error() {
218        let (store, cid) = make_store_with_conv().await;
219        let uuid = store.save_overflow(cid, b"data").await.expect("save");
220        // Executor without conversation_id must return error (not panic).
221        let exec = OverflowToolExecutor::new(store);
222        let call = make_call(&uuid);
223        let err = exec.execute_tool_call(&call).await.unwrap_err();
224        assert!(matches!(err, ToolError::Execution(_)));
225    }
226
227    #[tokio::test]
228    async fn valid_entry_returns_content() {
229        let (store, cid) = make_store_with_conv().await;
230        let content = b"full tool output content";
231        let uuid = store
232            .save_overflow(cid, content)
233            .await
234            .expect("save_overflow");
235
236        let exec = OverflowToolExecutor::new(Arc::clone(&store)).with_conversation(cid);
237        let call = make_call(&uuid);
238        let result = exec.execute_tool_call(&call).await.unwrap().unwrap();
239        assert_eq!(result.tool_name, OverflowToolExecutor::TOOL_NAME);
240        assert_eq!(result.summary.as_bytes(), content);
241    }
242
243    #[tokio::test]
244    async fn cross_conversation_access_denied() {
245        let (store, cid1) = make_store_with_conv().await;
246        let cid2 = store
247            .create_conversation()
248            .await
249            .expect("create_conversation")
250            .0;
251        let uuid = store.save_overflow(cid1, b"secret").await.expect("save");
252        // Executor bound to cid2 must not retrieve cid1's overflow.
253        let exec = OverflowToolExecutor::new(Arc::clone(&store)).with_conversation(cid2);
254        let call = make_call(&uuid);
255        let err = exec.execute_tool_call(&call).await.unwrap_err();
256        assert!(
257            matches!(err, ToolError::Execution(_)),
258            "must not access overflow from a different conversation"
259        );
260    }
261
262    #[tokio::test]
263    async fn read_overflow_output_is_not_reoverflowed() {
264        // Verify that the tool returns raw content regardless of size.
265        // The caller (native.rs) is responsible for skipping overflow for read_overflow results.
266        let (store, cid) = make_store_with_conv().await;
267        let big_content = "x".repeat(100_000).into_bytes();
268        let uuid = store
269            .save_overflow(cid, &big_content)
270            .await
271            .expect("save_overflow");
272
273        let exec = OverflowToolExecutor::new(Arc::clone(&store)).with_conversation(cid);
274        let call = make_call(&uuid);
275        let result = exec.execute_tool_call(&call).await.unwrap().unwrap();
276        assert_eq!(
277            result.summary.len(),
278            100_000,
279            "full content must be returned"
280        );
281    }
282}