1use std::collections::HashMap;
11use std::sync::{Arc, Mutex, PoisonError};
12use std::time::Duration;
13
14use base64::Engine;
15use futures::StreamExt;
16use regex::Regex;
17use serde::{Deserialize, Serialize};
18use serde_json::json;
19use strands::models::Model;
20use strands::sandbox::{ExecuteOptions, Sandbox, shell_quote};
21use strands::tools::{FunctionTool, ToolContext, ToolError};
22use strands::types::{JsonSchema, JsonValue};
23use strands::{Agent, ModelSource};
24use tokio::time::Instant;
25
26use crate::sandbox::{SandboxShell, shell_of};
27
28pub(crate) const USER_AGENT: &str = "strands-harness/1.0";
30const TIMEOUT_SECONDS: u64 = 30;
31pub(crate) const MAX_BYTES: usize = 5 * 1024 * 1024;
33pub(crate) const MAX_CHARS: usize = 50_000;
35const CACHE_TTL: Duration = Duration::from_secs(15 * 60);
36
37const SUMMARIZER_PROMPT: &str = concat!(
38 "You answer a request about a single fetched web page. Use only the provided content; if it ",
39 "does not contain the answer, say so plainly. Be concise and factual, and preserve concrete ",
40 "details (names, numbers, quotes, links) relevant to the request."
41);
42
43pub(crate) const WEB_FETCH_DESCRIPTION: &str = concat!(
45 "Fetch a URL and answer a prompt about its content. Performs an HTTP GET, reduces the ",
46 "response to text, and asks a small fast model to answer the prompt using only that content, ",
47 "returning the answer rather than the raw page so large pages do not flood the conversation. ",
48 "Fetched content is cached for 15 minutes, so repeated fetches of the same URL are fast while ",
49 "each prompt is answered fresh."
50);
51
52#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(rename_all = "lowercase")]
55#[non_exhaustive]
56pub enum WebFetchTransport {
57 #[default]
59 Curl,
60 Direct,
62}
63
64#[derive(Debug, Clone, Default, bon::Builder)]
66pub struct WebFetchConfig {
67 #[builder(into)]
72 pub model: Option<ModelSource>,
73 pub transport: Option<WebFetchTransport>,
75}
76
77fn input_schema() -> JsonSchema {
78 json!({
79 "type": "object",
80 "properties": {
81 "url": {"type": "string", "description": "The http(s) URL to fetch."},
82 "prompt": {
83 "description": "What to extract from or answer about the fetched content. Leave empty to get the whole page content back verbatim instead of a model-generated answer.",
84 "type": "string"
85 }
86 },
87 "required": ["url"],
88 "additionalProperties": false
89 })
90}
91
92#[derive(Debug, Clone)]
94struct Fetched {
95 resolved_url: String,
96 text: String,
97}
98
99struct Cached {
100 expires: Instant,
101 page: Fetched,
102}
103
104struct Inner {
105 summarizer: Option<Arc<dyn Model>>,
106 transport: WebFetchTransport,
107 cache: Mutex<HashMap<String, Cached>>,
108 client: reqwest::Client,
109 patterns: Patterns,
110}
111
112struct Patterns {
113 url_chars: Regex,
114 authority: Regex,
115 script: Regex,
116 style: Regex,
117 tag: Regex,
118 blanks: Regex,
119 paragraphs: Regex,
120 charset: Regex,
121}
122
123impl Patterns {
124 fn new() -> Result<Self, regex::Error> {
125 Ok(Self {
126 url_chars: Regex::new(r"^[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]+$")?,
127 authority: Regex::new(r"(?i)^https?://[^/?#]")?,
128 script: Regex::new(r"(?i)<script\b[^>]*>[\s\S]*?</script>")?,
129 style: Regex::new(r"(?i)<style\b[^>]*>[\s\S]*?</style>")?,
130 tag: Regex::new(r"<[^>]+>")?,
131 blanks: Regex::new(r"[ \t]+")?,
132 paragraphs: Regex::new(r"\n\s*\n\s*\n+")?,
133 charset: Regex::new(r#"(?i)charset=["']?([\w.-]+)"#)?,
134 })
135 }
136
137 fn html_to_text(&self, html: &str) -> String {
138 let text = self.script.replace_all(html, " ");
139 let text = self.style.replace_all(&text, " ");
140 let text = self.tag.replace_all(&text, " ");
141 let text = self.blanks.replace_all(&text, " ");
142 self.paragraphs.replace_all(&text, "\n\n").trim().to_owned()
143 }
144
145 fn validate_url(&self, url: &str) -> Result<String, String> {
147 let url = url.trim();
148 if !self.url_chars.is_match(url) {
149 return Err("web_fetch URLs may only contain the characters RFC 3986 allows; percent-encode spaces and non-ASCII characters (and punycode the host) and retry.".to_owned());
150 }
151 let quoted = JsonValue::from(url).to_string();
152 let parsed = reqwest::Url::parse(url).map_err(|_| format!("web_fetch could not parse the URL {quoted}."))?;
153 if !matches!(parsed.scheme(), "http" | "https") {
154 return Err(format!("web_fetch only supports http(s) URLs, got {quoted}."));
155 }
156 let has_host = parsed.host_str().is_some_and(|host| !host.is_empty());
157 if !has_host || !self.authority.is_match(url) {
158 return Err(format!("web_fetch URL has no host: {quoted}."));
159 }
160 Ok(url.to_owned())
161 }
162
163 fn decode(&self, data: &[u8], content_type: &str) -> String {
166 let encoding = self
167 .charset
168 .captures(content_type)
169 .and_then(|captures| captures.get(1))
170 .and_then(|label| encoding_rs::Encoding::for_label(label.as_str().as_bytes()))
171 .unwrap_or(encoding_rs::UTF_8);
172 encoding.decode_with_bom_removal(data).0.into_owned()
173 }
174
175 fn to_text(&self, data: &[u8], content_type: &str, resolved_url: &str, url: &str) -> Fetched {
176 let raw = self.decode(data, content_type);
177 let text = if content_type.to_lowercase().contains("html") {
178 self.html_to_text(&raw)
179 } else {
180 raw
181 };
182 let resolved_url = resolved_url.trim();
183 Fetched {
184 resolved_url: if resolved_url.is_empty() { url } else { resolved_url }.to_owned(),
185 text: text.chars().take(MAX_CHARS).collect(),
186 }
187 }
188}
189
190fn curl_command(url: &str) -> String {
196 format!(
197 "f=$(mktemp -t strands-web-fetch.XXXXXX) && curl -sSL -g --fail --proto '=http,https' --proto-redir '=http,https' --max-time {TIMEOUT_SECONDS} -A {} -o \"$f\" -w '%{{content_type}}\\n%{{url_effective}}\\n' -- {} && head -c {MAX_BYTES} \"$f\" | base64; s=$?; rm -f \"$f\"; exit $s",
198 shell_quote(USER_AGENT),
199 shell_quote(url)
200 )
201}
202
203fn powershell_curl_command(url: &str) -> String {
207 let quoted = format!("'{}'", url.replace('\'', "''"));
208 [
209 "$f = Join-Path ([IO.Path]::GetTempPath()) \"strands-web-fetch-$([guid]::NewGuid())\"".to_owned(),
210 "$s = 127".to_owned(),
211 "try {".to_owned(),
212 format!(
213 " curl.exe -sSL -g --fail --proto '=http,https' --proto-redir '=http,https' --max-time {TIMEOUT_SECONDS} -A '{USER_AGENT}' -o $f --stderr \"$f.err\" -w '%{{content_type}}\\n%{{url_effective}}\\n' {quoted}"
214 ),
215 " $s = $LASTEXITCODE".to_owned(),
216 " if ($s -eq 0) {".to_owned(),
217 " $in = [IO.File]::OpenRead($f)".to_owned(),
218 format!(
219 " try {{ $b = (New-Object IO.BinaryReader $in).ReadBytes([Math]::Min($in.Length, {MAX_BYTES})) }} finally {{ $in.Dispose() }}"
220 ),
221 " [Convert]::ToBase64String($b)".to_owned(),
222 " } elseif (Test-Path -LiteralPath \"$f.err\") { [Console]::Error.Write([IO.File]::ReadAllText(\"$f.err\")) }"
223 .to_owned(),
224 "} catch { if ($s -eq 0) { $s = 1 }; [Console]::Error.Write($_.Exception.Message) }".to_owned(),
225 "Remove-Item -Force -LiteralPath $f, \"$f.err\" -ErrorAction SilentlyContinue".to_owned(),
226 "exit $s".to_owned(),
227 ]
228 .join("\n")
229}
230
231impl Inner {
232 async fn fetch_curl(&self, sandbox: &Arc<dyn Sandbox>, url: &str) -> Result<Fetched, String> {
233 let shell = shell_of(sandbox).await.map_err(|error| error.to_string())?;
234 let command = match shell {
235 SandboxShell::PowerShell => powershell_curl_command(url),
236 SandboxShell::Sh => curl_command(url),
237 };
238 let options = ExecuteOptions {
239 timeout: Some(Duration::from_secs(TIMEOUT_SECONDS + 5)),
240 ..ExecuteOptions::default()
241 };
242 let result = sandbox
243 .execute(&command, options)
244 .await
245 .map_err(|error| error.to_string())?;
246 if result.exit_code != 0 {
247 let stderr = result.stderr.trim();
248 return Err(if stderr.is_empty() {
249 format!("curl exited with code {}", result.exit_code)
250 } else {
251 stderr.to_owned()
252 });
253 }
254 let mut lines = result.stdout.split('\n');
255 let content_type = lines.next().unwrap_or_default().trim().to_owned();
256 let resolved_url = lines.next().unwrap_or_default().trim().to_owned();
257 let body: String = lines.flat_map(str::chars).filter(|c| !c.is_whitespace()).collect();
258 let data = base64::engine::general_purpose::STANDARD
259 .decode(body)
260 .map_err(|error| error.to_string())?;
261 Ok(self.patterns.to_text(&data, &content_type, &resolved_url, url))
262 }
263
264 async fn fetch_direct(&self, url: &str) -> Result<Fetched, String> {
265 let response = self
266 .client
267 .get(url)
268 .header(reqwest::header::USER_AGENT, USER_AGENT)
269 .timeout(Duration::from_secs(TIMEOUT_SECONDS))
270 .send()
271 .await
272 .map_err(|error| {
273 if error.is_timeout() {
274 format!("web_fetch gave up after {TIMEOUT_SECONDS}s.")
275 } else {
276 error.to_string()
277 }
278 })?;
279 let status = response.status();
280 if !status.is_success() {
281 return Err(format!(
282 "HTTP {} {}",
283 status.as_u16(),
284 status.canonical_reason().unwrap_or_default()
285 ));
286 }
287 let content_type = response
288 .headers()
289 .get(reqwest::header::CONTENT_TYPE)
290 .and_then(|value| value.to_str().ok())
291 .unwrap_or_default()
292 .to_owned();
293 let resolved_url = response.url().to_string();
294 let data = read_capped(response).await?;
295 Ok(self.patterns.to_text(&data, &content_type, &resolved_url, url))
296 }
297
298 async fn fetch_text(&self, sandbox: &Arc<dyn Sandbox>, url: &str) -> Result<Fetched, String> {
299 let url = self.patterns.validate_url(url)?;
300 match self.transport {
301 WebFetchTransport::Direct => self.fetch_direct(&url).await,
302 _ => self.fetch_curl(sandbox, &url).await,
303 }
304 }
305
306 fn cached(&self, url: &str) -> Option<Fetched> {
307 let cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);
308 cache
309 .get(url)
310 .filter(|entry| entry.expires > Instant::now())
311 .map(|entry| entry.page.clone())
312 }
313
314 fn store(&self, url: &str, page: Fetched) {
315 let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);
316 cache.retain(|_, entry| entry.expires > Instant::now());
317 cache.insert(
318 url.to_owned(),
319 Cached {
320 expires: Instant::now() + CACHE_TTL,
321 page,
322 },
323 );
324 }
325
326 async fn run(&self, input: JsonValue, context: ToolContext) -> Result<JsonValue, ToolError> {
327 let url = input
328 .get("url")
329 .and_then(JsonValue::as_str)
330 .ok_or_else(|| ToolError::msg("Invalid input: expected string at \"url\"."))?;
331 let prompt = input.get("prompt").and_then(JsonValue::as_str).unwrap_or_default();
332 let page = match self.cached(url) {
333 Some(page) => page,
334 None => match self.fetch_text(context.agent().sandbox(), url).await {
335 Ok(page) => {
336 self.store(url, page.clone());
337 page
338 }
339 Err(error) => return Ok(format!("Failed to fetch {url}: {error}").into()),
340 },
341 };
342 if prompt.trim().is_empty() {
343 return Ok(page.text.into());
344 }
345 let model = self
346 .summarizer
347 .clone()
348 .unwrap_or_else(|| context.agent().aux_model().clone());
349 let mut summarizer = Agent::builder()
350 .model(model)
351 .system_prompt(SUMMARIZER_PROMPT)
352 .printer(false)
353 .build()?;
354 let result = summarizer
355 .invoke(format!(
356 "Fetched URL: {}\n\nRequest: {prompt}\n\n--- Content ---\n{}",
357 page.resolved_url, page.text
358 ))
359 .await?;
360 Ok(result.to_string().into())
361 }
362}
363
364async fn read_capped(response: reqwest::Response) -> Result<Vec<u8>, String> {
367 let mut stream = response.bytes_stream();
368 let mut data = Vec::new();
369 while data.len() < MAX_BYTES {
370 let Some(chunk) = stream.next().await else {
371 break;
372 };
373 let chunk = chunk.map_err(|error| error.to_string())?;
374 let room = MAX_BYTES - data.len();
375 data.extend_from_slice(&chunk[..chunk.len().min(room)]);
376 }
377 Ok(data)
378}
379
380pub fn web_fetch_tool(config: WebFetchConfig, summarizer: Option<Arc<dyn Model>>) -> strands::Result<FunctionTool> {
401 let summarizer = summarizer.or(match config.model {
402 Some(ModelSource::Model(model)) => Some(model),
403 Some(ModelSource::Router(router)) => Some(router.default_model()),
404 _ => None,
405 });
406 let patterns = Patterns::new().map_err(strands::Error::other)?;
407 let client = reqwest::Client::builder().build().map_err(strands::Error::other)?;
408 let inner = Arc::new(Inner {
409 summarizer,
410 transport: config.transport.unwrap_or_default(),
411 cache: Mutex::new(HashMap::new()),
412 client,
413 patterns,
414 });
415 Ok(FunctionTool::builder("web_fetch", WEB_FETCH_DESCRIPTION)
416 .input_schema(input_schema())
417 .callback(move |input, context| {
418 let inner = inner.clone();
419 async move { inner.run(input, context).await }
420 }))
421}
422
423#[cfg(test)]
424mod tests;