Skip to main content

vtcode_core/tools/defuddle/
mod.rs

1//! Defuddle-backed fetch: `https://defuddle.md/{link}` -> clean markdown.
2//!
3//! Defuddle is a third-party hosted service that takes a URL and returns
4//! LLM-friendly markdown for the page. It is a polite convenience for the
5//! rare case where `web_fetch` returns a payload the agent would rather not
6//! parse itself (heavy JS, paywalled HTML, raw RSS, etc.).
7//!
8//! Because the service is rate-limited, this tool is hard-capped at one call
9//! per `DefuddleTool` instance. A new instance per session is the recommended
10//! pattern; the registry constructs the tool once per agent, so the cap
11//! effectively means "once per session".
12//!
13//! The response is returned inline (no temp file). When the cap is hit, the
14//! tool returns a structured JSON error that points the agent back to
15//! `web_fetch` so it does not loop.
16
17use super::traits::Tool;
18use crate::config::constants::tools;
19use crate::tools::web_fetch::classify_helpers::extract_http_status;
20use crate::tools::web_fetch::is_private_host;
21use anyhow::{Context, Result, anyhow};
22use async_trait::async_trait;
23use serde::Deserialize;
24use serde_json::{Value, json};
25use std::sync::Arc;
26use std::sync::atomic::{AtomicUsize, Ordering};
27use std::time::Duration;
28use url::Url;
29
30const DEFAULT_TIMEOUT_SECS: u64 = 30;
31const MAX_TIMEOUT_SECS: u64 = 60;
32const MAX_BYTES: usize = 256 * 1024;
33const DEFUDDLE_BASE_URL: &str = "https://defuddle.md/";
34
35pub(crate) const DEFUDDLE_FETCH_DESCRIPTION: &str = "Fetch a REMOTE web page (http:// or https:// URLs ONLY) through the defuddle.md markdown extraction service and return the cleaned markdown inline. DO NOT use for local files: inspect local paths with exec_command and readonly shell commands such as sed, rg, ls, or find. Use this sparingly: the hosted service is rate-limited, so this tool can be called at most ONCE per session. Accepts: { url: string (must start with http:// or https://), max_bytes?: number }. Returns { url, markdown, bytes, used_this_session, session_cap } or a structured error if the cap has been hit.";
36
37#[derive(Debug, Deserialize)]
38struct DefuddleArgs {
39    #[serde(default)]
40    url: Option<String>,
41    #[serde(default)]
42    max_bytes: Option<usize>,
43}
44
45#[derive(Clone, Default)]
46pub struct DefuddleTool {
47    /// How many calls have been issued against this instance. Hard-capped at
48    /// `SESSION_CAP` to stay well under the third-party service's quota.
49    uses: Arc<AtomicUsize>,
50}
51
52const SESSION_CAP: usize = 1;
53
54impl DefuddleTool {
55    pub fn new() -> Self {
56        Self::default()
57    }
58
59    /// Reset the per-instance counter. Used by tests; production code should
60    /// not call this — a new `DefuddleTool` is the way to start a new budget.
61    pub fn reset(&self) {
62        self.uses.store(0, Ordering::SeqCst);
63    }
64
65    fn current_uses(&self) -> usize {
66        self.uses.load(Ordering::SeqCst)
67    }
68
69    fn try_consume(&self) -> bool {
70        // Compare-and-swap loop so concurrent callers cannot both succeed
71        // once the cap is hit.
72        loop {
73            let current = self.uses.load(Ordering::SeqCst);
74            if current >= SESSION_CAP {
75                return false;
76            }
77            if self
78                .uses
79                .compare_exchange(current, current + 1, Ordering::SeqCst, Ordering::SeqCst)
80                .is_ok()
81            {
82                return true;
83            }
84        }
85    }
86
87    async fn run(&self, raw_args: Value) -> Result<Value> {
88        let args: DefuddleArgs = serde_json::from_value(raw_args)
89            .context("Invalid arguments for defuddle_fetch. Provide a 'url' string.")?;
90
91        let url = args
92            .url
93            .map(|u| u.trim().to_string())
94            .filter(|u| !u.is_empty())
95            .ok_or_else(|| anyhow!("defuddle_fetch requires a non-empty 'url'"))?;
96
97        // Reject anything that is not an HTTP/HTTPS URL before URL parsing.
98        // This prevents the LLM from accidentally using defuddle_fetch for
99        // local file reads, bare paths, or other non-web URLs.
100        let lower = url.to_ascii_lowercase();
101        if !lower.starts_with("http://") && !lower.starts_with("https://") {
102            return Err(anyhow!(
103                "defuddle_fetch only accepts http:// or https:// URLs for web content extraction. \
104                For local file reads, use exec_command with readonly shell inspection commands instead. \
105                Got: {url}"
106            ));
107        }
108
109        validate_target_url(&url)?;
110
111        if !self.try_consume() {
112            return Ok(cap_reached_response(&url));
113        }
114
115        let max_bytes = args.max_bytes.unwrap_or(MAX_BYTES).min(MAX_BYTES);
116        let timeout_secs = DEFAULT_TIMEOUT_SECS.min(MAX_TIMEOUT_SECS);
117
118        let (body, truncated) = match fetch_markdown(&url, timeout_secs, max_bytes).await {
119            Ok(t) => t,
120            Err(e) => {
121                return Ok(defuddle_fetch_error_response(&url, max_bytes, timeout_secs, &e));
122            }
123        };
124
125        let bytes = body.len();
126        Ok(json!({
127            "url": url,
128            "markdown": body,
129            "bytes": bytes,
130            "truncated": truncated,
131            "used_this_session": self.current_uses(),
132            "session_cap": SESSION_CAP,
133        }))
134    }
135}
136
137fn defuddle_fetch_error_response(url: &str, max_bytes: usize, timeout_secs: u64, err: &anyhow::Error) -> Value {
138    let message = err.to_string();
139    let lower = message.to_lowercase();
140    // Timeout / network-class failures take priority over HTTP status:
141    // a slow upstream that returns a 5xx after the body stalls will
142    // carry a "timed out" prefix, and the right hint in that case is
143    // "retry later / use web_fetch" — not "the service is down".
144    let (error_type, next_action) = if lower.contains("timeout") || lower.contains("timed out") {
145        (
146            "network_error",
147            "defuddle.md timed out. The upstream service may be slow. Use web_fetch on a known URL as a fallback.",
148        )
149    } else if lower.contains("dns") || lower.contains("connection refused") {
150        (
151            "network_error",
152            "defuddle.md is unreachable from this network. Use web_fetch on a known URL as a fallback.",
153        )
154    } else if let Some(status) = extract_http_status(&message) {
155        let action = match status {
156            403 | 429 => {
157                "defuddle.md rate-limited or rejected the request, so a retry will hit the same limit; the session cap is also exhausted. Use web_fetch on a known URL as a fallback."
158            }
159            404 => {
160                "defuddle.md returned 404. The upstream service path may have changed; use web_fetch directly instead."
161            }
162            500..=599 => "defuddle.md is having a server issue. Use web_fetch on a known URL as a fallback.",
163            _ => "defuddle.md returned an unexpected status. Use web_fetch on a known URL as a fallback.",
164        };
165        ("http_error", action)
166    } else {
167        ("unknown_error", "defuddle.md request failed. Use web_fetch on a known URL as a fallback.")
168    };
169    json!({
170        "error": format!("defuddle_fetch failed for '{}': {}", url, message),
171        "url": url,
172        "max_bytes": max_bytes,
173        "timeout_secs": timeout_secs,
174        "error_type": error_type,
175        "next_action": next_action,
176        "used_this_session": 1,
177        "session_cap": SESSION_CAP,
178    })
179}
180
181fn cap_reached_response(url: &str) -> Value {
182    json!({
183        "error": "defuddle_fetch session cap reached",
184        "url": url,
185        "session_cap": SESSION_CAP,
186        "next_action": "defuddle_fetch can be called at most once per session because the defuddle.md service is rate-limited. Use web_fetch (which goes through vtcode's safe HTTP path) for additional pages in this session."
187    })
188}
189
190/// Validate that the requested URL is something we'd want to point the
191/// public defuddle.md service at. We do not run the defuddle.md request
192/// itself until after this check, so an obviously-bad URL never leaves the
193/// process.
194fn validate_target_url(url: &str) -> Result<()> {
195    let parsed = Url::parse(url).context("defuddle_fetch: invalid url")?;
196    match parsed.scheme() {
197        "http" | "https" => {}
198        other => {
199            return Err(anyhow!("defuddle_fetch: refusing to fetch {other}:// URL (only http/https are allowed)"));
200        }
201    }
202    let host = parsed
203        .host_str()
204        .filter(|h| !h.is_empty())
205        .ok_or_else(|| anyhow!("defuddle_fetch: refusing to fetch a URL with no host"))?;
206    // Block private / loopback / link-local / broadcast / multicast
207    // hosts so a malicious URL can't turn defuddle into an SSRF relay.
208    // Mirrors the `web_fetch` check via the shared `is_private_host` helper.
209    if is_private_host(host) {
210        return Err(anyhow!("defuddle_fetch: refusing to fetch private/local host '{host}'"));
211    }
212    Ok(())
213}
214
215async fn fetch_markdown(url: &str, timeout_secs: u64, max_bytes: usize) -> Result<(String, bool)> {
216    // Per the user's note: `curl defuddle.md/{link}`. We must NOT use
217    // `Url::join` here because the Rust URL spec treats absolute URLs as
218    // absolute on join, which would mean the request goes straight to the
219    // target host and defuddle.md is bypassed entirely. Instead, encode the
220    // input URL as a single path segment and append it to the base URL.
221    //
222    // SECURITY: this is the only place the request URL is constructed. A
223    // future refactor that "cleans up" the string concatenation in favor
224    // of `Url::join` or any other URL builder will silently turn the
225    // tool into an SSRF relay. The regression test
226    // `request_url_targets_defuddle_host_not_target_host` guards this.
227    let encoded = percent_encode_path(url);
228    let target = format!("{DEFUDDLE_BASE_URL}{encoded}");
229
230    let builder = reqwest::Client::builder()
231        .timeout(Duration::from_secs(timeout_secs))
232        // Do NOT follow redirects from the upstream service. Defuddle is a
233        // thin proxy; following its redirects could leak into SSRF-prone
234        // behavior, and we already validated the input URL above.
235        .redirect(reqwest::redirect::Policy::none());
236    let client = vtcode_commons::http::apply_connect_timeout(builder)
237        .build()
238        .context("defuddle_fetch: failed to build HTTP client")?;
239
240    let response = client
241        .get(&target)
242        .header("Accept", "text/markdown, text/plain;q=0.9, */*;q=0.5")
243        .send()
244        .await
245        .context("defuddle_fetch: request failed")?;
246
247    let status = response.status();
248    if !status.is_success() {
249        return Err(anyhow!("defuddle.md returned HTTP {status}"));
250    }
251
252    let body = response.text().await.context("defuddle_fetch: failed to read response body")?;
253
254    Ok(truncate_markdown_body(body, max_bytes))
255}
256
257fn truncate_markdown_body(body: String, max_bytes: usize) -> (String, bool) {
258    if body.len() > max_bytes {
259        // Truncate to a hard cap so a giant page never blows up the agent.
260        let truncated = vtcode_commons::formatting::truncate_byte_budget(&body, max_bytes, "");
261        // `truncated` is `true` only when the upstream body exceeded the cap,
262        // not when it just happened to land exactly on it.
263        (truncated, true)
264    } else {
265        (body, false)
266    }
267}
268
269/// Percent-encode a string so it is safe to append as a single path segment
270/// to a base URL. We unreserved-encode everything except `:`, `/`, `?`, `#`,
271/// `[`, `]`, `@`, `!`, `$`, `&`, `'`, `(`, `)`, `*`, `+`, `,`, `;`, `=`
272/// (per RFC 3986 sub-delims) — those are left alone so an http(s) URL
273/// survives encoding. This is intentionally simpler than the full RFC 3986
274/// path-segment set because we know our input is a URL.
275fn percent_encode_path(input: &str) -> String {
276    use std::fmt::Write as _;
277
278    let mut out = String::with_capacity(input.len());
279    for byte in input.bytes() {
280        let unreserved = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~');
281        let sub_delim = matches!(
282            byte,
283            b':' | b'/'
284                | b'?'
285                | b'#'
286                | b'['
287                | b']'
288                | b'@'
289                | b'!'
290                | b'$'
291                | b'&'
292                | b'\''
293                | b'('
294                | b')'
295                | b'*'
296                | b'+'
297                | b','
298                | b';'
299                | b'='
300        );
301        if unreserved || sub_delim {
302            out.push(byte as char);
303        } else {
304            // Write directly into `out` instead of allocating a temporary
305            // String via format! for every encoded byte.
306            let _ = write!(out, "%{byte:02X}");
307        }
308    }
309    out
310}
311
312#[async_trait]
313impl Tool for DefuddleTool {
314    async fn execute(&self, args: Value) -> Result<Value> {
315        self.run(args).await
316    }
317
318    fn name(&self) -> &str {
319        tools::DEFUDDLE_FETCH
320    }
321
322    fn description(&self) -> &str {
323        DEFUDDLE_FETCH_DESCRIPTION
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    #[test]
332    fn missing_url_is_rejected() {
333        let tool = DefuddleTool::new();
334        let result = tokio::runtime::Runtime::new().unwrap().block_on(tool.run(json!({})));
335        assert!(result.is_err());
336    }
337
338    #[test]
339    fn empty_url_is_rejected() {
340        let tool = DefuddleTool::new();
341        let result = tokio::runtime::Runtime::new()
342            .unwrap()
343            .block_on(tool.run(json!({ "url": "   " })));
344        assert!(result.is_err());
345    }
346
347    #[test]
348    fn non_http_scheme_is_rejected() {
349        let tool = DefuddleTool::new();
350        for bad in ["javascript:alert(1)", "file:///etc/passwd", "data:text/html,hi"] {
351            let result = tokio::runtime::Runtime::new()
352                .unwrap()
353                .block_on(tool.run(json!({ "url": bad })));
354            assert!(result.is_err(), "should reject {bad}");
355        }
356    }
357
358    #[test]
359    fn local_file_paths_are_rejected_before_url_parsing() {
360        let tool = DefuddleTool::new();
361        for bad in [
362            "/Users/vinhnguyenxuan/Documents/podcast/build-video.sh",
363            "./relative/path.txt",
364            "/etc/passwd",
365            "C:\\Users\\file.txt",
366        ] {
367            let result = tokio::runtime::Runtime::new()
368                .unwrap()
369                .block_on(tool.run(json!({ "url": bad })));
370            assert!(result.is_err(), "should reject local path: {bad}");
371            let err_msg = result.unwrap_err().to_string();
372            assert!(err_msg.contains("exec_command"));
373            assert!(!err_msg.contains(&format!("unified_{}", "file")));
374        }
375    }
376
377    #[test]
378    fn session_cap_rejects_second_call() {
379        let tool = DefuddleTool::new();
380        // Manually mark the cap as consumed; we don't make a real network
381        // call here. `try_consume` is the same code path the live call uses.
382        assert!(tool.try_consume());
383        let payload = tokio::runtime::Runtime::new()
384            .unwrap()
385            .block_on(tool.run(json!({ "url": "https://example.com" })))
386            .expect("cap hit must be a structured JSON, not a runtime error");
387        assert_eq!(payload["error"], "defuddle_fetch session cap reached");
388        assert_eq!(payload["session_cap"], 1);
389    }
390
391    #[test]
392    fn reset_allows_one_more_call() {
393        let tool = DefuddleTool::new();
394        assert!(tool.try_consume());
395        assert!(!tool.try_consume());
396        tool.reset();
397        assert!(tool.try_consume());
398    }
399
400    #[test]
401    fn markdown_truncation_preserves_utf8_boundaries() {
402        let (body, truncated) = truncate_markdown_body("你好".to_owned(), 4);
403
404        assert_eq!(body, "你");
405        assert!(truncated);
406    }
407
408    #[test]
409    fn validate_target_url_rejects_bad_inputs() {
410        assert!(validate_target_url("https://example.com").is_ok());
411        assert!(validate_target_url("https://example.com/path?q=1").is_ok());
412        assert!(validate_target_url("http://example.com").is_ok());
413        assert!(validate_target_url("javascript:alert(1)").is_err());
414        assert!(validate_target_url("file:///etc/passwd").is_err());
415        assert!(validate_target_url("data:text/html,hi").is_err());
416        assert!(validate_target_url("not a url at all").is_err());
417    }
418
419    /// Regression test for review H2: defuddle must NOT relay requests to
420    /// private / loopback / link-local / broadcast / multicast hosts.
421    /// Otherwise a URL like `http://192.168.0.1/admin` would tunnel an
422    /// SSRF through the public defuddle.md service.
423    #[test]
424    fn validate_target_url_blocks_private_hosts() {
425        for bad in [
426            "http://10.0.0.1/",
427            "http://192.168.1.1/admin",
428            "http://172.16.0.1/",
429            "http://127.0.0.1/",
430            "http://169.254.169.254/latest/meta-data/", // AWS IMDS
431            "http://[::1]/",
432            "http://[fc00::1]/",
433            "http://[fe80::1]/",
434            "http://255.255.255.255/",
435            "http://224.0.0.1/",
436            "http://localhost/admin",
437        ] {
438            let result = validate_target_url(bad);
439            assert!(result.is_err(), "private host should be rejected: {bad}");
440            let msg = result.unwrap_err().to_string();
441            assert!(
442                msg.contains("private") || msg.contains("local"),
443                "error should mention private/local; got: {msg} for {bad}"
444            );
445        }
446    }
447
448    #[test]
449    fn percent_encode_path_preserves_url_sub_delims() {
450        // Common http(s) URL: every byte is unreserved or sub-delim, so the
451        // encoded output should equal the input.
452        let url = "https://example.com/path?q=1&r=2#frag";
453        assert_eq!(percent_encode_path(url), url);
454    }
455
456    #[test]
457    fn percent_encode_path_escapes_spaces_and_unicode() {
458        let encoded = percent_encode_path("https://example.com/has space and \u{2603}");
459        assert!(encoded.starts_with("https://example.com/has%20space%20and%20%E2%98%83"));
460    }
461
462    #[test]
463    fn request_url_targets_defuddle_host_not_target_host() {
464        // Build the same URL the network call would build and assert it points
465        // at defuddle.md, not the user-supplied target. This guards against
466        // regressions where someone reintroduces `Url::join` (which would
467        // silently bypass defuddle.md for absolute URLs).
468        let user_url = "https://example.com/x";
469        let built = format!("{DEFUDDLE_BASE_URL}{}", percent_encode_path(user_url));
470        let parsed = Url::parse(&built).expect("defuddle URL must parse");
471        assert_eq!(parsed.host_str(), Some("defuddle.md"));
472        // The full input URL survives as a path segment on defuddle.md. We
473        // don't compare exact bytes (the URL parser may normalize `//`) —
474        // we just assert the target host is referenced somewhere in the path.
475        let path = parsed.path();
476        assert!(path.contains("example.com"), "defuddle.md URL should reference the user host in its path: {path}");
477    }
478
479    /// Regression test for turn_578: when defuddle.md rate-limits the
480    /// request, the structured error must say so and point the agent to
481    /// web_fetch as a fallback. It must not look like a generic
482    /// "PermissionDenied" (which is what the previous shape produced).
483    #[test]
484    fn error_response_classifies_403_and_suggests_web_fetch() {
485        let err = anyhow::anyhow!("defuddle.md returned HTTP 403");
486        let response = defuddle_fetch_error_response("https://example.com", MAX_BYTES, DEFAULT_TIMEOUT_SECS, &err);
487        assert_eq!(response["error_type"], "http_error");
488        assert!(
489            response["next_action"].as_str().unwrap_or("").contains("web_fetch"),
490            "next_action should fall back to web_fetch; got: {}",
491            response["next_action"]
492        );
493        assert!(response["session_cap"].is_number());
494    }
495
496    /// Network-level failures should classify distinctly from HTTP errors.
497    #[test]
498    fn error_response_classifies_timeout_as_network_error() {
499        let err = anyhow::anyhow!("request timed out after 30s");
500        let response = defuddle_fetch_error_response("https://example.com", MAX_BYTES, DEFAULT_TIMEOUT_SECS, &err);
501        assert_eq!(response["error_type"], "network_error");
502    }
503}