1use super::traits::Tool;
11use crate::config::constants::tools;
12use anyhow::{Context, Result, anyhow, bail};
13use async_trait::async_trait;
14use futures::stream::StreamExt;
15use hashbrown::HashSet;
16use reqwest::header::{ACCEPT, HeaderMap, HeaderValue, USER_AGENT};
17use serde::Deserialize;
18use serde_json::{Value, json};
19use std::path::PathBuf;
20use url::Url;
21use vtcode_commons::VtCodePaths;
22
23pub mod classify_helpers;
24pub mod domains;
25mod errors;
26mod html_preview;
27mod network_guards;
28pub(crate) mod request_budget;
29pub use classify_helpers::extract_http_status;
30pub use domains::{BUILTIN_BLOCKED_DOMAINS, BUILTIN_BLOCKED_PATTERNS, MALICIOUS_PATTERNS};
31use errors::web_fetch_error_response;
32use network_guards::{domain_matches_allowed, extract_domain};
33pub(crate) use network_guards::{is_blocked_special_use_tld, is_private_host};
34
35const DEFAULT_TIMEOUT_SECS: u64 = 30;
36const MAX_CONTENT_SIZE: usize = 500_000; const MAX_ALLOWED_BYTES: usize = 2_000_000; const MAX_ALLOWED_TIMEOUT_SECS: u64 = 120; const TEMP_SUBDIR: &str = "web_fetch";
42
43const TEMP_MAX_AGE_SECS: u64 = 3600;
45
46pub(crate) const WEB_FETCH_DESCRIPTION: &str = "Fetch a remote URL and return the start of the page inline. The result contains `preview` (readable text for HTML pages, else the first 8000 bytes of the body), `preview_kind` (`text` or `raw`), `content_length`, and a `temp_file` path holding the full fetched body; read `temp_file` only when the preview is not enough. The tool does not analyze the page: `prompt` is returned with the result to guide your own reading. Set format=markdown to get cleaned markdown inline from the defuddle.md extraction service instead; that mode allows 1 call per session. For docs domains, try /llms.txt first: for 'abc.com', fetch https://abc.com/llms.txt before the homepage, then traverse linked URLs for relevant Markdown sources. Prefer llms.txt over llms-full.txt, which can be multi-megabyte. A body larger than max_bytes is cut off and the result reports truncated_by_max_bytes and source_size_bytes, so you can retry with a larger max_bytes. Temp files are ephemeral and may be cleaned up after about an hour.";
47
48pub(crate) fn web_fetch_parameter_schema() -> Value {
55 json!({
56 "type": "object",
57 "properties": {
58 "url": {
59 "type": "string",
60 "description": "URL to fetch (HTTPS required by default)"
61 },
62 "prompt": {
63 "type": "string",
64 "description": "Question or instruction describing what to look for in the fetched content. It is returned with the result to guide your analysis; omit it to get a default summarize instruction."
65 },
66 "format": {
67 "type": "string",
68 "enum": ["summary", "markdown"],
69 "description": "Output mode (default: summary). summary fetches the page directly and returns a preview plus a temp_file path. markdown returns the page as cleaned markdown inline via the defuddle.md extraction service; it allows 1 call per session, accepts only remote http(s) URLs, caps max_bytes at 262144, and ignores prompt and timeout_secs."
70 },
71 "max_bytes": {
72 "type": "integer",
73 "description": "Maximum response body size in bytes (default: 500000, max: 2000000). The default fits most pages, including llms.txt, so set this only to raise the limit after a truncated_by_max_bytes result or to cap a very large page."
74 },
75 "timeout_secs": {
76 "type": "integer",
77 "description": "Request timeout in seconds (default: 30, max: 120)"
78 }
79 },
80 "required": ["url"],
81 "additionalProperties": false
82 })
83}
84
85#[derive(Debug, Deserialize)]
86struct WebFetchArgs {
87 url: String,
88 prompt: String,
89 #[serde(default)]
90 max_bytes: Option<usize>,
91 #[serde(default)]
92 timeout_secs: Option<u64>,
93}
94
95#[derive(Clone)]
97pub struct WebFetchTool {
98 pub mode: vtcode_config::WebFetchMode,
100 pub blocked_domains: HashSet<String>,
102 pub blocked_patterns: Vec<String>,
104 pub allowed_domains: HashSet<String>,
106 pub defuddle: crate::tools::defuddle::DefuddleTool,
109 pub strict_https_only: bool,
111}
112
113struct FetchedWebContent {
114 content: String,
115 truncated_by_max_bytes: bool,
116 source_size_bytes: usize,
117}
118
119fn fetched_content_from_bytes(bytes: &[u8], max_bytes: usize) -> Result<FetchedWebContent> {
120 let source_size_bytes = bytes.len();
121 let truncated_by_max_bytes = source_size_bytes > max_bytes;
122 if !truncated_by_max_bytes {
123 return Ok(FetchedWebContent {
124 content: String::from_utf8(bytes.to_vec()).context("Response body is not valid UTF-8")?,
125 truncated_by_max_bytes,
126 source_size_bytes,
127 });
128 }
129
130 let valid_end = match std::str::from_utf8(&bytes[..max_bytes]) {
135 Ok(_) => max_bytes,
136 Err(err) => err.valid_up_to(),
137 };
138
139 let content = String::from_utf8(bytes[..valid_end].to_vec()).context("Response body is not valid UTF-8")?;
140 Ok(FetchedWebContent { content, truncated_by_max_bytes, source_size_bytes })
141}
142
143async fn web_fetch_temp_dir() -> Result<PathBuf> {
146 VtCodePaths::resolve()
147 .context("Could not resolve VT Code cache directory")?
148 .ensure_cache_child_dir(TEMP_SUBDIR)
149 .context("Failed to create web-fetch cache directory")
150}
151
152async fn write_to_temp_file(content: &str, url: &str) -> Result<PathBuf> {
155 let temp_dir = web_fetch_temp_dir().await?;
156 let timestamp = std::time::SystemTime::now()
157 .duration_since(std::time::UNIX_EPOCH)
158 .unwrap_or_default()
159 .as_micros();
160
161 let url_hash = {
163 use std::collections::hash_map::DefaultHasher;
164 use std::hash::{Hash, Hasher};
165 let mut hasher = DefaultHasher::new();
166 url.hash(&mut hasher);
167 format!("{:016x}", hasher.finish())
168 };
169
170 let filename = format!("{url_hash}_{timestamp}.txt");
171 let file_path = temp_dir.join(&filename);
172
173 let bytes = content.as_bytes().to_vec();
174 let write_path = file_path.clone();
175 tokio::task::spawn_blocking(move || VtCodePaths::write_private_file_atomic(&write_path, &bytes))
176 .await
177 .context("web-fetch cache writer task panicked")?
178 .with_context(|| format!("Failed to write temp file: {}", file_path.display()))?;
179
180 Ok(file_path)
181}
182
183pub async fn cleanup_old_web_fetch_temps(max_age_secs: u64) -> Result<usize> {
185 let temp_dir = match web_fetch_temp_dir().await {
186 Ok(d) => d,
187 Err(_) => return Ok(0),
188 };
189
190 if tokio::fs::metadata(&temp_dir).await.is_err() {
191 return Ok(0);
192 }
193
194 let cutoff = std::time::SystemTime::now()
195 .checked_sub(std::time::Duration::from_secs(max_age_secs))
196 .unwrap_or(std::time::UNIX_EPOCH);
197
198 let mut removed = 0;
199 let mut entries = match tokio::fs::read_dir(&temp_dir).await {
200 Ok(e) => e,
201 Err(_) => return Ok(0),
202 };
203
204 while let Some(entry) = entries.next_entry().await.unwrap_or(None) {
205 let path = entry.path();
206 if !path.is_file() {
207 continue;
208 }
209 if let Ok(metadata) = entry.metadata().await
210 && let Ok(modified) = metadata.modified()
211 && modified <= cutoff
212 && tokio::fs::remove_file(&path).await.is_ok()
213 {
214 removed += 1;
215 }
216 }
217
218 if removed > 0 {
219 tracing::info!(count = removed, "Cleaned up old web_fetch temp files");
220 }
221
222 Ok(removed)
223}
224
225impl WebFetchTool {
226 pub fn new() -> Self {
227 Self {
228 mode: vtcode_config::WebFetchMode::Restricted,
229 blocked_domains: HashSet::new(),
230 blocked_patterns: Vec::new(),
231 allowed_domains: HashSet::new(),
232 defuddle: crate::tools::defuddle::DefuddleTool::new(),
233 strict_https_only: true,
234 }
235 }
236
237 pub fn with_config(
239 mode: vtcode_config::WebFetchMode,
240 blocked_domains: Vec<String>,
241 blocked_patterns: Vec<String>,
242 allowed_domains: Vec<String>,
243 strict_https_only: bool,
244 ) -> Self {
245 Self {
246 mode,
247 blocked_domains: blocked_domains.into_iter().collect(),
248 blocked_patterns,
249 allowed_domains: allowed_domains.into_iter().collect(),
250 defuddle: crate::tools::defuddle::DefuddleTool::new(),
251 strict_https_only,
252 }
253 }
254
255 pub fn from_config(config: &vtcode_config::WebFetchConfig) -> Self {
259 Self::with_config(
260 config.mode,
261 config.blocked_domains.clone(),
262 config.blocked_patterns.clone(),
263 config.allowed_domains.clone(),
264 config.strict_https_only,
265 )
266 }
267
268 async fn fetch_url_content(&self, url: &str, max_bytes: usize, timeout_secs: u64) -> Result<FetchedWebContent> {
269 self.validate_url(url)?;
271
272 let budget = request_budget::RequestBudget::current();
273 let redirect_budget = budget.clone();
274 let default_headers = Self::default_headers();
275
276 let blocked_domains = self.blocked_domains.clone();
279 let blocked_patterns = self.blocked_patterns.clone();
280 let allowed_domains = self.allowed_domains.clone();
281 let strict_https = self.strict_https_only;
282 let redirect_policy = reqwest::redirect::Policy::custom(move |attempt| {
283 if attempt.previous().len() >= 5 {
284 return attempt.stop();
285 }
286 let next_url = attempt.url();
287 let next_str = next_url.as_str();
288
289 if strict_https && !next_str.starts_with("https://") {
291 return attempt.stop();
292 }
293
294 if let Ok(domain) = extract_domain(next_str) {
296 if is_private_host(&domain) {
297 return attempt.stop();
298 }
299 let domain_lower = domain.to_ascii_lowercase();
300 if domain_lower.ends_with(".local")
301 || domain_lower.ends_with(".internal")
302 || domain_lower.ends_with(".localhost")
303 || domain_lower.ends_with(".test")
304 || domain_lower.ends_with(".invalid")
305 || domain_lower.ends_with(".home.arpa")
306 {
307 return attempt.stop();
308 }
309 let mut all_blocked = BUILTIN_BLOCKED_DOMAINS.to_vec();
311 all_blocked.extend(blocked_domains.iter().map(|s| s.as_str()));
312 for blocked in &all_blocked {
313 if next_str.to_lowercase().contains(blocked) {
314 return attempt.stop();
315 }
316 }
317 let mut all_patterns = BUILTIN_BLOCKED_PATTERNS.to_vec();
319 all_patterns.extend(blocked_patterns.iter().map(|s| s.as_str()));
320 for pattern in &all_patterns {
321 if next_str.to_lowercase().contains(pattern) {
322 return attempt.stop();
323 }
324 }
325 for allowed in &allowed_domains {
327 if domain_matches_allowed(&domain, allowed) {
328 return follow_with_budget(attempt, redirect_budget.as_ref());
329 }
330 }
331 }
332 follow_with_budget(attempt, redirect_budget.as_ref())
333 });
334
335 let client = vtcode_commons::http::apply_connect_timeout(
336 reqwest::Client::builder()
337 .default_headers(default_headers)
338 .timeout(std::time::Duration::from_secs(timeout_secs))
339 .redirect(redirect_policy),
340 )
341 .build()?;
342
343 let response = fetch_response(&client, url, max_bytes, timeout_secs, budget.as_ref()).await?;
344
345 let content_type = response
346 .headers()
347 .get("content-type")
348 .and_then(|h| h.to_str().ok())
349 .unwrap_or("")
350 .to_string();
351
352 self.validate_content_type(&content_type)?;
354
355 if let Some(content_length) = response.content_length()
364 && content_length > max_bytes as u64
365 {
366 return Err(anyhow!(
367 "Response Content-Length {} exceeds max_bytes {}; refusing to buffer the full body",
368 content_length,
369 max_bytes
370 ));
371 }
372
373 let mut bytes = Vec::with_capacity(max_bytes.min(64 * 1024));
374 let mut stream = response.bytes_stream();
375 let mut max_reached = false;
376 while let Some(chunk) = stream.next().await {
377 let chunk = chunk.context("Failed to read response body")?;
378 if bytes.len() >= max_bytes {
379 max_reached = true;
380 break;
381 }
382 let take = chunk.len().min(max_bytes - bytes.len());
383 bytes.extend_from_slice(&chunk[..take]);
384 }
385
386 let mut fetched = fetched_content_from_bytes(&bytes, max_bytes)?;
387 if max_reached || bytes.len() >= max_bytes {
392 fetched.truncated_by_max_bytes = true;
393 }
394 Ok(fetched)
395 }
396
397 fn validate_url(&self, url: &str) -> Result<()> {
398 let parsed = Url::parse(url).map_err(|error| {
399 anyhow!(
400 "web_fetch only accepts remote HTTP(S) URLs; use read_file or unified_file to read local files: {error}"
401 )
402 })?;
403 if !matches!(parsed.scheme(), "http" | "https") {
404 bail!("web_fetch only accepts remote HTTP(S) URLs; use read_file or unified_file to read local files");
405 }
406
407 if self.strict_https_only && parsed.scheme() != "https" {
409 return Err(anyhow!("Only HTTPS URLs are allowed for security"));
410 }
411
412 let domain = extract_domain(url).map_err(|e| anyhow!("Failed to parse URL for security validation: {e}"))?;
415
416 if is_private_host(&domain) {
418 return Err(anyhow!("Access to local/private networks is blocked"));
419 }
420
421 if is_blocked_special_use_tld(&domain) {
424 return Err(anyhow!("Access to local/private networks is blocked"));
425 }
426
427 let url_lower = url.to_lowercase();
428
429 match self.mode {
431 vtcode_config::WebFetchMode::Whitelist => self.validate_whitelist_mode(&url_lower)?,
432 vtcode_config::WebFetchMode::Restricted => self.validate_restricted_mode(&url_lower)?,
433 }
434
435 Ok(())
436 }
437
438 fn validate_whitelist_mode(&self, url: &str) -> Result<()> {
439 let domain = extract_domain(url)?;
441
442 if self.allowed_domains.is_empty() {
443 return Err(anyhow!(
444 "Whitelist mode enabled but no domains are whitelisted. Configure allowed_domains in web_fetch settings."
445 ));
446 }
447
448 for allowed in &self.allowed_domains {
450 if domain_matches_allowed(&domain, allowed) {
451 return Ok(());
452 }
453 }
454
455 Err(anyhow!(
456 "Domain '{domain}' is not in the whitelist. Only explicitly allowed domains are permitted in whitelist mode."
457 ))
458 }
459
460 fn validate_restricted_mode(&self, url: &str) -> Result<()> {
461 let url_lower = url.to_lowercase();
463
464 let domain = extract_domain(url)?;
466 for allowed in &self.allowed_domains {
467 if domain_matches_allowed(&domain, allowed) {
468 return Ok(());
469 }
470 }
471
472 self.validate_url_safety(&url_lower)?;
474
475 Ok(())
476 }
477
478 fn validate_url_safety(&self, url: &str) -> Result<()> {
479 let mut all_blocked_domains = BUILTIN_BLOCKED_DOMAINS.to_vec();
481 all_blocked_domains.extend(self.blocked_domains.iter().map(|s| s.as_str()));
482
483 let mut all_blocked_patterns = BUILTIN_BLOCKED_PATTERNS.to_vec();
485 all_blocked_patterns.extend(self.blocked_patterns.iter().map(|s| s.as_str()));
486
487 for domain in &all_blocked_domains {
489 if url.contains(domain) {
490 return Err(anyhow!(
491 "Access to sensitive domain '{domain}' is blocked for privacy and security reasons"
492 ));
493 }
494 }
495
496 for pattern in &all_blocked_patterns {
498 if url.contains(pattern) {
499 return Err(anyhow!(
500 "URL contains sensitive pattern '{pattern}'. Fetching URLs with credentials or sensitive data is blocked"
501 ));
502 }
503 }
504
505 self.check_malicious_indicators(url)?;
507
508 Ok(())
509 }
510
511 fn check_malicious_indicators(&self, url: &str) -> Result<()> {
512 for pattern in MALICIOUS_PATTERNS {
513 if url.contains(pattern) {
514 return Err(anyhow!("URL contains potentially malicious pattern. Access blocked for safety"));
515 }
516 }
517
518 Ok(())
519 }
520
521 fn validate_content_type(&self, content_type: &str) -> Result<()> {
522 if content_type.is_empty() {
523 return Ok(());
524 }
525
526 let allowed_types = [
527 "text/html",
528 "text/plain",
529 "text/markdown",
530 "application/json",
531 "application/xml",
532 "text/xml",
533 "application/javascript",
534 "text/css",
535 "text/javascript",
536 "application/xhtml+xml",
537 ];
538
539 let content_type_lower = content_type.to_lowercase();
542 let media_type = content_type_lower.split(';').next().unwrap_or(&content_type_lower).trim();
543
544 if allowed_types.contains(&media_type) {
545 Ok(())
546 } else {
547 Err(anyhow!(
548 "Content type '{content_type}' is not supported. Only text-based content types are allowed."
549 ))
550 }
551 }
552
553 async fn run(&self, raw_args: Value) -> Result<Value> {
554 let args: WebFetchArgs = serde_json::from_value(raw_args)
555 .context("Invalid arguments for web_fetch tool. Provide 'url' (and optionally 'prompt').")?;
556
557 let max_bytes = args.max_bytes.map(|v| v.min(MAX_ALLOWED_BYTES)).unwrap_or(MAX_CONTENT_SIZE);
558 let timeout_secs = args
559 .timeout_secs
560 .map(|v| v.min(MAX_ALLOWED_TIMEOUT_SECS))
561 .unwrap_or(DEFAULT_TIMEOUT_SECS);
562
563 let fetched = match self.fetch_url_content(&args.url, max_bytes, timeout_secs).await {
565 Ok(fetched) => fetched,
566 Err(e) => {
567 return Ok(web_fetch_error_response(&args.url, max_bytes, timeout_secs, &e));
573 }
574 };
575 let content = fetched.content;
576
577 let content_length = content.len();
578
579 if content_length == 0 {
580 return Ok(json!({
581 "error": format!(
582 "web_fetch: no content fetched from '{}'. The URL may be unreachable, returned empty content, or used an unsupported content-type.",
583 args.url
584 ),
585 "url": args.url,
586 "error_type": "empty_content",
587 "next_action": "The host returned an empty body. This may be a bot block, a JS-only page, or a real empty document. Try web_search to confirm the page exists; if it does, the content is probably JavaScript-rendered and you need a different tool."
588 }));
589 }
590
591 let temp_path = write_to_temp_file(&content, &args.url).await?;
594 let temp_path_str = temp_path.to_string_lossy().to_string();
595
596 let preview_limit = 8000;
600 let extracted_text = if html_preview::looks_like_html(&content) {
601 let text = html_preview::extract_text_preview(&content);
602 (!text.is_empty()).then_some(text)
603 } else {
604 None
605 };
606 let (preview, truncated, preview_kind, preview_basis_len) = match extracted_text {
607 Some(text) => {
608 let basis_len = text.len();
609 let truncated = basis_len > preview_limit;
610 let preview = if truncated {
611 vtcode_commons::formatting::truncate_byte_budget(&text, preview_limit, "...")
612 } else {
613 text
614 };
615 (preview, truncated, "text", basis_len)
616 }
617 None => {
618 let truncated = content_length > preview_limit;
619 let preview = if truncated {
620 vtcode_commons::formatting::truncate_byte_budget(&content, preview_limit, "...")
621 } else {
622 content.clone()
623 };
624 (preview, truncated, "raw", content_length)
625 }
626 };
627
628 if let Err(e) = cleanup_old_web_fetch_temps(TEMP_MAX_AGE_SECS).await {
630 tracing::debug!(error = %e, "Periodic web_fetch temp cleanup failed");
631 }
632
633 let mut response = json!({
640 "url": args.url,
641 "prompt": args.prompt,
642 "temp_file": temp_path_str,
643 "preview": preview,
644 "preview_kind": preview_kind,
645 "content_length": content_length,
646 "truncated": truncated,
647 "no_spool": true,
648 "next_action_hint": if preview_kind == "text" {
649 "Analyze the inline `preview` (readable text extracted from the page; scripts and styles removed) using `prompt` and answer the user directly. Only read `temp_file` (raw HTML) if you need content beyond the preview; it is ephemeral and may already be cleaned up."
650 } else {
651 "Analyze the inline `preview` (the start of the page) using `prompt` and answer the user directly. Only read `temp_file` if you need content beyond the preview; it is ephemeral and may already be cleaned up."
652 }
653 });
654
655 if truncated {
657 response["overflow"] = json!(format!("[+{} more characters]", preview_basis_len - preview_limit));
658 }
659
660 if fetched.truncated_by_max_bytes {
661 response["truncated_by_max_bytes"] = json!(true);
662 response["max_bytes"] = json!(max_bytes);
663 response["source_size_bytes"] = json!(fetched.source_size_bytes);
664 response["next_action_hint"] = json!(
665 "Read `temp_file` to get the fetched content. Analyze it using `prompt`. If it does not contain enough detail, retry web_fetch with a larger max_bytes or a more specific URL."
666 );
667 }
668
669 Ok(response)
670 }
671}
672
673impl WebFetchTool {
674 fn default_headers() -> HeaderMap {
678 let mut headers = HeaderMap::new();
679 headers.insert(ACCEPT, HeaderValue::from_static("text/markdown, */*"));
680 headers.insert(USER_AGENT, HeaderValue::from_static("VT Code/1.0 (compatible; web-fetch tool)"));
681 headers
682 }
683}
684
685async fn fetch_response(
686 client: &reqwest::Client,
687 url: &str,
688 max_bytes: usize,
689 timeout_secs: u64,
690 budget: Option<&request_budget::RequestBudget>,
691) -> Result<reqwest::Response> {
692 let transport = match &budget {
693 Some(budget) => Some(budget.lock_transport().await?),
694 None => None,
695 };
696 if let Some(budget) = &budget {
697 budget.admit(&Url::parse(url)?).map_err(|error| anyhow::Error::new(*error))?;
698 }
699 let response = client.get(url).send().await?;
700
701 if !response.status().is_success() {
702 let failure = errors::HttpFetchFailure {
703 status: response.status().as_u16(),
704 retry_after_ms: response
705 .headers()
706 .get(reqwest::header::RETRY_AFTER)
707 .and_then(|value| value.to_str().ok())
708 .and_then(errors::retry_after_ms),
709 };
710 if let Some(budget) = &budget {
711 let error = web_fetch_error_response(response.url().as_str(), max_bytes, timeout_secs, &failure.into());
712 if let Some(mut error) = crate::tools::registry::ToolExecutionError::from_tool_output(&error) {
713 if let Some(context) = error.debug_context.as_mut() {
714 context
715 .metadata
716 .push(("effective_origin".to_owned(), response.url().origin().ascii_serialization()));
717 }
718 return Err(budget.observe(response.url(), error).into());
719 }
720 bail!("failed to classify HTTP response");
721 }
722 return Err(failure.into());
723 }
724 drop(transport);
726 Ok(response)
727}
728
729fn follow_with_budget(
730 attempt: reqwest::redirect::Attempt<'_>,
731 budget: Option<&request_budget::RequestBudget>,
732) -> reqwest::redirect::Action {
733 if let Some(budget) = budget
734 && let Err(error) = budget.admit(attempt.url())
735 {
736 return attempt.error(*error);
737 }
738 attempt.follow()
739}
740
741impl Default for WebFetchTool {
742 fn default() -> Self {
743 Self::new()
744 }
745}
746
747#[async_trait]
748impl Tool for WebFetchTool {
749 async fn execute(&self, mut args: Value) -> Result<Value> {
750 if let Some(url) = args.get("url").and_then(Value::as_str) {
754 let max_bytes = args
755 .get("max_bytes")
756 .and_then(Value::as_u64)
757 .map(|value| value as usize)
758 .unwrap_or(MAX_CONTENT_SIZE);
759 let timeout_secs = args.get("timeout_secs").and_then(Value::as_u64).unwrap_or(DEFAULT_TIMEOUT_SECS);
760 if let Err(error) = self.validate_url(url) {
761 return Ok(web_fetch_error_response(url, max_bytes, timeout_secs, &error));
762 }
763 }
764
765 if let Some(obj) = args.as_object_mut() {
777 let wants_markdown = obj
778 .get("format")
779 .and_then(Value::as_str)
780 .is_some_and(|f| f.eq_ignore_ascii_case("markdown"));
781 if wants_markdown {
782 let mut defuddle_args = serde_json::Map::new();
783 if let Some(url) = obj.get("url").cloned() {
784 defuddle_args.insert("url".to_string(), url);
785 }
786 if let Some(max_bytes) = obj.get("max_bytes").cloned() {
787 defuddle_args.insert("max_bytes".to_string(), max_bytes);
788 }
789 return self.defuddle.execute(Value::Object(defuddle_args)).await;
790 }
791 }
792
793 if let Some(obj) = args.as_object_mut() {
794 let has_url = obj.get("url").is_some_and(Value::is_string);
795 let has_prompt = obj.get("prompt").is_some_and(Value::is_string);
796
797 if has_url && !has_prompt {
798 obj.insert(
799 "prompt".to_string(),
800 json!("Summarize this page concisely. Read the temp_file to get the full content, then focus on the primary purpose, key information, and any actionable details."),
801 );
802 }
803 }
804
805 self.run(args).await
806 }
807
808 fn name(&self) -> &str {
809 tools::WEB_FETCH
810 }
811
812 fn description(&self) -> &str {
813 WEB_FETCH_DESCRIPTION
814 }
815}
816
817#[cfg(test)]
818mod tests;