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. 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 {
51 json!({
52 "type": "object",
53 "properties": {
54 "url": {
55 "type": "string",
56 "description": "URL to fetch (HTTPS required by default)"
57 },
58 "prompt": {
59 "type": "string",
60 "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."
61 },
62 "max_bytes": {
63 "type": "integer",
64 "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."
65 },
66 "timeout_secs": {
67 "type": "integer",
68 "description": "Request timeout in seconds (default: 30, max: 120)"
69 }
70 },
71 "required": ["url"],
72 "additionalProperties": false
73 })
74}
75
76#[derive(Debug, Deserialize)]
77struct WebFetchArgs {
78 url: String,
79 prompt: String,
80 #[serde(default)]
81 max_bytes: Option<usize>,
82 #[serde(default)]
83 timeout_secs: Option<u64>,
84}
85
86#[derive(Clone)]
88pub struct WebFetchTool {
89 pub mode: vtcode_config::WebFetchMode,
91 pub blocked_domains: HashSet<String>,
93 pub blocked_patterns: Vec<String>,
95 pub allowed_domains: HashSet<String>,
97 pub strict_https_only: bool,
99}
100
101struct FetchedWebContent {
102 content: String,
103 truncated_by_max_bytes: bool,
104 source_size_bytes: usize,
105}
106
107fn fetched_content_from_bytes(bytes: &[u8], max_bytes: usize) -> Result<FetchedWebContent> {
108 let source_size_bytes = bytes.len();
109 let truncated_by_max_bytes = source_size_bytes > max_bytes;
110 if !truncated_by_max_bytes {
111 return Ok(FetchedWebContent {
112 content: String::from_utf8(bytes.to_vec()).context("Response body is not valid UTF-8")?,
113 truncated_by_max_bytes,
114 source_size_bytes,
115 });
116 }
117
118 let valid_end = match std::str::from_utf8(&bytes[..max_bytes]) {
123 Ok(_) => max_bytes,
124 Err(err) => err.valid_up_to(),
125 };
126
127 let content = String::from_utf8(bytes[..valid_end].to_vec()).context("Response body is not valid UTF-8")?;
128 Ok(FetchedWebContent { content, truncated_by_max_bytes, source_size_bytes })
129}
130
131async fn web_fetch_temp_dir() -> Result<PathBuf> {
134 VtCodePaths::resolve()
135 .context("Could not resolve VT Code cache directory")?
136 .ensure_cache_child_dir(TEMP_SUBDIR)
137 .context("Failed to create web-fetch cache directory")
138}
139
140async fn write_to_temp_file(content: &str, url: &str) -> Result<PathBuf> {
143 let temp_dir = web_fetch_temp_dir().await?;
144 let timestamp = std::time::SystemTime::now()
145 .duration_since(std::time::UNIX_EPOCH)
146 .unwrap_or_default()
147 .as_micros();
148
149 let url_hash = {
151 use std::collections::hash_map::DefaultHasher;
152 use std::hash::{Hash, Hasher};
153 let mut hasher = DefaultHasher::new();
154 url.hash(&mut hasher);
155 format!("{:016x}", hasher.finish())
156 };
157
158 let filename = format!("{url_hash}_{timestamp}.txt");
159 let file_path = temp_dir.join(&filename);
160
161 let bytes = content.as_bytes().to_vec();
162 let write_path = file_path.clone();
163 tokio::task::spawn_blocking(move || VtCodePaths::write_private_file_atomic(&write_path, &bytes))
164 .await
165 .context("web-fetch cache writer task panicked")?
166 .with_context(|| format!("Failed to write temp file: {}", file_path.display()))?;
167
168 Ok(file_path)
169}
170
171pub async fn cleanup_old_web_fetch_temps(max_age_secs: u64) -> Result<usize> {
173 let temp_dir = match web_fetch_temp_dir().await {
174 Ok(d) => d,
175 Err(_) => return Ok(0),
176 };
177
178 if tokio::fs::metadata(&temp_dir).await.is_err() {
179 return Ok(0);
180 }
181
182 let cutoff = std::time::SystemTime::now()
183 .checked_sub(std::time::Duration::from_secs(max_age_secs))
184 .unwrap_or(std::time::UNIX_EPOCH);
185
186 let mut removed = 0;
187 let mut entries = match tokio::fs::read_dir(&temp_dir).await {
188 Ok(e) => e,
189 Err(_) => return Ok(0),
190 };
191
192 while let Some(entry) = entries.next_entry().await.unwrap_or(None) {
193 let path = entry.path();
194 if !path.is_file() {
195 continue;
196 }
197 if let Ok(metadata) = entry.metadata().await
198 && let Ok(modified) = metadata.modified()
199 && modified <= cutoff
200 && tokio::fs::remove_file(&path).await.is_ok()
201 {
202 removed += 1;
203 }
204 }
205
206 if removed > 0 {
207 tracing::info!(count = removed, "Cleaned up old web_fetch temp files");
208 }
209
210 Ok(removed)
211}
212
213impl WebFetchTool {
214 pub fn new() -> Self {
215 Self {
216 mode: vtcode_config::WebFetchMode::Restricted,
217 blocked_domains: HashSet::new(),
218 blocked_patterns: Vec::new(),
219 allowed_domains: HashSet::new(),
220 strict_https_only: true,
221 }
222 }
223
224 pub fn with_config(
226 mode: vtcode_config::WebFetchMode,
227 blocked_domains: Vec<String>,
228 blocked_patterns: Vec<String>,
229 allowed_domains: Vec<String>,
230 strict_https_only: bool,
231 ) -> Self {
232 Self {
233 mode,
234 blocked_domains: blocked_domains.into_iter().collect(),
235 blocked_patterns,
236 allowed_domains: allowed_domains.into_iter().collect(),
237 strict_https_only,
238 }
239 }
240
241 pub fn from_config(config: &vtcode_config::WebFetchConfig) -> Self {
245 Self::with_config(
246 config.mode,
247 config.blocked_domains.clone(),
248 config.blocked_patterns.clone(),
249 config.allowed_domains.clone(),
250 config.strict_https_only,
251 )
252 }
253
254 async fn fetch_url_content(&self, url: &str, max_bytes: usize, timeout_secs: u64) -> Result<FetchedWebContent> {
255 self.validate_url(url)?;
257
258 let budget = request_budget::RequestBudget::current();
259 let redirect_budget = budget.clone();
260 let default_headers = Self::default_headers();
261
262 let blocked_domains = self.blocked_domains.clone();
265 let blocked_patterns = self.blocked_patterns.clone();
266 let allowed_domains = self.allowed_domains.clone();
267 let strict_https = self.strict_https_only;
268 let redirect_policy = reqwest::redirect::Policy::custom(move |attempt| {
269 if attempt.previous().len() >= 5 {
270 return attempt.stop();
271 }
272 let next_url = attempt.url();
273 let next_str = next_url.as_str();
274
275 if strict_https && !next_str.starts_with("https://") {
277 return attempt.stop();
278 }
279
280 if let Ok(domain) = extract_domain(next_str) {
282 if is_private_host(&domain) {
283 return attempt.stop();
284 }
285 let domain_lower = domain.to_ascii_lowercase();
286 if domain_lower.ends_with(".local")
287 || domain_lower.ends_with(".internal")
288 || domain_lower.ends_with(".localhost")
289 || domain_lower.ends_with(".test")
290 || domain_lower.ends_with(".invalid")
291 || domain_lower.ends_with(".home.arpa")
292 {
293 return attempt.stop();
294 }
295 let mut all_blocked = BUILTIN_BLOCKED_DOMAINS.to_vec();
297 all_blocked.extend(blocked_domains.iter().map(|s| s.as_str()));
298 for blocked in &all_blocked {
299 if next_str.to_lowercase().contains(blocked) {
300 return attempt.stop();
301 }
302 }
303 let mut all_patterns = BUILTIN_BLOCKED_PATTERNS.to_vec();
305 all_patterns.extend(blocked_patterns.iter().map(|s| s.as_str()));
306 for pattern in &all_patterns {
307 if next_str.to_lowercase().contains(pattern) {
308 return attempt.stop();
309 }
310 }
311 for allowed in &allowed_domains {
313 if domain_matches_allowed(&domain, allowed) {
314 return follow_with_budget(attempt, redirect_budget.as_ref());
315 }
316 }
317 }
318 follow_with_budget(attempt, redirect_budget.as_ref())
319 });
320
321 let client = vtcode_commons::http::apply_connect_timeout(
322 reqwest::Client::builder()
323 .default_headers(default_headers)
324 .timeout(std::time::Duration::from_secs(timeout_secs))
325 .redirect(redirect_policy),
326 )
327 .build()?;
328
329 let response = fetch_response(&client, url, max_bytes, timeout_secs, budget.as_ref()).await?;
330
331 let content_type = response
332 .headers()
333 .get("content-type")
334 .and_then(|h| h.to_str().ok())
335 .unwrap_or("")
336 .to_string();
337
338 self.validate_content_type(&content_type)?;
340
341 if let Some(content_length) = response.content_length()
350 && content_length > max_bytes as u64
351 {
352 return Err(anyhow!(
353 "Response Content-Length {} exceeds max_bytes {}; refusing to buffer the full body",
354 content_length,
355 max_bytes
356 ));
357 }
358
359 let mut bytes = Vec::with_capacity(max_bytes.min(64 * 1024));
360 let mut stream = response.bytes_stream();
361 let mut max_reached = false;
362 while let Some(chunk) = stream.next().await {
363 let chunk = chunk.context("Failed to read response body")?;
364 if bytes.len() >= max_bytes {
365 max_reached = true;
366 break;
367 }
368 let take = chunk.len().min(max_bytes - bytes.len());
369 bytes.extend_from_slice(&chunk[..take]);
370 }
371
372 let mut fetched = fetched_content_from_bytes(&bytes, max_bytes)?;
373 if max_reached || bytes.len() >= max_bytes {
378 fetched.truncated_by_max_bytes = true;
379 }
380 Ok(fetched)
381 }
382
383 fn validate_url(&self, url: &str) -> Result<()> {
384 let parsed = Url::parse(url).map_err(|error| {
385 anyhow!(
386 "web_fetch only accepts remote HTTP(S) URLs; use read_file or unified_file to read local files: {error}"
387 )
388 })?;
389 if !matches!(parsed.scheme(), "http" | "https") {
390 bail!("web_fetch only accepts remote HTTP(S) URLs; use read_file or unified_file to read local files");
391 }
392
393 if self.strict_https_only && parsed.scheme() != "https" {
395 return Err(anyhow!("Only HTTPS URLs are allowed for security"));
396 }
397
398 let domain = extract_domain(url).map_err(|e| anyhow!("Failed to parse URL for security validation: {e}"))?;
401
402 if is_private_host(&domain) {
404 return Err(anyhow!("Access to local/private networks is blocked"));
405 }
406
407 if is_blocked_special_use_tld(&domain) {
410 return Err(anyhow!("Access to local/private networks is blocked"));
411 }
412
413 let url_lower = url.to_lowercase();
414
415 match self.mode {
417 vtcode_config::WebFetchMode::Whitelist => self.validate_whitelist_mode(&url_lower)?,
418 vtcode_config::WebFetchMode::Restricted => self.validate_restricted_mode(&url_lower)?,
419 }
420
421 Ok(())
422 }
423
424 fn validate_whitelist_mode(&self, url: &str) -> Result<()> {
425 let domain = extract_domain(url)?;
427
428 if self.allowed_domains.is_empty() {
429 return Err(anyhow!(
430 "Whitelist mode enabled but no domains are whitelisted. Configure allowed_domains in web_fetch settings."
431 ));
432 }
433
434 for allowed in &self.allowed_domains {
436 if domain_matches_allowed(&domain, allowed) {
437 return Ok(());
438 }
439 }
440
441 Err(anyhow!(
442 "Domain '{domain}' is not in the whitelist. Only explicitly allowed domains are permitted in whitelist mode."
443 ))
444 }
445
446 fn validate_restricted_mode(&self, url: &str) -> Result<()> {
447 let url_lower = url.to_lowercase();
449
450 let domain = extract_domain(url)?;
452 for allowed in &self.allowed_domains {
453 if domain_matches_allowed(&domain, allowed) {
454 return Ok(());
455 }
456 }
457
458 self.validate_url_safety(&url_lower)?;
460
461 Ok(())
462 }
463
464 fn validate_url_safety(&self, url: &str) -> Result<()> {
465 let mut all_blocked_domains = BUILTIN_BLOCKED_DOMAINS.to_vec();
467 all_blocked_domains.extend(self.blocked_domains.iter().map(|s| s.as_str()));
468
469 let mut all_blocked_patterns = BUILTIN_BLOCKED_PATTERNS.to_vec();
471 all_blocked_patterns.extend(self.blocked_patterns.iter().map(|s| s.as_str()));
472
473 for domain in &all_blocked_domains {
475 if url.contains(domain) {
476 return Err(anyhow!(
477 "Access to sensitive domain '{domain}' is blocked for privacy and security reasons"
478 ));
479 }
480 }
481
482 for pattern in &all_blocked_patterns {
484 if url.contains(pattern) {
485 return Err(anyhow!(
486 "URL contains sensitive pattern '{pattern}'. Fetching URLs with credentials or sensitive data is blocked"
487 ));
488 }
489 }
490
491 self.check_malicious_indicators(url)?;
493
494 Ok(())
495 }
496
497 fn check_malicious_indicators(&self, url: &str) -> Result<()> {
498 for pattern in MALICIOUS_PATTERNS {
499 if url.contains(pattern) {
500 return Err(anyhow!("URL contains potentially malicious pattern. Access blocked for safety"));
501 }
502 }
503
504 Ok(())
505 }
506
507 fn validate_content_type(&self, content_type: &str) -> Result<()> {
508 if content_type.is_empty() {
509 return Ok(());
510 }
511
512 let allowed_types = [
513 "text/html",
514 "text/plain",
515 "text/markdown",
516 "application/json",
517 "application/xml",
518 "text/xml",
519 "application/javascript",
520 "text/css",
521 "text/javascript",
522 "application/xhtml+xml",
523 ];
524
525 let content_type_lower = content_type.to_lowercase();
528 let media_type = content_type_lower.split(';').next().unwrap_or(&content_type_lower).trim();
529
530 if allowed_types.contains(&media_type) {
531 Ok(())
532 } else {
533 Err(anyhow!(
534 "Content type '{content_type}' is not supported. Only text-based content types are allowed."
535 ))
536 }
537 }
538
539 async fn run(&self, raw_args: Value) -> Result<Value> {
540 let args: WebFetchArgs = serde_json::from_value(raw_args)
541 .context("Invalid arguments for web_fetch tool. Provide 'url' (and optionally 'prompt').")?;
542
543 let max_bytes = args.max_bytes.map(|v| v.min(MAX_ALLOWED_BYTES)).unwrap_or(MAX_CONTENT_SIZE);
544 let timeout_secs = args
545 .timeout_secs
546 .map(|v| v.min(MAX_ALLOWED_TIMEOUT_SECS))
547 .unwrap_or(DEFAULT_TIMEOUT_SECS);
548
549 let fetched = match self.fetch_url_content(&args.url, max_bytes, timeout_secs).await {
551 Ok(fetched) => fetched,
552 Err(e) => {
553 return Ok(web_fetch_error_response(&args.url, max_bytes, timeout_secs, &e));
559 }
560 };
561 let content = fetched.content;
562
563 let content_length = content.len();
564
565 if content_length == 0 {
566 return Ok(json!({
567 "error": format!(
568 "web_fetch: no content fetched from '{}'. The URL may be unreachable, returned empty content, or used an unsupported content-type.",
569 args.url
570 ),
571 "url": args.url,
572 "error_type": "empty_content",
573 "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."
574 }));
575 }
576
577 let temp_path = write_to_temp_file(&content, &args.url).await?;
580 let temp_path_str = temp_path.to_string_lossy().to_string();
581
582 let preview_limit = 8000;
586 let extracted_text = if html_preview::looks_like_html(&content) {
587 let text = html_preview::extract_text_preview(&content);
588 (!text.is_empty()).then_some(text)
589 } else {
590 None
591 };
592 let (preview, truncated, preview_kind, preview_basis_len) = match extracted_text {
593 Some(text) => {
594 let basis_len = text.len();
595 let truncated = basis_len > preview_limit;
596 let preview = if truncated {
597 vtcode_commons::formatting::truncate_byte_budget(&text, preview_limit, "...")
598 } else {
599 text
600 };
601 (preview, truncated, "text", basis_len)
602 }
603 None => {
604 let truncated = content_length > preview_limit;
605 let preview = if truncated {
606 vtcode_commons::formatting::truncate_byte_budget(&content, preview_limit, "...")
607 } else {
608 content.clone()
609 };
610 (preview, truncated, "raw", content_length)
611 }
612 };
613
614 if let Err(e) = cleanup_old_web_fetch_temps(TEMP_MAX_AGE_SECS).await {
616 tracing::debug!(error = %e, "Periodic web_fetch temp cleanup failed");
617 }
618
619 let mut response = json!({
626 "url": args.url,
627 "prompt": args.prompt,
628 "temp_file": temp_path_str,
629 "preview": preview,
630 "preview_kind": preview_kind,
631 "content_length": content_length,
632 "truncated": truncated,
633 "no_spool": true,
634 "next_action_hint": if preview_kind == "text" {
635 "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."
636 } else {
637 "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."
638 }
639 });
640
641 if truncated {
643 response["overflow"] = json!(format!("[+{} more characters]", preview_basis_len - preview_limit));
644 }
645
646 if fetched.truncated_by_max_bytes {
647 response["truncated_by_max_bytes"] = json!(true);
648 response["max_bytes"] = json!(max_bytes);
649 response["source_size_bytes"] = json!(fetched.source_size_bytes);
650 response["next_action_hint"] = json!(
651 "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."
652 );
653 }
654
655 Ok(response)
656 }
657}
658
659impl WebFetchTool {
660 fn default_headers() -> HeaderMap {
664 let mut headers = HeaderMap::new();
665 headers.insert(ACCEPT, HeaderValue::from_static("text/markdown, */*"));
666 headers.insert(USER_AGENT, HeaderValue::from_static("VT Code/1.0 (compatible; web-fetch tool)"));
667 headers
668 }
669}
670
671async fn fetch_response(
672 client: &reqwest::Client,
673 url: &str,
674 max_bytes: usize,
675 timeout_secs: u64,
676 budget: Option<&request_budget::RequestBudget>,
677) -> Result<reqwest::Response> {
678 let transport = match &budget {
679 Some(budget) => Some(budget.lock_transport().await?),
680 None => None,
681 };
682 if let Some(budget) = &budget {
683 budget.admit(&Url::parse(url)?).map_err(|error| anyhow::Error::new(*error))?;
684 }
685 let response = client.get(url).send().await?;
686
687 if !response.status().is_success() {
688 let failure = errors::HttpFetchFailure {
689 status: response.status().as_u16(),
690 retry_after_ms: response
691 .headers()
692 .get(reqwest::header::RETRY_AFTER)
693 .and_then(|value| value.to_str().ok())
694 .and_then(errors::retry_after_ms),
695 };
696 if let Some(budget) = &budget {
697 let error = web_fetch_error_response(response.url().as_str(), max_bytes, timeout_secs, &failure.into());
698 if let Some(mut error) = crate::tools::registry::ToolExecutionError::from_tool_output(&error) {
699 if let Some(context) = error.debug_context.as_mut() {
700 context
701 .metadata
702 .push(("effective_origin".to_owned(), response.url().origin().ascii_serialization()));
703 }
704 return Err(budget.observe(response.url(), error).into());
705 }
706 bail!("failed to classify HTTP response");
707 }
708 return Err(failure.into());
709 }
710 drop(transport);
712 Ok(response)
713}
714
715fn follow_with_budget(
716 attempt: reqwest::redirect::Attempt<'_>,
717 budget: Option<&request_budget::RequestBudget>,
718) -> reqwest::redirect::Action {
719 if let Some(budget) = budget
720 && let Err(error) = budget.admit(attempt.url())
721 {
722 return attempt.error(*error);
723 }
724 attempt.follow()
725}
726
727impl Default for WebFetchTool {
728 fn default() -> Self {
729 Self::new()
730 }
731}
732
733#[async_trait]
734impl Tool for WebFetchTool {
735 async fn execute(&self, mut args: Value) -> Result<Value> {
736 if let Some(url) = args.get("url").and_then(Value::as_str) {
740 let max_bytes = args
741 .get("max_bytes")
742 .and_then(Value::as_u64)
743 .map(|value| value as usize)
744 .unwrap_or(MAX_CONTENT_SIZE);
745 let timeout_secs = args.get("timeout_secs").and_then(Value::as_u64).unwrap_or(DEFAULT_TIMEOUT_SECS);
746 if let Err(error) = self.validate_url(url) {
747 return Ok(web_fetch_error_response(url, max_bytes, timeout_secs, &error));
748 }
749 }
750
751 if let Some(obj) = args.as_object_mut() {
760 let has_url = obj.get("url").is_some_and(Value::is_string);
761 let has_prompt = obj.get("prompt").is_some_and(Value::is_string);
762
763 if has_url && !has_prompt {
764 obj.insert(
765 "prompt".to_string(),
766 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."),
767 );
768 }
769 }
770
771 self.run(args).await
772 }
773
774 fn name(&self) -> &str {
775 tools::WEB_FETCH
776 }
777
778 fn description(&self) -> &str {
779 WEB_FETCH_DESCRIPTION
780 }
781}
782
783#[cfg(test)]
784mod tests;