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            output_schema: None,
53        }]
54    }
55
56    async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
57        Ok(None)
58    }
59
60    async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
61        if call.tool_id != Self::TOOL_NAME {
62            return Ok(None);
63        }
64        let params: ReadOverflowParams = deserialize_params(&call.params)?;
65
66        let id = params.id.strip_prefix("overflow:").unwrap_or(&params.id);
67
68        if uuid::Uuid::parse_str(id).is_err() {
69            return Err(ToolError::InvalidParams {
70                message: "id must be a valid UUID".to_owned(),
71            });
72        }
73
74        let Some(conv_id) = self.conversation_id else {
75            return Err(ToolError::Execution(std::io::Error::other(
76                "overflow entry not found or expired",
77            )));
78        };
79
80        match self.sqlite.load_overflow(id, conv_id).await {
81            Ok(Some(bytes)) => {
82                let text = String::from_utf8_lossy(&bytes).into_owned();
83                Ok(Some(ToolOutput {
84                    tool_name: zeph_common::ToolName::new(Self::TOOL_NAME),
85                    summary: text,
86                    blocks_executed: 1,
87                    filter_stats: None,
88                    diff: None,
89                    streamed: false,
90                    terminal_id: None,
91                    locations: None,
92                    raw_response: None,
93                    claim_source: None,
94                }))
95            }
96            Ok(None) => Err(ToolError::Execution(std::io::Error::other(
97                "overflow entry not found or expired",
98            ))),
99            Err(e) => Err(ToolError::Execution(std::io::Error::other(format!(
100                "failed to load overflow: {e}"
101            )))),
102        }
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use zeph_memory::store::SqliteStore;
110
111    async fn make_store_with_conv() -> (Arc<SqliteStore>, i64) {
112        let store = SqliteStore::new(":memory:")
113            .await
114            .expect("SqliteStore::new");
115        let cid = store
116            .create_conversation()
117            .await
118            .expect("create_conversation");
119        (Arc::new(store), cid.0)
120    }
121
122    fn make_call(id: &str) -> ToolCall {
123        let mut params = serde_json::Map::new();
124        params.insert("id".into(), serde_json::Value::String(id.to_owned()));
125        ToolCall {
126            tool_id: zeph_common::ToolName::new("read_overflow"),
127            params,
128            caller_id: None,
129            context: None,
130
131            tool_call_id: String::new(),
132        }
133    }
134
135    #[tokio::test]
136    async fn tool_definitions_returns_one_tool() {
137        let (store, _) = make_store_with_conv().await;
138        let exec = OverflowToolExecutor::new(store);
139        let defs = exec.tool_definitions();
140        assert_eq!(defs.len(), 1);
141        assert_eq!(defs[0].id.as_ref(), OverflowToolExecutor::TOOL_NAME);
142    }
143
144    #[tokio::test]
145    async fn execute_always_returns_none() {
146        let (store, _) = make_store_with_conv().await;
147        let exec = OverflowToolExecutor::new(store);
148        let result = exec.execute("anything").await.unwrap();
149        assert!(result.is_none());
150    }
151
152    #[tokio::test]
153    async fn unknown_tool_returns_none() {
154        let (store, _) = make_store_with_conv().await;
155        let exec = OverflowToolExecutor::new(store);
156        let call = ToolCall {
157            tool_id: zeph_common::ToolName::new("other_tool"),
158            params: serde_json::Map::new(),
159            caller_id: None,
160            context: None,
161
162            tool_call_id: String::new(),
163        };
164        let result = exec.execute_tool_call(&call).await.unwrap();
165        assert!(result.is_none());
166    }
167
168    #[tokio::test]
169    async fn invalid_uuid_returns_error() {
170        let (store, cid) = make_store_with_conv().await;
171        let exec = OverflowToolExecutor::new(store).with_conversation(cid);
172        let call = make_call("not-a-uuid");
173        let err = exec.execute_tool_call(&call).await.unwrap_err();
174        assert!(matches!(err, ToolError::InvalidParams { .. }));
175    }
176
177    #[tokio::test]
178    async fn overflow_prefix_accepted_and_stripped() {
179        let (store, cid) = make_store_with_conv().await;
180        let content = b"prefixed overflow content";
181        let uuid = store
182            .save_overflow(cid, content)
183            .await
184            .expect("save_overflow");
185
186        let exec = OverflowToolExecutor::new(Arc::clone(&store)).with_conversation(cid);
187        let call = make_call(&format!("overflow:{uuid}"));
188        let result = exec.execute_tool_call(&call).await.unwrap().unwrap();
189        assert_eq!(result.summary.as_bytes(), content);
190    }
191
192    #[tokio::test]
193    async fn bare_uuid_still_accepted() {
194        let (store, cid) = make_store_with_conv().await;
195        let content = b"bare uuid content";
196        let uuid = store
197            .save_overflow(cid, content)
198            .await
199            .expect("save_overflow");
200
201        let exec = OverflowToolExecutor::new(Arc::clone(&store)).with_conversation(cid);
202        let call = make_call(&uuid);
203        let result = exec.execute_tool_call(&call).await.unwrap().unwrap();
204        assert_eq!(result.summary.as_bytes(), content);
205    }
206
207    #[tokio::test]
208    async fn invalid_uuid_with_overflow_prefix_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("overflow:not-a-uuid");
212        let err = exec.execute_tool_call(&call).await.unwrap_err();
213        assert!(matches!(err, ToolError::InvalidParams { .. }));
214    }
215
216    #[tokio::test]
217    async fn missing_entry_returns_error() {
218        let (store, cid) = make_store_with_conv().await;
219        let exec = OverflowToolExecutor::new(store).with_conversation(cid);
220        let call = make_call("00000000-0000-0000-0000-000000000000");
221        let err = exec.execute_tool_call(&call).await.unwrap_err();
222        assert!(matches!(err, ToolError::Execution(_)));
223    }
224
225    #[tokio::test]
226    async fn no_conversation_returns_error() {
227        let (store, cid) = make_store_with_conv().await;
228        let uuid = store.save_overflow(cid, b"data").await.expect("save");
229        // Executor without conversation_id must return error (not panic).
230        let exec = OverflowToolExecutor::new(store);
231        let call = make_call(&uuid);
232        let err = exec.execute_tool_call(&call).await.unwrap_err();
233        assert!(matches!(err, ToolError::Execution(_)));
234    }
235
236    #[tokio::test]
237    async fn valid_entry_returns_content() {
238        let (store, cid) = make_store_with_conv().await;
239        let content = b"full tool output content";
240        let uuid = store
241            .save_overflow(cid, content)
242            .await
243            .expect("save_overflow");
244
245        let exec = OverflowToolExecutor::new(Arc::clone(&store)).with_conversation(cid);
246        let call = make_call(&uuid);
247        let result = exec.execute_tool_call(&call).await.unwrap().unwrap();
248        assert_eq!(result.tool_name, OverflowToolExecutor::TOOL_NAME);
249        assert_eq!(result.summary.as_bytes(), content);
250    }
251
252    #[tokio::test]
253    async fn cross_conversation_access_denied() {
254        let (store, cid1) = make_store_with_conv().await;
255        let cid2 = store
256            .create_conversation()
257            .await
258            .expect("create_conversation")
259            .0;
260        let uuid = store.save_overflow(cid1, b"secret").await.expect("save");
261        // Executor bound to cid2 must not retrieve cid1's overflow.
262        let exec = OverflowToolExecutor::new(Arc::clone(&store)).with_conversation(cid2);
263        let call = make_call(&uuid);
264        let err = exec.execute_tool_call(&call).await.unwrap_err();
265        assert!(
266            matches!(err, ToolError::Execution(_)),
267            "must not access overflow from a different conversation"
268        );
269    }
270
271    #[tokio::test]
272    async fn read_overflow_output_is_not_reoverflowed() {
273        // Verify that the tool returns raw content regardless of size.
274        // The caller (native.rs) is responsible for skipping overflow for read_overflow results.
275        let (store, cid) = make_store_with_conv().await;
276        let big_content = "x".repeat(100_000).into_bytes();
277        let uuid = store
278            .save_overflow(cid, &big_content)
279            .await
280            .expect("save_overflow");
281
282        let exec = OverflowToolExecutor::new(Arc::clone(&store)).with_conversation(cid);
283        let call = make_call(&uuid);
284        let result = exec.execute_tool_call(&call).await.unwrap().unwrap();
285        assert_eq!(
286            result.summary.len(),
287            100_000,
288            "full content must be returned"
289        );
290    }
291}