| 1 | //! Web browsing tool with multi-command support (search/open/click/find/screenshot). |
| 2 | //! |
| 3 | //! This mirrors the Codex harness `web.run` interface so models can use a single |
| 4 | //! tool call to perform multiple web actions and cite sources with ref_ids. |
| 5 | |
| 6 | use super::spec::{ |
| 7 | ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, |
| 8 | optional_u64, required_str, |
| 9 | }; |
| 10 | use super::web::extract::{DocumentKind, ExtractedDocument, extract_document}; |
| 11 | #[cfg(test)] |
| 12 | use super::web::fetch::fetch_readable_with_initial_pin; |
| 13 | use super::web::fetch::{FetchOptions, HARD_MAX_BYTES, Readable, fetch_readable}; |
| 14 | use super::web::overflow::bound_text as bound_web_text; |
| 15 | #[cfg(test)] |
| 16 | use super::web::overflow::inline_char_budget; |
| 17 | use async_trait::async_trait; |
| 18 | #[cfg(test)] |
| 19 | use codewhale_net::guard::DnsPin; |
| 20 | use regex::Regex; |
| 21 | use serde::{Deserialize, Serialize}; |
| 22 | use serde_json::{Value, json}; |
| 23 | use std::collections::{HashMap, HashSet, VecDeque}; |
| 24 | use std::hash::{Hash, Hasher}; |
| 25 | use std::sync::{Arc, OnceLock}; |
| 26 | use std::time::{Duration, Instant}; |
| 27 | use unicode_width::UnicodeWidthStr; |
| 28 | |
| 29 | use parking_lot::{RwLock, RwLockWriteGuard}; |
| 30 | |
| 31 | use super::web::contract::{ |
| 32 | DEFAULT_SEARCH_RESULTS, DEFAULT_SEARCH_TIMEOUT_MS, MAX_SEARCH_RESULTS, MAX_SEARCH_TIMEOUT_MS, |
| 33 | Recency, SearchQuery, SearchReceipt, SearchResult as NormalizedSearchResult, |
| 34 | }; |
| 35 | use super::web::scrape::BROWSER_USER_AGENT as USER_AGENT; |
| 36 | use super::web::scrape::decode_html_entities; |
| 37 | use super::web_search::{domain_matches, execute_search}; |
| 38 | |
| 39 | // Search and open share the retrieval-path defaults from `web::contract` and |
| 40 | // `web::fetch` so `web.run` cannot drift from `web_search` / `fetch_url`. |
| 41 | const DEFAULT_OPEN_TIMEOUT_MS: u64 = super::web::fetch::DEFAULT_TIMEOUT.as_millis() as u64; |
| 42 | const MAX_WEB_RUN_SESSIONS: usize = 64; |
| 43 | const MAX_OPERATIONS_PER_CALL: usize = 64; |
| 44 | const MAX_PAGES_PER_SESSION: usize = 256; |
| 45 | const WEB_RUN_SESSION_TTL: Duration = Duration::from_secs(30 * 60); |
| 46 | |
| 47 | static WEB_RUN_STATE: OnceLock<WebRunCache> = OnceLock::new(); |
| 48 | |
| 49 | #[derive(Default)] |
| 50 | struct WebRunCache { |
| 51 | sessions: RwLock<HashMap<String, WebRunSessionState>>, |
| 52 | pages: RwLock<HashMap<String, StoredWebPage>>, |
| 53 | } |
| 54 | |
| 55 | #[derive(Default)] |
| 56 | struct WebRunState { |
| 57 | sessions: HashMap<String, WebRunSessionState>, |
| 58 | pages: HashMap<String, StoredWebPage>, |
| 59 | } |
| 60 | |
| 61 | struct WebRunSessionState { |
| 62 | next_turn: u64, |
| 63 | refs: VecDeque<String>, |
| 64 | last_access: Instant, |
| 65 | /// Hosts that refused to serve a page this session (HTTP 401/403 even |
| 66 | /// after the browser-agent fallback). Later search results from them are |
| 67 | /// ranked after sources that are likely to load. |
| 68 | refusing_hosts: HashSet<String>, |
| 69 | } |
| 70 | |
| 71 | impl Default for WebRunSessionState { |
| 72 | fn default() -> Self { |
| 73 | Self { |
| 74 | next_turn: 0, |
| 75 | refs: VecDeque::new(), |
| 76 | last_access: Instant::now(), |
| 77 | refusing_hosts: HashSet::new(), |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | #[derive(Debug, Clone)] |
| 83 | struct StoredWebPage { |
| 84 | namespace: String, |
| 85 | page: Arc<WebPage>, |
| 86 | } |
| 87 | |
| 88 | impl WebRunState { |
| 89 | fn cleanup(&mut self) { |
| 90 | let now = Instant::now(); |
| 91 | let expired = self |
| 92 | .sessions |
| 93 | .iter() |
| 94 | .filter_map(|(namespace, session)| { |
| 95 | if now.duration_since(session.last_access) > WEB_RUN_SESSION_TTL { |
| 96 | Some(namespace.clone()) |
| 97 | } else { |
| 98 | None |
| 99 | } |
| 100 | }) |
| 101 | .collect::<Vec<_>>(); |
| 102 | for namespace in expired { |
| 103 | self.remove_session(&namespace); |
| 104 | } |
| 105 | |
| 106 | while self.sessions.len() > MAX_WEB_RUN_SESSIONS { |
| 107 | let Some(oldest_namespace) = self |
| 108 | .sessions |
| 109 | .iter() |
| 110 | .min_by_key(|(_, session)| session.last_access) |
| 111 | .map(|(namespace, _)| namespace.clone()) |
| 112 | else { |
| 113 | break; |
| 114 | }; |
| 115 | self.remove_session(&oldest_namespace); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | fn remove_session(&mut self, namespace: &str) { |
| 120 | if let Some(session) = self.sessions.remove(namespace) { |
| 121 | for ref_id in session.refs { |
| 122 | self.pages.remove(&ref_id); |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | fn touch_session(&mut self, namespace: &str) { |
| 128 | self.cleanup(); |
| 129 | if !self.sessions.contains_key(namespace) |
| 130 | && self.sessions.len() >= MAX_WEB_RUN_SESSIONS |
| 131 | && let Some(oldest_namespace) = self |
| 132 | .sessions |
| 133 | .iter() |
| 134 | .min_by_key(|(_, session)| session.last_access) |
| 135 | .map(|(existing_namespace, _)| existing_namespace.clone()) |
| 136 | { |
| 137 | self.remove_session(&oldest_namespace); |
| 138 | } |
| 139 | |
| 140 | let session = self.sessions.entry(namespace.to_string()).or_default(); |
| 141 | session.last_access = Instant::now(); |
| 142 | } |
| 143 | |
| 144 | fn next_turn(&mut self, namespace: &str) -> u64 { |
| 145 | self.touch_session(namespace); |
| 146 | let session = self |
| 147 | .sessions |
| 148 | .get_mut(namespace) |
| 149 | .expect("session should exist after touch"); |
| 150 | let current = session.next_turn; |
| 151 | session.next_turn = session.next_turn.saturating_add(1); |
| 152 | current |
| 153 | } |
| 154 | |
| 155 | fn note_refusing_host(&mut self, namespace: &str, host: &str) { |
| 156 | self.touch_session(namespace); |
| 157 | if let Some(session) = self.sessions.get_mut(namespace) { |
| 158 | session.refusing_hosts.insert(host.to_string()); |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | fn refusing_hosts(&self, namespace: &str) -> HashSet<String> { |
| 163 | self.sessions |
| 164 | .get(namespace) |
| 165 | .map(|session| session.refusing_hosts.clone()) |
| 166 | .unwrap_or_default() |
| 167 | } |
| 168 | |
| 169 | fn store_page(&mut self, namespace: &str, ref_id: &str, page: WebPage) { |
| 170 | self.touch_session(namespace); |
| 171 | let mut evicted_refs = Vec::new(); |
| 172 | { |
| 173 | let session = self |
| 174 | .sessions |
| 175 | .get_mut(namespace) |
| 176 | .expect("session should exist after touch"); |
| 177 | if let Some(existing_idx) = session.refs.iter().position(|existing| existing == ref_id) |
| 178 | { |
| 179 | session.refs.remove(existing_idx); |
| 180 | } |
| 181 | session.refs.push_back(ref_id.to_string()); |
| 182 | |
| 183 | while session.refs.len() > MAX_PAGES_PER_SESSION { |
| 184 | if let Some(evicted_ref) = session.refs.pop_front() { |
| 185 | evicted_refs.push(evicted_ref); |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | self.pages.insert( |
| 191 | ref_id.to_string(), |
| 192 | StoredWebPage { |
| 193 | namespace: namespace.to_string(), |
| 194 | page: Arc::new(page), |
| 195 | }, |
| 196 | ); |
| 197 | for evicted_ref in evicted_refs { |
| 198 | self.pages.remove(&evicted_ref); |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | #[derive(Debug, Clone, Serialize)] |
| 204 | struct WebLink { |
| 205 | id: usize, |
| 206 | url: String, |
| 207 | text: String, |
| 208 | } |
| 209 | |
| 210 | #[derive(Debug, Clone)] |
| 211 | struct WebPage { |
| 212 | url: String, |
| 213 | title: Option<String>, |
| 214 | content_type: Option<String>, |
| 215 | lines: Vec<String>, |
| 216 | links: Vec<WebLink>, |
| 217 | pdf_pages: Option<Vec<Vec<String>>>, |
| 218 | truncated: bool, |
| 219 | partial: Option<String>, |
| 220 | } |
| 221 | |
| 222 | #[derive(Debug, Clone, Copy)] |
| 223 | enum ResponseLength { |
| 224 | Short, |
| 225 | Medium, |
| 226 | Long, |
| 227 | } |
| 228 | |
| 229 | impl ResponseLength { |
| 230 | fn from_input(input: Option<&Value>) -> Self { |
| 231 | let raw = input.and_then(|v| v.as_str()).unwrap_or("medium"); |
| 232 | match raw.to_lowercase().as_str() { |
| 233 | "short" => Self::Short, |
| 234 | "long" => Self::Long, |
| 235 | _ => Self::Medium, |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | fn view_lines(self) -> usize { |
| 240 | match self { |
| 241 | Self::Short => 40, |
| 242 | Self::Medium => 80, |
| 243 | Self::Long => 160, |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | fn wrap_width(self) -> usize { |
| 248 | match self { |
| 249 | Self::Short => 88, |
| 250 | Self::Medium => 110, |
| 251 | Self::Long => 140, |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | fn max_results(self) -> usize { |
| 256 | match self { |
| 257 | Self::Short => DEFAULT_SEARCH_RESULTS, |
| 258 | Self::Medium => 8, |
| 259 | Self::Long => usize::from(MAX_SEARCH_RESULTS), |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | fn max_find_matches(self) -> usize { |
| 264 | match self { |
| 265 | Self::Short => 8, |
| 266 | Self::Medium => 15, |
| 267 | Self::Long => 30, |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | #[derive(Debug, Clone, Serialize)] |
| 273 | struct WebRunSearchResult { |
| 274 | ref_id: String, |
| 275 | query: String, |
| 276 | source: String, |
| 277 | count: usize, |
| 278 | results: Vec<NormalizedSearchResult>, |
| 279 | #[serde(skip_serializing_if = "Option::is_none")] |
| 280 | warning: Option<String>, |
| 281 | receipt: SearchReceipt, |
| 282 | } |
| 283 | |
| 284 | #[derive(Debug, Clone, Serialize)] |
| 285 | struct PageViewResult { |
| 286 | ref_id: String, |
| 287 | url: String, |
| 288 | #[serde(skip_serializing_if = "Option::is_none")] |
| 289 | title: Option<String>, |
| 290 | #[serde(skip_serializing_if = "Option::is_none")] |
| 291 | content_type: Option<String>, |
| 292 | line_start: usize, |
| 293 | line_end: usize, |
| 294 | total_lines: usize, |
| 295 | #[serde(default, skip_serializing_if = "is_false")] |
| 296 | truncated: bool, |
| 297 | #[serde(default, skip_serializing_if = "is_false")] |
| 298 | partial: bool, |
| 299 | #[serde(skip_serializing_if = "Option::is_none")] |
| 300 | note: Option<String>, |
| 301 | content: String, |
| 302 | links: Vec<WebLink>, |
| 303 | } |
| 304 | |
| 305 | #[derive(Debug, Clone, Serialize)] |
| 306 | struct FindMatch { |
| 307 | line: usize, |
| 308 | text: String, |
| 309 | } |
| 310 | |
| 311 | fn is_false(value: &bool) -> bool { |
| 312 | !*value |
| 313 | } |
| 314 | |
| 315 | #[derive(Debug, Clone, Serialize)] |
| 316 | struct FindResult { |
| 317 | ref_id: String, |
| 318 | pattern: String, |
| 319 | count: usize, |
| 320 | matches: Vec<FindMatch>, |
| 321 | } |
| 322 | |
| 323 | #[derive(Debug, Clone, Serialize)] |
| 324 | struct ScreenshotResult { |
| 325 | ref_id: String, |
| 326 | pageno: usize, |
| 327 | total_pages: usize, |
| 328 | content: String, |
| 329 | } |
| 330 | |
| 331 | #[derive(Debug, Clone, Serialize)] |
| 332 | struct ImageResultEntry { |
| 333 | ref_id: String, |
| 334 | image: String, |
| 335 | #[serde(skip_serializing_if = "Option::is_none")] |
| 336 | thumbnail: Option<String>, |
| 337 | #[serde(skip_serializing_if = "Option::is_none")] |
| 338 | title: Option<String>, |
| 339 | #[serde(skip_serializing_if = "Option::is_none")] |
| 340 | url: Option<String>, |
| 341 | #[serde(skip_serializing_if = "Option::is_none")] |
| 342 | source: Option<String>, |
| 343 | #[serde(skip_serializing_if = "Option::is_none")] |
| 344 | width: Option<u32>, |
| 345 | #[serde(skip_serializing_if = "Option::is_none")] |
| 346 | height: Option<u32>, |
| 347 | } |
| 348 | |
| 349 | #[derive(Debug, Clone, Serialize)] |
| 350 | struct ImageQueryResult { |
| 351 | query: String, |
| 352 | source: String, |
| 353 | count: usize, |
| 354 | results: Vec<ImageResultEntry>, |
| 355 | #[serde(skip_serializing_if = "Option::is_none")] |
| 356 | warning: Option<String>, |
| 357 | } |
| 358 | |
| 359 | #[derive(Debug, Clone, Serialize, Default)] |
| 360 | struct WebRunOutput { |
| 361 | #[serde(skip_serializing_if = "Option::is_none")] |
| 362 | search_query: Option<Vec<WebRunSearchResult>>, |
| 363 | #[serde(skip_serializing_if = "Option::is_none")] |
| 364 | image_query: Option<Vec<ImageQueryResult>>, |
| 365 | #[serde(skip_serializing_if = "Option::is_none")] |
| 366 | open: Option<Vec<PageViewResult>>, |
| 367 | #[serde(skip_serializing_if = "Option::is_none")] |
| 368 | click: Option<Vec<PageViewResult>>, |
| 369 | #[serde(skip_serializing_if = "Option::is_none")] |
| 370 | find: Option<Vec<FindResult>>, |
| 371 | #[serde(skip_serializing_if = "Option::is_none")] |
| 372 | screenshot: Option<Vec<ScreenshotResult>>, |
| 373 | #[serde(skip_serializing_if = "Vec::is_empty", default)] |
| 374 | warnings: Vec<String>, |
| 375 | /// Every page this call tried to open or click, loaded ones first, so the |
| 376 | /// model cites what actually loaded and moves past what did not. |
| 377 | #[serde(skip_serializing_if = "Vec::is_empty", default)] |
| 378 | sources: Vec<SourceEntry>, |
| 379 | } |
| 380 | |
| 381 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 382 | #[serde(rename_all = "snake_case")] |
| 383 | enum SourceStatus { |
| 384 | Loaded, |
| 385 | /// The site answered but would not serve a readable page (403, 404, |
| 386 | /// script-only body). Not retryable as-is; use another source. |
| 387 | Unavailable, |
| 388 | /// Network or server trouble (timeout, 5xx, 429). May load on a later try. |
| 389 | Transient, |
| 390 | } |
| 391 | |
| 392 | #[derive(Debug, Clone, Serialize)] |
| 393 | struct SourceEntry { |
| 394 | #[serde(skip_serializing_if = "Option::is_none")] |
| 395 | ref_id: Option<String>, |
| 396 | url: String, |
| 397 | #[serde(skip_serializing_if = "Option::is_none")] |
| 398 | title: Option<String>, |
| 399 | status: SourceStatus, |
| 400 | #[serde(skip_serializing_if = "Option::is_none")] |
| 401 | reason: Option<String>, |
| 402 | } |
| 403 | |
| 404 | impl SourceEntry { |
| 405 | fn loaded(ref_id: &str, page: &WebPage) -> Self { |
| 406 | Self { |
| 407 | ref_id: Some(ref_id.to_string()), |
| 408 | url: page.url.clone(), |
| 409 | title: page.title.clone(), |
| 410 | status: SourceStatus::Loaded, |
| 411 | reason: None, |
| 412 | } |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | pub struct WebRunTool; |
| 417 | |
| 418 | #[async_trait] |
| 419 | impl ToolSpec for WebRunTool { |
| 420 | fn name(&self) -> &'static str { |
| 421 | "web.run" |
| 422 | } |
| 423 | |
| 424 | fn description(&self) -> &'static str { |
| 425 | "Browse the web (search/open/click/find/screenshot/image_query) and return structured results with ref_ids for citations." |
| 426 | } |
| 427 | |
| 428 | fn input_schema(&self) -> Value { |
| 429 | json!({ |
| 430 | "type": "object", |
| 431 | "properties": { |
| 432 | "search_query": { |
| 433 | "type": "array", |
| 434 | "items": { |
| 435 | "type": "object", |
| 436 | "properties": { |
| 437 | "q": { "type": "string" }, |
| 438 | "recency": { "type": "integer", "minimum": 1, "maximum": 3650 }, |
| 439 | "max_results": { "type": "integer" }, |
| 440 | "timeout_ms": { "type": "integer" }, |
| 441 | "domains": { "type": "array", "items": { "type": "string" } } |
| 442 | }, |
| 443 | "required": ["q"] |
| 444 | } |
| 445 | }, |
| 446 | "image_query": { |
| 447 | "type": "array", |
| 448 | "items": { |
| 449 | "type": "object", |
| 450 | "properties": { |
| 451 | "q": { "type": "string" }, |
| 452 | "recency": { "type": "integer" }, |
| 453 | "max_results": { "type": "integer" }, |
| 454 | "timeout_ms": { "type": "integer" }, |
| 455 | "domains": { "type": "array", "items": { "type": "string" } } |
| 456 | }, |
| 457 | "required": ["q"] |
| 458 | } |
| 459 | }, |
| 460 | "open": { |
| 461 | "type": "array", |
| 462 | "items": { |
| 463 | "type": "object", |
| 464 | "properties": { |
| 465 | "ref_id": { "type": "string" }, |
| 466 | "lineno": { "type": "integer" } |
| 467 | }, |
| 468 | "required": ["ref_id"] |
| 469 | } |
| 470 | }, |
| 471 | "click": { |
| 472 | "type": "array", |
| 473 | "items": { |
| 474 | "type": "object", |
| 475 | "properties": { |
| 476 | "ref_id": { "type": "string" }, |
| 477 | "id": { "type": "integer" } |
| 478 | }, |
| 479 | "required": ["ref_id", "id"] |
| 480 | } |
| 481 | }, |
| 482 | "find": { |
| 483 | "type": "array", |
| 484 | "items": { |
| 485 | "type": "object", |
| 486 | "properties": { |
| 487 | "ref_id": { "type": "string" }, |
| 488 | "pattern": { "type": "string" } |
| 489 | }, |
| 490 | "required": ["ref_id", "pattern"] |
| 491 | } |
| 492 | }, |
| 493 | "screenshot": { |
| 494 | "type": "array", |
| 495 | "items": { |
| 496 | "type": "object", |
| 497 | "properties": { |
| 498 | "ref_id": { "type": "string" }, |
| 499 | "pageno": { "type": "integer" } |
| 500 | }, |
| 501 | "required": ["ref_id", "pageno"] |
| 502 | } |
| 503 | }, |
| 504 | "response_length": { |
| 505 | "type": "string", |
| 506 | "enum": ["short", "medium", "long"], |
| 507 | "description": "Controls result verbosity" |
| 508 | } |
| 509 | } |
| 510 | }) |
| 511 | } |
| 512 | |
| 513 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 514 | vec![ToolCapability::ReadOnly, ToolCapability::Network] |
| 515 | } |
| 516 | |
| 517 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 518 | // Read-only HTTP can still disclose local data through a URL or query. |
| 519 | // Host allowlisting controls reachability, not approval of this payload. |
| 520 | ApprovalRequirement::Required |
| 521 | } |
| 522 | |
| 523 | fn refusal_before_approval(&self, input: &Value, context: &ToolContext) -> Option<ToolResult> { |
| 524 | super::web::consent::planned_search_refusal(self.name(), input, context) |
| 525 | .map(ToolResult::success) |
| 526 | } |
| 527 | |
| 528 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 529 | let operation_count = [ |
| 530 | "search_query", |
| 531 | "image_query", |
| 532 | "open", |
| 533 | "click", |
| 534 | "find", |
| 535 | "screenshot", |
| 536 | ] |
| 537 | .into_iter() |
| 538 | .fold(0usize, |count, field| { |
| 539 | count.saturating_add( |
| 540 | input |
| 541 | .get(field) |
| 542 | .and_then(Value::as_array) |
| 543 | .map_or(0, Vec::len), |
| 544 | ) |
| 545 | }); |
| 546 | if operation_count > MAX_OPERATIONS_PER_CALL { |
| 547 | return Err(ToolError::invalid_input(format!( |
| 548 | "web.run accepts at most {MAX_OPERATIONS_PER_CALL} operations across all command arrays" |
| 549 | ))); |
| 550 | } |
| 551 | if let Some(refusal) = |
| 552 | super::web::consent::planned_search_refusal(self.name(), &input, context) |
| 553 | { |
| 554 | return Ok(ToolResult::success(refusal)); |
| 555 | } |
| 556 | let chosen = super::web::consent::with_chosen_search(context); |
| 557 | let context = chosen.as_ref().unwrap_or(context); |
| 558 | let response_length = ResponseLength::from_input(input.get("response_length")); |
| 559 | let mut output = WebRunOutput::default(); |
| 560 | let scope = scoped_ref_prefix(&context.state_namespace); |
| 561 | let turn = with_state(|state| state.next_turn(&context.state_namespace)); |
| 562 | |
| 563 | let mut search_counter = 0usize; |
| 564 | let mut view_counter = 0usize; |
| 565 | let mut click_counter = 0usize; |
| 566 | |
| 567 | if let Some(searches) = input.get("search_query").and_then(|v| v.as_array()) { |
| 568 | let mut results = Vec::new(); |
| 569 | for search in searches { |
| 570 | let query = required_str(search, "q")?.trim().to_string(); |
| 571 | if query.is_empty() { |
| 572 | continue; |
| 573 | } |
| 574 | let recency = optional_u64(search, "recency", 0)?; |
| 575 | let max_results = usize::try_from(optional_u64( |
| 576 | search, |
| 577 | "max_results", |
| 578 | response_length.max_results() as u64, |
| 579 | )?) |
| 580 | .unwrap_or(response_length.max_results()) |
| 581 | .clamp(1, usize::from(MAX_SEARCH_RESULTS)); |
| 582 | let timeout_ms = optional_u64(search, "timeout_ms", DEFAULT_SEARCH_TIMEOUT_MS)? |
| 583 | .min(MAX_SEARCH_TIMEOUT_MS); |
| 584 | |
| 585 | let domains = search |
| 586 | .get("domains") |
| 587 | .and_then(|v| v.as_array()) |
| 588 | .map(|arr| { |
| 589 | arr.iter() |
| 590 | .filter_map(|v| v.as_str().map(|s| s.to_string())) |
| 591 | .collect::<Vec<_>>() |
| 592 | }) |
| 593 | .unwrap_or_default(); |
| 594 | |
| 595 | let requested_recency = if recency == 0 { |
| 596 | None |
| 597 | } else { |
| 598 | let days = u16::try_from(recency) |
| 599 | .ok() |
| 600 | .filter(|days| *days <= 3650) |
| 601 | .ok_or_else(|| { |
| 602 | ToolError::invalid_input( |
| 603 | "Field 'search_query[].recency' must be between 1 and 3650 days", |
| 604 | ) |
| 605 | })?; |
| 606 | Some(Recency::Days(days)) |
| 607 | }; |
| 608 | let mut response = execute_search( |
| 609 | SearchQuery::new(query, max_results, requested_recency, domains, None), |
| 610 | timeout_ms, |
| 611 | context, |
| 612 | ) |
| 613 | .await?; |
| 614 | let refusing_hosts = |
| 615 | with_state(|state| state.refusing_hosts(&context.state_namespace)); |
| 616 | prefer_loading_sources(&mut response.results, &refusing_hosts); |
| 617 | let warning = response.receipt.warning(); |
| 618 | search_counter += 1; |
| 619 | let ref_id = format!("{scope}turn{turn}search{search_counter}"); |
| 620 | |
| 621 | let page = page_from_search(&response.query, &response.results); |
| 622 | store_page(&context.state_namespace, &ref_id, page); |
| 623 | |
| 624 | results.push(WebRunSearchResult { |
| 625 | ref_id, |
| 626 | query: response.query, |
| 627 | source: response.source, |
| 628 | count: response.count, |
| 629 | results: response.results, |
| 630 | warning, |
| 631 | receipt: response.receipt, |
| 632 | }); |
| 633 | } |
| 634 | if !results.is_empty() { |
| 635 | output.search_query = Some(results); |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | if let Some(images) = input.get("image_query").and_then(|v| v.as_array()) { |
| 640 | let mut results = Vec::new(); |
| 641 | for image in images { |
| 642 | let query = required_str(image, "q")?.trim().to_string(); |
| 643 | if query.is_empty() { |
| 644 | continue; |
| 645 | } |
| 646 | let recency = optional_u64(image, "recency", 0)?; |
| 647 | let max_results = usize::try_from(optional_u64( |
| 648 | image, |
| 649 | "max_results", |
| 650 | response_length.max_results() as u64, |
| 651 | )?) |
| 652 | .unwrap_or(response_length.max_results()) |
| 653 | .clamp(1, usize::from(MAX_SEARCH_RESULTS)); |
| 654 | let timeout_ms = optional_u64(image, "timeout_ms", DEFAULT_SEARCH_TIMEOUT_MS)? |
| 655 | .min(MAX_SEARCH_TIMEOUT_MS); |
| 656 | |
| 657 | let domains = image |
| 658 | .get("domains") |
| 659 | .and_then(|v| v.as_array()) |
| 660 | .map(|arr| { |
| 661 | arr.iter() |
| 662 | .filter_map(|v| v.as_str().map(|s| s.to_string())) |
| 663 | .collect::<Vec<_>>() |
| 664 | }) |
| 665 | .unwrap_or_default(); |
| 666 | |
| 667 | let (mut entries, warning) = |
| 668 | run_image_search(&query, max_results, timeout_ms, &domains, context).await?; |
| 669 | entries.retain_mut(|entry| { |
| 670 | let canonical_url = entry.url.as_deref().unwrap_or(&entry.image); |
| 671 | let Some(citation) = super::web::citations::register( |
| 672 | &context.state_namespace, |
| 673 | canonical_url, |
| 674 | entry.title.as_deref(), |
| 675 | ) else { |
| 676 | return false; |
| 677 | }; |
| 678 | entry.ref_id = citation.ref_id; |
| 679 | true |
| 680 | }); |
| 681 | |
| 682 | let mut warnings = Vec::new(); |
| 683 | if recency > 0 { |
| 684 | warnings.push(format!( |
| 685 | "Recency filter not enforced (requested last {recency} days)" |
| 686 | )); |
| 687 | } |
| 688 | if let Some(w) = warning { |
| 689 | warnings.push(w); |
| 690 | } |
| 691 | |
| 692 | results.push(ImageQueryResult { |
| 693 | query, |
| 694 | source: "duckduckgo_images".to_string(), |
| 695 | count: entries.len(), |
| 696 | results: entries, |
| 697 | warning: if warnings.is_empty() { |
| 698 | None |
| 699 | } else { |
| 700 | Some(warnings.join("; ")) |
| 701 | }, |
| 702 | }); |
| 703 | } |
| 704 | if !results.is_empty() { |
| 705 | output.image_query = Some(results); |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | if let Some(opens) = input.get("open").and_then(|v| v.as_array()) { |
| 710 | let mut views = Vec::new(); |
| 711 | for open in opens { |
| 712 | let ref_id = required_str(open, "ref_id")?.to_string(); |
| 713 | let lineno = optional_u64(open, "lineno", 1)?.max(1) as usize; |
| 714 | |
| 715 | let page = |
| 716 | match resolve_or_fetch_page(&ref_id, DEFAULT_OPEN_TIMEOUT_MS, context).await { |
| 717 | Ok(page) => page, |
| 718 | Err(error) => { |
| 719 | let target = open_target_url(&context.state_namespace, &ref_id); |
| 720 | output.sources.push(source_failure( |
| 721 | &context.state_namespace, |
| 722 | target.as_deref().unwrap_or(&ref_id), |
| 723 | error, |
| 724 | )?); |
| 725 | continue; |
| 726 | } |
| 727 | }; |
| 728 | view_counter += 1; |
| 729 | let view_ref = format!("{scope}turn{turn}view{view_counter}"); |
| 730 | store_page(&context.state_namespace, &view_ref, (*page).clone()); |
| 731 | output.sources.push(SourceEntry::loaded(&view_ref, &page)); |
| 732 | |
| 733 | let view = render_view(&view_ref, &page, lineno, response_length); |
| 734 | views.push(view); |
| 735 | } |
| 736 | if !views.is_empty() { |
| 737 | output.open = Some(views); |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | if let Some(clicks) = input.get("click").and_then(|v| v.as_array()) { |
| 742 | let mut views = Vec::new(); |
| 743 | for click in clicks { |
| 744 | let ref_id = required_str(click, "ref_id")?.to_string(); |
| 745 | let link_id = optional_u64(click, "id", 0)? as usize; |
| 746 | if link_id == 0 { |
| 747 | return Err(ToolError::invalid_input("click.id must be >= 1")); |
| 748 | } |
| 749 | let page = get_page(&context.state_namespace, &ref_id).ok_or_else(|| { |
| 750 | ToolError::invalid_input(format!("Unknown ref_id '{ref_id}'")) |
| 751 | })?; |
| 752 | let link = page.links.iter().find(|l| l.id == link_id).ok_or_else(|| { |
| 753 | ToolError::invalid_input(format!( |
| 754 | "Link id {link_id} not found for ref_id '{ref_id}'" |
| 755 | )) |
| 756 | })?; |
| 757 | let target = link.url.clone(); |
| 758 | let fetched = |
| 759 | match resolve_or_fetch_page(&target, DEFAULT_OPEN_TIMEOUT_MS, context).await { |
| 760 | Ok(page) => page, |
| 761 | Err(error) => { |
| 762 | output.sources.push(source_failure( |
| 763 | &context.state_namespace, |
| 764 | &target, |
| 765 | error, |
| 766 | )?); |
| 767 | continue; |
| 768 | } |
| 769 | }; |
| 770 | click_counter += 1; |
| 771 | let click_ref = format!("{scope}turn{turn}click{click_counter}"); |
| 772 | store_page(&context.state_namespace, &click_ref, (*fetched).clone()); |
| 773 | output |
| 774 | .sources |
| 775 | .push(SourceEntry::loaded(&click_ref, &fetched)); |
| 776 | let view = render_view(&click_ref, &fetched, 1, response_length); |
| 777 | views.push(view); |
| 778 | } |
| 779 | if !views.is_empty() { |
| 780 | output.click = Some(views); |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | if let Some(find_requests) = input.get("find").and_then(|v| v.as_array()) { |
| 785 | let mut finds = Vec::new(); |
| 786 | for find_req in find_requests { |
| 787 | let ref_id = required_str(find_req, "ref_id")?.to_string(); |
| 788 | let pattern = required_str(find_req, "pattern")?.to_string(); |
| 789 | let page = get_page(&context.state_namespace, &ref_id).ok_or_else(|| { |
| 790 | ToolError::invalid_input(format!("Unknown ref_id '{ref_id}'")) |
| 791 | })?; |
| 792 | let find_result = find_in_page(&ref_id, &pattern, &page, response_length); |
| 793 | finds.push(find_result); |
| 794 | } |
| 795 | if !finds.is_empty() { |
| 796 | output.find = Some(finds); |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | if let Some(shots) = input.get("screenshot").and_then(|v| v.as_array()) { |
| 801 | let mut screenshots = Vec::new(); |
| 802 | for shot in shots { |
| 803 | let ref_id = required_str(shot, "ref_id")?.to_string(); |
| 804 | let pageno = optional_u64(shot, "pageno", 0)? as usize; |
| 805 | let page = get_page(&context.state_namespace, &ref_id).ok_or_else(|| { |
| 806 | ToolError::invalid_input(format!("Unknown ref_id '{ref_id}'")) |
| 807 | })?; |
| 808 | let screenshot = screenshot_page(&ref_id, pageno, &page)?; |
| 809 | screenshots.push(screenshot); |
| 810 | } |
| 811 | if !screenshots.is_empty() { |
| 812 | output.screenshot = Some(screenshots); |
| 813 | } |
| 814 | } |
| 815 | |
| 816 | let failed = output |
| 817 | .sources |
| 818 | .iter() |
| 819 | .filter(|source| source.status != SourceStatus::Loaded) |
| 820 | .count(); |
| 821 | if failed > 0 { |
| 822 | output |
| 823 | .sources |
| 824 | .sort_by_key(|source| source.status != SourceStatus::Loaded); |
| 825 | output.warnings.push(format!( |
| 826 | "{failed} source(s) did not load. Cite only sources marked loaded; open another \ |
| 827 | search result instead of retrying an unavailable URL." |
| 828 | )); |
| 829 | } |
| 830 | |
| 831 | if output.performed_no_op() && output.sources.is_empty() { |
| 832 | // #5123-class: an empty success here reads as "nothing found" |
| 833 | // rather than "you called the tool wrong" (e.g. the natural |
| 834 | // {"query": …} shape, which matches no op key). |
| 835 | let received: Vec<&str> = input |
| 836 | .as_object() |
| 837 | .map(|object| object.keys().map(String::as_str).collect()) |
| 838 | .unwrap_or_default(); |
| 839 | return Err(ToolError::invalid_input(format!( |
| 840 | "web.run performed no operation. Pass at least one non-empty op array \ |
| 841 | ({}). Received keys: [{}].", |
| 842 | WEB_RUN_OP_KEYS.join(", "), |
| 843 | received.join(", ") |
| 844 | ))); |
| 845 | } |
| 846 | |
| 847 | let mut result = bounded_web_run_result(&output, context)?; |
| 848 | if failed > 0 { |
| 849 | // A site refusing a page is an outcome of the browse, not a tool |
| 850 | // failure: the call still succeeds, and clients render these |
| 851 | // neutrally instead of as errors. |
| 852 | let metadata = result.metadata.get_or_insert_with(|| json!({})); |
| 853 | metadata["source_failures"] = json!(failed); |
| 854 | metadata["source_failure_severity"] = json!("neutral"); |
| 855 | } |
| 856 | Ok(result) |
| 857 | } |
| 858 | } |
| 859 | |
| 860 | /// Where an `open` ref would be fetched from, for the failure receipt. |
| 861 | fn open_target_url(namespace: &str, ref_id: &str) -> Option<String> { |
| 862 | if let Some(citation) = super::web::citations::resolve(namespace, ref_id) { |
| 863 | return Some(citation.url); |
| 864 | } |
| 865 | looks_like_url(ref_id).then(|| ref_id.to_string()) |
| 866 | } |
| 867 | |
| 868 | /// Turn a failed page fetch into a source receipt, or pass the error through |
| 869 | /// when it is the caller's mistake or a gate (bad ref, denied host, cancel). |
| 870 | fn source_failure(namespace: &str, url: &str, error: ToolError) -> Result<SourceEntry, ToolError> { |
| 871 | let (status, reason) = match &error { |
| 872 | ToolError::Timeout { .. } => (SourceStatus::Transient, error.to_string()), |
| 873 | ToolError::ExecutionFailed { message, .. } => { |
| 874 | let status = match http_status_of(message) { |
| 875 | Some(code) if code == 429 || (500..600).contains(&code) => SourceStatus::Transient, |
| 876 | Some(_) => SourceStatus::Unavailable, |
| 877 | None if message.contains("timed out") || message.contains("after one retry") => { |
| 878 | SourceStatus::Transient |
| 879 | } |
| 880 | None => SourceStatus::Unavailable, |
| 881 | }; |
| 882 | (status, message.clone()) |
| 883 | } |
| 884 | _ => return Err(error), |
| 885 | }; |
| 886 | if let Some(code) = http_status_of(&reason) |
| 887 | && matches!(code, 401 | 403) |
| 888 | && let Some(host) = reqwest::Url::parse(url) |
| 889 | .ok() |
| 890 | .and_then(|parsed| parsed.host_str().map(str::to_ascii_lowercase)) |
| 891 | { |
| 892 | with_state(|state| state.note_refusing_host(namespace, &host)); |
| 893 | } |
| 894 | Ok(SourceEntry { |
| 895 | ref_id: None, |
| 896 | url: url.to_string(), |
| 897 | title: None, |
| 898 | status, |
| 899 | reason: Some(reason), |
| 900 | }) |
| 901 | } |
| 902 | |
| 903 | /// The HTTP status carried by a `document_from_fetched` rejection. |
| 904 | fn http_status_of(message: &str) -> Option<u16> { |
| 905 | let (_, tail) = message.rsplit_once(" failed: HTTP ")?; |
| 906 | tail.get(..3)?.parse().ok() |
| 907 | } |
| 908 | |
| 909 | /// Rank results from hosts that already refused this session after the ones |
| 910 | /// likely to load, keeping each group's order and renumbering `rank`. |
| 911 | fn prefer_loading_sources( |
| 912 | results: &mut [NormalizedSearchResult], |
| 913 | refusing_hosts: &HashSet<String>, |
| 914 | ) { |
| 915 | if refusing_hosts.is_empty() { |
| 916 | return; |
| 917 | } |
| 918 | results.sort_by_key(|result| refusing_hosts.contains(&result.domain)); |
| 919 | for (index, result) in results.iter_mut().enumerate() { |
| 920 | result.rank = u8::try_from(index + 1).unwrap_or(u8::MAX); |
| 921 | } |
| 922 | } |
| 923 | |
| 924 | const WEB_RUN_OP_KEYS: [&str; 6] = [ |
| 925 | "search_query", |
| 926 | "image_query", |
| 927 | "open", |
| 928 | "click", |
| 929 | "find", |
| 930 | "screenshot", |
| 931 | ]; |
| 932 | |
| 933 | impl WebRunOutput { |
| 934 | fn performed_no_op(&self) -> bool { |
| 935 | self.search_query.is_none() |
| 936 | && self.image_query.is_none() |
| 937 | && self.open.is_none() |
| 938 | && self.click.is_none() |
| 939 | && self.find.is_none() |
| 940 | && self.screenshot.is_none() |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | fn with_state<T>(f: impl FnOnce(&mut WebRunState) -> T) -> T { |
| 945 | let cache = WEB_RUN_STATE.get_or_init(WebRunCache::default); |
| 946 | let sessions = cache.sessions.write(); |
| 947 | let pages = cache.pages.write(); |
| 948 | let mut guard = WebRunStateWriteBack::new(sessions, pages); |
| 949 | guard.state_mut().cleanup(); |
| 950 | let result = f(guard.state_mut()); |
| 951 | guard.write_back(); |
| 952 | result |
| 953 | } |
| 954 | |
| 955 | struct WebRunStateWriteBack<'a> { |
| 956 | sessions: RwLockWriteGuard<'a, HashMap<String, WebRunSessionState>>, |
| 957 | pages: RwLockWriteGuard<'a, HashMap<String, StoredWebPage>>, |
| 958 | state: Option<WebRunState>, |
| 959 | } |
| 960 | |
| 961 | impl<'a> WebRunStateWriteBack<'a> { |
| 962 | fn new( |
| 963 | mut sessions: RwLockWriteGuard<'a, HashMap<String, WebRunSessionState>>, |
| 964 | mut pages: RwLockWriteGuard<'a, HashMap<String, StoredWebPage>>, |
| 965 | ) -> Self { |
| 966 | let state = WebRunState { |
| 967 | sessions: std::mem::take(&mut *sessions), |
| 968 | pages: std::mem::take(&mut *pages), |
| 969 | }; |
| 970 | Self { |
| 971 | sessions, |
| 972 | pages, |
| 973 | state: Some(state), |
| 974 | } |
| 975 | } |
| 976 | |
| 977 | fn state_mut(&mut self) -> &mut WebRunState { |
| 978 | self.state |
| 979 | .as_mut() |
| 980 | .expect("web run state should be present until write-back") |
| 981 | } |
| 982 | |
| 983 | fn write_back(mut self) { |
| 984 | self.restore(); |
| 985 | } |
| 986 | |
| 987 | fn restore(&mut self) { |
| 988 | if let Some(state) = self.state.take() { |
| 989 | *self.sessions = state.sessions; |
| 990 | *self.pages = state.pages; |
| 991 | } |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | impl Drop for WebRunStateWriteBack<'_> { |
| 996 | fn drop(&mut self) { |
| 997 | self.restore(); |
| 998 | } |
| 999 | } |
| 1000 | |
| 1001 | fn scoped_ref_prefix(namespace: &str) -> String { |
| 1002 | let mut hasher = std::collections::hash_map::DefaultHasher::new(); |
| 1003 | namespace.hash(&mut hasher); |
| 1004 | format!("s{:016x}_", hasher.finish()) |
| 1005 | } |
| 1006 | |
| 1007 | fn store_page(namespace: &str, ref_id: &str, page: WebPage) { |
| 1008 | let _ = super::web::citations::register_with_ref( |
| 1009 | namespace, |
| 1010 | ref_id, |
| 1011 | &page.url, |
| 1012 | page.title.as_deref(), |
| 1013 | ); |
| 1014 | with_state(|state| { |
| 1015 | state.store_page(namespace, ref_id, page); |
| 1016 | }); |
| 1017 | } |
| 1018 | |
| 1019 | fn get_page(namespace: &str, ref_id: &str) -> Option<Arc<WebPage>> { |
| 1020 | let cache = WEB_RUN_STATE.get_or_init(WebRunCache::default); |
| 1021 | let stored = { |
| 1022 | let pages = cache.pages.read(); |
| 1023 | pages.get(ref_id).cloned() |
| 1024 | }?; |
| 1025 | if stored.namespace != namespace { |
| 1026 | return None; |
| 1027 | } |
| 1028 | { |
| 1029 | let mut sessions = cache.sessions.write(); |
| 1030 | if let Some(session) = sessions.get_mut(namespace) { |
| 1031 | session.last_access = Instant::now(); |
| 1032 | } |
| 1033 | } |
| 1034 | Some(stored.page) |
| 1035 | } |
| 1036 | |
| 1037 | #[cfg(test)] |
| 1038 | fn reset_web_run_state() { |
| 1039 | with_state(|state| { |
| 1040 | *state = WebRunState::default(); |
| 1041 | }); |
| 1042 | } |
| 1043 | |
| 1044 | #[cfg(test)] |
| 1045 | fn next_turn_for_namespace(namespace: &str) -> u64 { |
| 1046 | with_state(|state| state.next_turn(namespace)) |
| 1047 | } |
| 1048 | |
| 1049 | async fn resolve_or_fetch_page( |
| 1050 | ref_id: &str, |
| 1051 | timeout_ms: u64, |
| 1052 | context: &ToolContext, |
| 1053 | ) -> Result<Arc<WebPage>, ToolError> { |
| 1054 | if let Some(page) = get_page(&context.state_namespace, ref_id) { |
| 1055 | return Ok(page); |
| 1056 | } |
| 1057 | if let Some(citation) = super::web::citations::resolve(&context.state_namespace, ref_id) { |
| 1058 | return fetch_page(&citation.url, timeout_ms, context) |
| 1059 | .await |
| 1060 | .map(Arc::new); |
| 1061 | } |
| 1062 | if looks_like_url(ref_id) { |
| 1063 | return fetch_page(ref_id, timeout_ms, context).await.map(Arc::new); |
| 1064 | } |
| 1065 | Err(ToolError::invalid_input(format!( |
| 1066 | "Unknown ref_id '{ref_id}'" |
| 1067 | ))) |
| 1068 | } |
| 1069 | |
| 1070 | fn looks_like_url(value: &str) -> bool { |
| 1071 | value.starts_with("http://") || value.starts_with("https://") |
| 1072 | } |
| 1073 | |
| 1074 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1075 | struct DuckDuckGoImageResponse { |
| 1076 | #[serde(default)] |
| 1077 | results: Vec<DuckDuckGoImageResult>, |
| 1078 | } |
| 1079 | |
| 1080 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1081 | struct DuckDuckGoImageResult { |
| 1082 | image: String, |
| 1083 | #[serde(default)] |
| 1084 | thumbnail: Option<String>, |
| 1085 | #[serde(default)] |
| 1086 | title: Option<String>, |
| 1087 | #[serde(default)] |
| 1088 | url: Option<String>, |
| 1089 | #[serde(default)] |
| 1090 | source: Option<String>, |
| 1091 | #[serde(default)] |
| 1092 | width: Option<u32>, |
| 1093 | #[serde(default)] |
| 1094 | height: Option<u32>, |
| 1095 | } |
| 1096 | |
| 1097 | fn extract_duckduckgo_vqd(html: &str) -> Option<String> { |
| 1098 | let html = html.trim(); |
| 1099 | if html.is_empty() { |
| 1100 | return None; |
| 1101 | } |
| 1102 | |
| 1103 | for (prefix, suffix) in [("vqd='", "'"), ("vqd=\"", "\"")] { |
| 1104 | if let Some(start) = html.find(prefix) { |
| 1105 | let rest = &html[start + prefix.len()..]; |
| 1106 | if let Some(end) = rest.find(suffix) { |
| 1107 | let token = rest[..end].trim(); |
| 1108 | if !token.is_empty() { |
| 1109 | return Some(token.to_string()); |
| 1110 | } |
| 1111 | } |
| 1112 | } |
| 1113 | } |
| 1114 | |
| 1115 | // Fallback: look for `vqd=` and accept a conservative token charset. |
| 1116 | if let Some(start) = html.find("vqd=") { |
| 1117 | let rest = &html[start + 4..]; |
| 1118 | let mut token = String::new(); |
| 1119 | for ch in rest.chars() { |
| 1120 | if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' { |
| 1121 | token.push(ch); |
| 1122 | } else { |
| 1123 | break; |
| 1124 | } |
| 1125 | } |
| 1126 | if !token.is_empty() { |
| 1127 | return Some(token); |
| 1128 | } |
| 1129 | } |
| 1130 | |
| 1131 | None |
| 1132 | } |
| 1133 | |
| 1134 | async fn run_image_search( |
| 1135 | query: &str, |
| 1136 | max_results: usize, |
| 1137 | timeout_ms: u64, |
| 1138 | domains: &[String], |
| 1139 | context: &ToolContext, |
| 1140 | ) -> Result<(Vec<ImageResultEntry>, Option<String>), ToolError> { |
| 1141 | super::web_search::check_policy(context.network_policy.as_ref(), "duckduckgo.com")?; |
| 1142 | let client = crate::platform_client_builder() |
| 1143 | .timeout(Duration::from_millis(timeout_ms)) |
| 1144 | .user_agent(USER_AGENT) |
| 1145 | .build() |
| 1146 | .map_err(|e| ToolError::execution_failed(format!("Failed to build HTTP client: {e}")))?; |
| 1147 | |
| 1148 | // Step 1: fetch the HTML page to obtain the `vqd` token used by the images API. |
| 1149 | let encoded = url_encode(query); |
| 1150 | let seed_url = format!("https://duckduckgo.com/?q={encoded}&iax=images&ia=images"); |
| 1151 | let seed_resp = client |
| 1152 | .get(&seed_url) |
| 1153 | .header( |
| 1154 | "Accept", |
| 1155 | "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", |
| 1156 | ) |
| 1157 | .header("Accept-Language", "en-US,en;q=0.5") |
| 1158 | .send() |
| 1159 | .await |
| 1160 | .map_err(|e| { |
| 1161 | ToolError::execution_failed(format!("Image search seed request failed: {e}")) |
| 1162 | })?; |
| 1163 | |
| 1164 | let seed_status = seed_resp.status(); |
| 1165 | let seed_body = if super::web::adapter::search_selected(context) { |
| 1166 | super::web::adapter::read_response_with_limit(seed_resp, context, HARD_MAX_BYTES) |
| 1167 | .await |
| 1168 | .map_err(ToolError::from)? |
| 1169 | } else { |
| 1170 | let bytes = codewhale_util::utils::read_response_body_capped(seed_resp, HARD_MAX_BYTES) |
| 1171 | .await |
| 1172 | .map_err(|e| { |
| 1173 | ToolError::execution_failed(format!("Failed to read image seed response: {e}")) |
| 1174 | })?; |
| 1175 | String::from_utf8_lossy(&bytes).into_owned() |
| 1176 | }; |
| 1177 | |
| 1178 | if !seed_status.is_success() { |
| 1179 | return Err(ToolError::execution_failed(format!( |
| 1180 | "Image search seed request failed: HTTP {}", |
| 1181 | seed_status.as_u16() |
| 1182 | ))); |
| 1183 | } |
| 1184 | |
| 1185 | let vqd = extract_duckduckgo_vqd(&seed_body).ok_or_else(|| { |
| 1186 | ToolError::execution_failed("Failed to extract DuckDuckGo image token (vqd)") |
| 1187 | })?; |
| 1188 | |
| 1189 | // Step 2: query the DuckDuckGo images JSON endpoint. |
| 1190 | let api_url = format!("https://duckduckgo.com/i.js?l=us-en&o=json&q={encoded}&vqd={vqd}&p=1"); |
| 1191 | super::web_search::check_policy(context.network_policy.as_ref(), "duckduckgo.com")?; |
| 1192 | let api_resp = client |
| 1193 | .get(&api_url) |
| 1194 | .header("Accept", "application/json") |
| 1195 | .header("Referer", "https://duckduckgo.com/") |
| 1196 | .send() |
| 1197 | .await |
| 1198 | .map_err(|e| ToolError::execution_failed(format!("Image search request failed: {e}")))?; |
| 1199 | |
| 1200 | let api_status = api_resp.status(); |
| 1201 | let api_body = if super::web::adapter::search_selected(context) { |
| 1202 | super::web::adapter::read_response(api_resp, context) |
| 1203 | .await |
| 1204 | .map_err(ToolError::from)? |
| 1205 | } else { |
| 1206 | let bytes = codewhale_util::utils::read_response_body_capped(api_resp, HARD_MAX_BYTES) |
| 1207 | .await |
| 1208 | .map_err(|e| { |
| 1209 | ToolError::execution_failed(format!("Failed to read image response: {e}")) |
| 1210 | })?; |
| 1211 | String::from_utf8_lossy(&bytes).into_owned() |
| 1212 | }; |
| 1213 | |
| 1214 | if !api_status.is_success() { |
| 1215 | return Err(ToolError::execution_failed(format!( |
| 1216 | "Image search failed: HTTP {}", |
| 1217 | api_status.as_u16() |
| 1218 | ))); |
| 1219 | } |
| 1220 | |
| 1221 | let mut parsed: DuckDuckGoImageResponse = serde_json::from_str(&api_body).map_err(|e| { |
| 1222 | ToolError::execution_failed(format!("Failed to parse image search JSON: {e}")) |
| 1223 | })?; |
| 1224 | |
| 1225 | if super::web::adapter::search_selected(context) { |
| 1226 | #[derive(Deserialize)] |
| 1227 | #[serde(deny_unknown_fields)] |
| 1228 | struct Proposal { |
| 1229 | kind: String, |
| 1230 | entries: Vec<DuckDuckGoImageResult>, |
| 1231 | max_results: usize, |
| 1232 | } |
| 1233 | let mut urls = super::web_search::OpaqueUrls::default(); |
| 1234 | let mut captured = parsed.clone(); |
| 1235 | for entry in &mut captured.results { |
| 1236 | entry.image = urls.capture(&entry.image); |
| 1237 | if let Some(value) = entry.thumbnail.as_mut() { |
| 1238 | *value = urls.capture(value); |
| 1239 | } |
| 1240 | if let Some(value) = entry.url.as_mut() { |
| 1241 | *value = urls.capture(value); |
| 1242 | } |
| 1243 | } |
| 1244 | let proposal: Proposal = super::web::adapter::transform( |
| 1245 | crate::extension_host::StockOperation::WebImages, |
| 1246 | json!({"max_results":max_results,"parsed":captured}), |
| 1247 | context, |
| 1248 | Duration::from_millis(timeout_ms), |
| 1249 | ) |
| 1250 | .await |
| 1251 | .map_err(ToolError::from)?; |
| 1252 | if proposal.kind != "web_images" |
| 1253 | || proposal.max_results != max_results |
| 1254 | || proposal.entries.len() > parsed.results.len() |
| 1255 | { |
| 1256 | return Err(ToolError::execution_failed( |
| 1257 | "Web Host returned inconsistent image candidates; no fallback was attempted", |
| 1258 | )); |
| 1259 | } |
| 1260 | parsed.results = proposal.entries; |
| 1261 | for entry in &mut parsed.results { |
| 1262 | entry.image = urls.restore(&entry.image).map_err(ToolError::from)?; |
| 1263 | if let Some(value) = entry.thumbnail.as_mut() { |
| 1264 | *value = urls.restore(value).map_err(ToolError::from)?; |
| 1265 | } |
| 1266 | if let Some(value) = entry.url.as_mut() { |
| 1267 | *value = urls.restore(value).map_err(ToolError::from)?; |
| 1268 | } |
| 1269 | } |
| 1270 | } |
| 1271 | |
| 1272 | let mut results = parsed |
| 1273 | .results |
| 1274 | .into_iter() |
| 1275 | .filter(|item| !item.image.trim().is_empty()) |
| 1276 | .map(|item| ImageResultEntry { |
| 1277 | ref_id: String::new(), |
| 1278 | image: item.image, |
| 1279 | thumbnail: item.thumbnail, |
| 1280 | title: item.title, |
| 1281 | url: item.url, |
| 1282 | source: item.source, |
| 1283 | width: item.width, |
| 1284 | height: item.height, |
| 1285 | }) |
| 1286 | .collect::<Vec<_>>(); |
| 1287 | |
| 1288 | // Domain filter is applied to the source page URL when available. |
| 1289 | let warning = if !domains.is_empty() { |
| 1290 | let before = results.len(); |
| 1291 | results.retain(|entry| match entry.url.as_deref() { |
| 1292 | Some(url) => domain_matches(url, domains), |
| 1293 | None => true, |
| 1294 | }); |
| 1295 | if before != results.len() { |
| 1296 | Some("Filtered image results by domain list".to_string()) |
| 1297 | } else { |
| 1298 | None |
| 1299 | } |
| 1300 | } else { |
| 1301 | None |
| 1302 | }; |
| 1303 | |
| 1304 | results.truncate(max_results); |
| 1305 | Ok((results, warning)) |
| 1306 | } |
| 1307 | |
| 1308 | fn page_from_search(query: &str, results: &[NormalizedSearchResult]) -> WebPage { |
| 1309 | let mut lines = Vec::new(); |
| 1310 | let mut links = Vec::new(); |
| 1311 | |
| 1312 | lines.push(format!("Search results for: {query}")); |
| 1313 | for (idx, entry) in results.iter().enumerate() { |
| 1314 | let id = idx + 1; |
| 1315 | links.push(WebLink { |
| 1316 | id, |
| 1317 | url: entry.url.clone(), |
| 1318 | text: entry.title.clone(), |
| 1319 | }); |
| 1320 | lines.push(format!("{}. [{}] {}", id, id, entry.title)); |
| 1321 | if let Some(snippet) = entry.snippet.as_ref() |
| 1322 | && !snippet.trim().is_empty() |
| 1323 | { |
| 1324 | lines.push(format!(" {snippet}")); |
| 1325 | } |
| 1326 | lines.push(format!(" {url}", url = entry.url)); |
| 1327 | } |
| 1328 | |
| 1329 | WebPage { |
| 1330 | url: "https://html.duckduckgo.com/html/".to_string(), |
| 1331 | title: Some("Search Results".to_string()), |
| 1332 | content_type: Some("text/html".to_string()), |
| 1333 | lines, |
| 1334 | links, |
| 1335 | pdf_pages: None, |
| 1336 | truncated: false, |
| 1337 | partial: None, |
| 1338 | } |
| 1339 | } |
| 1340 | |
| 1341 | fn open_fetch_options(timeout_ms: u64) -> FetchOptions { |
| 1342 | FetchOptions::new( |
| 1343 | Duration::from_millis(timeout_ms), |
| 1344 | HARD_MAX_BYTES, |
| 1345 | "text/html,text/markdown,text/plain,application/xhtml+xml,application/pdf,image/*,audio/*,video/*,*/*;q=0.5", |
| 1346 | ) |
| 1347 | } |
| 1348 | |
| 1349 | /// A 401/403 earns one browser-agent retry inside [`fetch_readable`]. |
| 1350 | async fn fetch_page( |
| 1351 | url: &str, |
| 1352 | timeout_ms: u64, |
| 1353 | context: &ToolContext, |
| 1354 | ) -> Result<WebPage, ToolError> { |
| 1355 | fetch_page_with(url, &open_fetch_options(timeout_ms), context).await |
| 1356 | } |
| 1357 | |
| 1358 | async fn fetch_page_with( |
| 1359 | url: &str, |
| 1360 | options: &FetchOptions, |
| 1361 | context: &ToolContext, |
| 1362 | ) -> Result<WebPage, ToolError> { |
| 1363 | let readable = fetch_readable( |
| 1364 | url, |
| 1365 | options, |
| 1366 | context, |
| 1367 | "web_run", |
| 1368 | |payload: super::web::fetch::FetchedPayload| { |
| 1369 | Box::pin(async move { document_from_fetched(&payload, context).await }) |
| 1370 | }, |
| 1371 | ) |
| 1372 | .await?; |
| 1373 | page_from_readable(readable.payload, readable.document, context) |
| 1374 | } |
| 1375 | |
| 1376 | #[cfg(test)] |
| 1377 | async fn fetch_page_with_initial_pin( |
| 1378 | url: &str, |
| 1379 | timeout_ms: u64, |
| 1380 | context: &ToolContext, |
| 1381 | initial_pin: Option<DnsPin>, |
| 1382 | ) -> Result<WebPage, ToolError> { |
| 1383 | let readable = fetch_readable_with_initial_pin( |
| 1384 | url, |
| 1385 | &open_fetch_options(timeout_ms), |
| 1386 | context, |
| 1387 | "web_run", |
| 1388 | initial_pin.flatten(), |
| 1389 | |payload: super::web::fetch::FetchedPayload| { |
| 1390 | Box::pin(async move { document_from_fetched(&payload, context).await }) |
| 1391 | }, |
| 1392 | ) |
| 1393 | .await?; |
| 1394 | page_from_readable(readable.payload, readable.document, context) |
| 1395 | } |
| 1396 | |
| 1397 | /// Reject non-2xx responses, then extract one readable document. |
| 1398 | /// |
| 1399 | /// Kept separate from rendering so `fetch_readable` can re-run exactly this |
| 1400 | /// step against a cache-busted second response (#5904). |
| 1401 | async fn document_from_fetched( |
| 1402 | payload: &super::web::fetch::FetchedPayload, |
| 1403 | context: &ToolContext, |
| 1404 | ) -> super::web::adapter::AdapterResult<ExtractedDocument> { |
| 1405 | if !(200..300).contains(&payload.status) { |
| 1406 | return Err((ToolError::execution_failed(format!( |
| 1407 | "Web request to {} failed: HTTP {}", |
| 1408 | payload.url, payload.status |
| 1409 | ))) |
| 1410 | .into()); |
| 1411 | } |
| 1412 | extract_document( |
| 1413 | &payload.url, |
| 1414 | Some(&payload.content_type), |
| 1415 | &payload.bytes, |
| 1416 | payload.truncated, |
| 1417 | Some(context), |
| 1418 | ) |
| 1419 | .await |
| 1420 | } |
| 1421 | |
| 1422 | fn page_from_readable( |
| 1423 | payload: super::web::fetch::FetchedPayload, |
| 1424 | document: Readable<ExtractedDocument>, |
| 1425 | context: &ToolContext, |
| 1426 | ) -> Result<WebPage, ToolError> { |
| 1427 | match document { |
| 1428 | Readable::Document(document) => page_from_document(payload, document, context), |
| 1429 | Readable::Partial(page) => { |
| 1430 | page_from_document(payload, page.document, context).map(|web_page| WebPage { |
| 1431 | partial: Some(page.note), |
| 1432 | ..web_page |
| 1433 | }) |
| 1434 | } |
| 1435 | } |
| 1436 | } |
| 1437 | |
| 1438 | fn page_from_document( |
| 1439 | payload: super::web::fetch::FetchedPayload, |
| 1440 | document: ExtractedDocument, |
| 1441 | context: &ToolContext, |
| 1442 | ) -> Result<WebPage, ToolError> { |
| 1443 | let content_type = Some(payload.content_type); |
| 1444 | match document.kind { |
| 1445 | DocumentKind::Html => { |
| 1446 | let html = document.cleaned_html.ok_or_else(|| { |
| 1447 | ToolError::execution_failed("Readable HTML extraction returned no document") |
| 1448 | })?; |
| 1449 | let (lines, links, parsed_title) = parse_html(&html, &payload.url); |
| 1450 | Ok(WebPage { |
| 1451 | url: payload.url, |
| 1452 | title: document.title.or(parsed_title), |
| 1453 | content_type, |
| 1454 | lines, |
| 1455 | links, |
| 1456 | pdf_pages: None, |
| 1457 | truncated: payload.truncated, |
| 1458 | partial: None, |
| 1459 | }) |
| 1460 | } |
| 1461 | DocumentKind::Markdown => { |
| 1462 | let (lines, links) = parse_markdown(&document.markdown, &payload.url); |
| 1463 | Ok(WebPage { |
| 1464 | url: payload.url, |
| 1465 | title: document.title, |
| 1466 | content_type, |
| 1467 | lines, |
| 1468 | links, |
| 1469 | pdf_pages: None, |
| 1470 | truncated: payload.truncated, |
| 1471 | partial: None, |
| 1472 | }) |
| 1473 | } |
| 1474 | DocumentKind::Text => Ok(WebPage { |
| 1475 | url: payload.url, |
| 1476 | title: document.title, |
| 1477 | content_type, |
| 1478 | lines: readable_lines(&document.text), |
| 1479 | links: Vec::new(), |
| 1480 | pdf_pages: None, |
| 1481 | truncated: payload.truncated, |
| 1482 | partial: None, |
| 1483 | }), |
| 1484 | DocumentKind::Pdf => { |
| 1485 | let pages = document.pdf_pages.unwrap_or_default(); |
| 1486 | Ok(WebPage { |
| 1487 | url: payload.url, |
| 1488 | title: document.title, |
| 1489 | content_type, |
| 1490 | lines: pages.first().cloned().unwrap_or_default(), |
| 1491 | links: Vec::new(), |
| 1492 | pdf_pages: Some(pages), |
| 1493 | truncated: payload.truncated, |
| 1494 | partial: None, |
| 1495 | }) |
| 1496 | } |
| 1497 | DocumentKind::Media => { |
| 1498 | let extension = document.media_extension.unwrap_or("bin"); |
| 1499 | let digest = codewhale_runtime::hashing::sha256_hex(&*payload.bytes); |
| 1500 | let artifact_id = format!("web_media_{}", &digest[..16]); |
| 1501 | let (_absolute, relative) = codewhale_runtime::artifacts::write_session_artifact_bytes( |
| 1502 | &context.state_namespace, |
| 1503 | &artifact_id, |
| 1504 | extension, |
| 1505 | &payload.bytes, |
| 1506 | ) |
| 1507 | .map_err(|error| { |
| 1508 | ToolError::execution_failed(format!( |
| 1509 | "failed to preserve fetched media artifact: {error}" |
| 1510 | )) |
| 1511 | })?; |
| 1512 | let path = codewhale_runtime::artifacts::format_artifact_relative_path(&relative); |
| 1513 | Ok(WebPage { |
| 1514 | url: payload.url, |
| 1515 | title: Some("Media artifact".to_string()), |
| 1516 | content_type, |
| 1517 | lines: vec![format!("Fetched media saved to {path}")], |
| 1518 | links: Vec::new(), |
| 1519 | pdf_pages: None, |
| 1520 | truncated: payload.truncated, |
| 1521 | partial: None, |
| 1522 | }) |
| 1523 | } |
| 1524 | } |
| 1525 | } |
| 1526 | |
| 1527 | fn bounded_web_run_result( |
| 1528 | output: &WebRunOutput, |
| 1529 | context: &ToolContext, |
| 1530 | ) -> Result<ToolResult, ToolError> { |
| 1531 | let full = serde_json::to_string_pretty(output) |
| 1532 | .map_err(|error| ToolError::execution_failed(error.to_string()))?; |
| 1533 | let bounded = bound_web_text( |
| 1534 | full, |
| 1535 | context, |
| 1536 | |body| { |
| 1537 | let digest = codewhale_runtime::hashing::sha256_hex(body.as_bytes()); |
| 1538 | format!("web_run_{}", &digest[..16]) |
| 1539 | }, |
| 1540 | "web.run result", |
| 1541 | )?; |
| 1542 | let metadata = bounded.artifact.map(|artifact| { |
| 1543 | json!({ |
| 1544 | "spillover_path": artifact.absolute_path.display().to_string(), |
| 1545 | "artifact_session_id": artifact.session_id, |
| 1546 | "artifact_relative_path": codewhale_runtime::artifacts::format_artifact_relative_path(&artifact.relative_path), |
| 1547 | "artifact_byte_size": artifact.byte_size, |
| 1548 | "artifact_preview": artifact.preview, |
| 1549 | // The overflow footer points at `retrieve_tool_result`; flag the |
| 1550 | // evidence so the engine auto-activates that tool next turn (same |
| 1551 | // contract as the shell-truncation spillover). |
| 1552 | "evidence_available": true, |
| 1553 | }) |
| 1554 | }); |
| 1555 | |
| 1556 | Ok(ToolResult { |
| 1557 | content: bounded.content, |
| 1558 | success: true, |
| 1559 | metadata, |
| 1560 | }) |
| 1561 | } |
| 1562 | |
| 1563 | fn render_view( |
| 1564 | ref_id: &str, |
| 1565 | page: &WebPage, |
| 1566 | lineno: usize, |
| 1567 | response: ResponseLength, |
| 1568 | ) -> PageViewResult { |
| 1569 | let total = page.lines.len(); |
| 1570 | let view_lines = response.view_lines(); |
| 1571 | let start = if total == 0 { |
| 1572 | 1 |
| 1573 | } else if lineno > total { |
| 1574 | total.saturating_sub(view_lines.saturating_sub(1)).max(1) |
| 1575 | } else { |
| 1576 | lineno |
| 1577 | }; |
| 1578 | let end = if total == 0 { |
| 1579 | 0 |
| 1580 | } else { |
| 1581 | (start + view_lines - 1).min(total) |
| 1582 | }; |
| 1583 | |
| 1584 | let content = if total == 0 { |
| 1585 | "(no content)".to_string() |
| 1586 | } else { |
| 1587 | render_lines(&page.lines, start, end) |
| 1588 | }; |
| 1589 | |
| 1590 | PageViewResult { |
| 1591 | ref_id: ref_id.to_string(), |
| 1592 | url: page.url.clone(), |
| 1593 | title: page.title.clone(), |
| 1594 | content_type: page.content_type.clone(), |
| 1595 | line_start: start, |
| 1596 | line_end: end, |
| 1597 | total_lines: total, |
| 1598 | truncated: page.truncated, |
| 1599 | partial: page.partial.is_some(), |
| 1600 | note: page.partial.clone(), |
| 1601 | content, |
| 1602 | links: page.links.clone(), |
| 1603 | } |
| 1604 | } |
| 1605 | |
| 1606 | fn render_lines(lines: &[String], start: usize, end: usize) -> String { |
| 1607 | lines |
| 1608 | .iter() |
| 1609 | .enumerate() |
| 1610 | .filter_map(|(idx, line)| { |
| 1611 | let line_no = idx + 1; |
| 1612 | if line_no < start || line_no > end { |
| 1613 | return None; |
| 1614 | } |
| 1615 | Some(format!("{line_no:>4} {line}")) |
| 1616 | }) |
| 1617 | .collect::<Vec<_>>() |
| 1618 | .join("\n") |
| 1619 | } |
| 1620 | |
| 1621 | fn find_in_page( |
| 1622 | ref_id: &str, |
| 1623 | pattern: &str, |
| 1624 | page: &WebPage, |
| 1625 | response: ResponseLength, |
| 1626 | ) -> FindResult { |
| 1627 | let needle = pattern.to_lowercase(); |
| 1628 | let mut matches = Vec::new(); |
| 1629 | for (idx, line) in page.lines.iter().enumerate() { |
| 1630 | if line.to_lowercase().contains(&needle) { |
| 1631 | matches.push(FindMatch { |
| 1632 | line: idx + 1, |
| 1633 | text: line.clone(), |
| 1634 | }); |
| 1635 | } |
| 1636 | if matches.len() >= response.max_find_matches() { |
| 1637 | break; |
| 1638 | } |
| 1639 | } |
| 1640 | |
| 1641 | FindResult { |
| 1642 | ref_id: ref_id.to_string(), |
| 1643 | pattern: pattern.to_string(), |
| 1644 | count: matches.len(), |
| 1645 | matches, |
| 1646 | } |
| 1647 | } |
| 1648 | |
| 1649 | fn screenshot_page( |
| 1650 | ref_id: &str, |
| 1651 | pageno: usize, |
| 1652 | page: &WebPage, |
| 1653 | ) -> Result<ScreenshotResult, ToolError> { |
| 1654 | let pages = page |
| 1655 | .pdf_pages |
| 1656 | .as_ref() |
| 1657 | .ok_or_else(|| ToolError::invalid_input("screenshot is only supported for PDF pages"))?; |
| 1658 | if pages.is_empty() { |
| 1659 | return Err(ToolError::execution_failed("PDF has no pages")); |
| 1660 | } |
| 1661 | if pageno >= pages.len() { |
| 1662 | return Err(ToolError::invalid_input(format!( |
| 1663 | "pageno {pageno} out of range (0..{max})", |
| 1664 | max = pages.len().saturating_sub(1) |
| 1665 | ))); |
| 1666 | } |
| 1667 | let content = pages[pageno].join("\n"); |
| 1668 | Ok(ScreenshotResult { |
| 1669 | ref_id: ref_id.to_string(), |
| 1670 | pageno, |
| 1671 | total_pages: pages.len(), |
| 1672 | content, |
| 1673 | }) |
| 1674 | } |
| 1675 | |
| 1676 | // === HTML Parsing === |
| 1677 | |
| 1678 | static ANCHOR_RE: OnceLock<Regex> = OnceLock::new(); |
| 1679 | static TAG_RE: OnceLock<Regex> = OnceLock::new(); |
| 1680 | static BLOCK_RE: OnceLock<Regex> = OnceLock::new(); |
| 1681 | static SCRIPT_RE: OnceLock<Regex> = OnceLock::new(); |
| 1682 | static STYLE_RE: OnceLock<Regex> = OnceLock::new(); |
| 1683 | static TITLE_RE: OnceLock<Regex> = OnceLock::new(); |
| 1684 | static MARKDOWN_LINK_RE: OnceLock<Regex> = OnceLock::new(); |
| 1685 | |
| 1686 | fn get_anchor_re() -> &'static Regex { |
| 1687 | ANCHOR_RE.get_or_init(|| { |
| 1688 | Regex::new(r#"(?is)<a\s+[^>]*href\s*=\s*['\"]([^'\"]+)['\"][^>]*>(.*?)</a>"#) |
| 1689 | .expect("anchor regex") |
| 1690 | }) |
| 1691 | } |
| 1692 | |
| 1693 | fn get_tag_re() -> &'static Regex { |
| 1694 | TAG_RE.get_or_init(|| Regex::new(r"<[^>]+>").expect("tag regex")) |
| 1695 | } |
| 1696 | |
| 1697 | fn get_block_re() -> &'static Regex { |
| 1698 | BLOCK_RE.get_or_init(|| { |
| 1699 | Regex::new(r"(?is)</?(p|div|li|ul|ol|br|h[1-6]|tr|td|th|table|section|article)[^>]*>") |
| 1700 | .expect("block regex") |
| 1701 | }) |
| 1702 | } |
| 1703 | |
| 1704 | fn get_script_re() -> &'static Regex { |
| 1705 | SCRIPT_RE.get_or_init(|| Regex::new(r"(?is)<script[^>]*>.*?</script>").unwrap()) |
| 1706 | } |
| 1707 | |
| 1708 | fn get_style_re() -> &'static Regex { |
| 1709 | STYLE_RE.get_or_init(|| Regex::new(r"(?is)<style[^>]*>.*?</style>").unwrap()) |
| 1710 | } |
| 1711 | |
| 1712 | fn get_title_re() -> &'static Regex { |
| 1713 | TITLE_RE.get_or_init(|| Regex::new(r"(?is)<title[^>]*>(.*?)</title>").unwrap()) |
| 1714 | } |
| 1715 | |
| 1716 | fn parse_html(html: &str, base_url: &str) -> (Vec<String>, Vec<WebLink>, Option<String>) { |
| 1717 | let title = extract_title(html); |
| 1718 | let without_scripts = get_script_re().replace_all(html, "").to_string(); |
| 1719 | let without_styles = get_style_re().replace_all(&without_scripts, "").to_string(); |
| 1720 | |
| 1721 | let (with_links, links) = replace_links(&without_styles, base_url); |
| 1722 | let with_breaks = get_block_re().replace_all(&with_links, "\n").to_string(); |
| 1723 | let without_tags = get_tag_re().replace_all(&with_breaks, "").to_string(); |
| 1724 | let decoded = decode_html_entities(&without_tags); |
| 1725 | |
| 1726 | let mut lines = Vec::new(); |
| 1727 | for line in decoded.lines() { |
| 1728 | let trimmed = normalize_whitespace(line); |
| 1729 | if trimmed.is_empty() { |
| 1730 | continue; |
| 1731 | } |
| 1732 | for wrapped in wrap_line(&trimmed, ResponseLength::Medium.wrap_width()) { |
| 1733 | lines.push(wrapped); |
| 1734 | } |
| 1735 | } |
| 1736 | |
| 1737 | (lines, links, title) |
| 1738 | } |
| 1739 | |
| 1740 | fn parse_markdown(markdown: &str, base_url: &str) -> (Vec<String>, Vec<WebLink>) { |
| 1741 | let re = MARKDOWN_LINK_RE.get_or_init(|| { |
| 1742 | Regex::new(r#"\[([^\]]+)\]\(([^\s)]+)(?:\s+"[^"]*")?\)"#).expect("markdown link regex") |
| 1743 | }); |
| 1744 | let mut links = Vec::new(); |
| 1745 | let mut replaced = String::with_capacity(markdown.len()); |
| 1746 | let mut last = 0; |
| 1747 | for capture in re.captures_iter(markdown) { |
| 1748 | let Some(full) = capture.get(0) else { continue }; |
| 1749 | let Some(text) = capture.get(1) else { continue }; |
| 1750 | let Some(target) = capture.get(2) else { |
| 1751 | continue; |
| 1752 | }; |
| 1753 | replaced.push_str(&markdown[last..full.start()]); |
| 1754 | let id = links.len() + 1; |
| 1755 | let text = normalize_whitespace(text.as_str()); |
| 1756 | let url = resolve_url(base_url, target.as_str()); |
| 1757 | links.push(WebLink { |
| 1758 | id, |
| 1759 | url, |
| 1760 | text: text.clone(), |
| 1761 | }); |
| 1762 | replaced.push_str(&format!("[{id}] {text}")); |
| 1763 | last = full.end(); |
| 1764 | } |
| 1765 | replaced.push_str(&markdown[last..]); |
| 1766 | (readable_lines(&replaced), links) |
| 1767 | } |
| 1768 | |
| 1769 | fn readable_lines(text: &str) -> Vec<String> { |
| 1770 | text.lines() |
| 1771 | .flat_map(|line| { |
| 1772 | let line = normalize_whitespace(line); |
| 1773 | wrap_line(&line, ResponseLength::Medium.wrap_width()) |
| 1774 | }) |
| 1775 | .filter(|line| !line.is_empty()) |
| 1776 | .collect() |
| 1777 | } |
| 1778 | |
| 1779 | fn extract_title(html: &str) -> Option<String> { |
| 1780 | let re = get_title_re(); |
| 1781 | let cap = re.captures(html)?; |
| 1782 | let raw = cap.get(1)?.as_str(); |
| 1783 | let cleaned = normalize_whitespace(&decode_html_entities(raw)); |
| 1784 | if cleaned.is_empty() { |
| 1785 | None |
| 1786 | } else { |
| 1787 | Some(cleaned) |
| 1788 | } |
| 1789 | } |
| 1790 | |
| 1791 | fn replace_links(html: &str, base_url: &str) -> (String, Vec<WebLink>) { |
| 1792 | let re = get_anchor_re(); |
| 1793 | let mut links = Vec::new(); |
| 1794 | let mut output = String::with_capacity(html.len()); |
| 1795 | let mut last = 0; |
| 1796 | |
| 1797 | for cap in re.captures_iter(html) { |
| 1798 | let Some(full) = cap.get(0) else { continue }; |
| 1799 | let Some(href) = cap.get(1) else { continue }; |
| 1800 | let Some(text_match) = cap.get(2) else { |
| 1801 | continue; |
| 1802 | }; |
| 1803 | |
| 1804 | output.push_str(&html[last..full.start()]); |
| 1805 | let text = normalize_whitespace(&strip_tags(text_match.as_str())); |
| 1806 | let resolved = resolve_url(base_url, href.as_str()); |
| 1807 | if !text.is_empty() { |
| 1808 | let id = links.len() + 1; |
| 1809 | links.push(WebLink { |
| 1810 | id, |
| 1811 | url: resolved.clone(), |
| 1812 | text: text.clone(), |
| 1813 | }); |
| 1814 | output.push_str(&format!("[{id}] {text}")); |
| 1815 | } else { |
| 1816 | output.push_str(&resolved); |
| 1817 | } |
| 1818 | last = full.end(); |
| 1819 | } |
| 1820 | |
| 1821 | output.push_str(&html[last..]); |
| 1822 | (output, links) |
| 1823 | } |
| 1824 | |
| 1825 | fn resolve_url(base: &str, href: &str) -> String { |
| 1826 | if href.starts_with("http://") || href.starts_with("https://") { |
| 1827 | return href.to_string(); |
| 1828 | } |
| 1829 | if href.starts_with("//") { |
| 1830 | return format!("https:{href}"); |
| 1831 | } |
| 1832 | if let Ok(base_url) = reqwest::Url::parse(base) |
| 1833 | && let Ok(joined) = base_url.join(href) |
| 1834 | { |
| 1835 | return joined.to_string(); |
| 1836 | } |
| 1837 | href.to_string() |
| 1838 | } |
| 1839 | |
| 1840 | fn strip_tags(text: &str) -> String { |
| 1841 | get_tag_re().replace_all(text, "").to_string() |
| 1842 | } |
| 1843 | |
| 1844 | fn normalize_whitespace(text: &str) -> String { |
| 1845 | text.split_whitespace().collect::<Vec<_>>().join(" ") |
| 1846 | } |
| 1847 | |
| 1848 | /// Reflow one line to `width` terminal columns. |
| 1849 | /// |
| 1850 | /// `width` is a column budget, so every measurement here is a display width. |
| 1851 | /// Measuring `str::len()` instead made the budget script-dependent: Cyrillic |
| 1852 | /// and Greek are two bytes per single-column character and CJK three bytes per |
| 1853 | /// double-column character, so a Russian page wrapped at half the requested |
| 1854 | /// width and a Japanese one at two thirds. That is not only ragged output — |
| 1855 | /// `render_view` pages these lines by count, so the extra lines pushed real |
| 1856 | /// content past `ResponseLength::view_lines()` and the model saw a fraction of |
| 1857 | /// the page an English URL would have returned. Widths equal byte lengths for |
| 1858 | /// ASCII, so Latin-script wrapping is unchanged. |
| 1859 | fn wrap_line(text: &str, width: usize) -> Vec<String> { |
| 1860 | if UnicodeWidthStr::width(text) <= width { |
| 1861 | return vec![text.to_string()]; |
| 1862 | } |
| 1863 | let mut lines = Vec::new(); |
| 1864 | let mut current = String::new(); |
| 1865 | let mut current_width = 0usize; |
| 1866 | for word in text.split_whitespace() { |
| 1867 | let word_width = UnicodeWidthStr::width(word); |
| 1868 | if current.is_empty() { |
| 1869 | current.push_str(word); |
| 1870 | current_width = word_width; |
| 1871 | } else if current_width + word_width < width { |
| 1872 | current.push(' '); |
| 1873 | current.push_str(word); |
| 1874 | current_width += 1 + word_width; |
| 1875 | } else { |
| 1876 | lines.push(std::mem::take(&mut current)); |
| 1877 | current.push_str(word); |
| 1878 | current_width = word_width; |
| 1879 | } |
| 1880 | } |
| 1881 | if !current.is_empty() { |
| 1882 | lines.push(current); |
| 1883 | } |
| 1884 | lines |
| 1885 | } |
| 1886 | |
| 1887 | fn url_encode(input: &str) -> String { |
| 1888 | codewhale_util::utils::url_encode(input) |
| 1889 | } |
| 1890 | |
| 1891 | // === Tests === |
| 1892 | |
| 1893 | #[cfg(test)] |
| 1894 | mod tests { |
| 1895 | use super::*; |
| 1896 | use crate::tools::web::scrape::{parse_bing_results, parse_duckduckgo_results}; |
| 1897 | use std::path::PathBuf; |
| 1898 | use tokio::sync::{Mutex, MutexGuard}; |
| 1899 | |
| 1900 | static WEB_RUN_TEST_LOCK: Mutex<()> = Mutex::const_new(()); |
| 1901 | |
| 1902 | struct ArtifactRootRestore(Option<PathBuf>); |
| 1903 | |
| 1904 | impl Drop for ArtifactRootRestore { |
| 1905 | fn drop(&mut self) { |
| 1906 | codewhale_runtime::artifacts::set_test_artifact_sessions_root(self.0.take()); |
| 1907 | } |
| 1908 | } |
| 1909 | |
| 1910 | fn lock_web_run_test_state() -> MutexGuard<'static, ()> { |
| 1911 | WEB_RUN_TEST_LOCK.blocking_lock() |
| 1912 | } |
| 1913 | |
| 1914 | fn sample_page(url: &str) -> WebPage { |
| 1915 | WebPage { |
| 1916 | url: url.to_string(), |
| 1917 | title: Some("Example".to_string()), |
| 1918 | content_type: Some("text/html".to_string()), |
| 1919 | lines: vec!["example line".to_string()], |
| 1920 | links: Vec::new(), |
| 1921 | pdf_pages: None, |
| 1922 | truncated: false, |
| 1923 | partial: None, |
| 1924 | } |
| 1925 | } |
| 1926 | |
| 1927 | fn sample_page_with_link(url: &str, target: &str) -> WebPage { |
| 1928 | let mut page = sample_page(url); |
| 1929 | page.links.push(WebLink { |
| 1930 | id: 1, |
| 1931 | url: target.to_string(), |
| 1932 | text: "target".to_string(), |
| 1933 | }); |
| 1934 | page |
| 1935 | } |
| 1936 | |
| 1937 | #[test] |
| 1938 | fn html_link_parsing_extracts_links() { |
| 1939 | let html = r#" |
| 1940 | <html><body> |
| 1941 | <p>Hello <a href="https://example.com">Example</a> world.</p> |
| 1942 | </body></html> |
| 1943 | "#; |
| 1944 | let (lines, links, title) = parse_html(html, "https://example.com"); |
| 1945 | assert!(title.is_none()); |
| 1946 | assert_eq!(links.len(), 1); |
| 1947 | assert_eq!(links[0].url, "https://example.com"); |
| 1948 | assert!(lines.iter().any(|line| line.contains("Example"))); |
| 1949 | } |
| 1950 | |
| 1951 | #[test] |
| 1952 | fn html_parsing_does_not_double_decode_escaped_entities() { |
| 1953 | let html = "<html><head><title>&lt;br&gt; tag</title></head>\ |
| 1954 | <body><p>Use &lt;br&gt; here</p></body></html>"; |
| 1955 | let (lines, _links, title) = parse_html(html, "https://example.com"); |
| 1956 | assert_eq!(title.as_deref(), Some("<br> tag")); |
| 1957 | assert!( |
| 1958 | lines.iter().any(|line| line == "Use <br> here"), |
| 1959 | "lines: {lines:?}" |
| 1960 | ); |
| 1961 | } |
| 1962 | |
| 1963 | #[test] |
| 1964 | fn markdown_link_parsing_preserves_click_targets() { |
| 1965 | let (lines, links) = parse_markdown( |
| 1966 | "## Guide\n\nRead [the proof](/proof) before shipping.", |
| 1967 | "https://example.com/docs/start", |
| 1968 | ); |
| 1969 | |
| 1970 | assert_eq!(links.len(), 1); |
| 1971 | assert_eq!(links[0].url, "https://example.com/proof"); |
| 1972 | assert!(lines.iter().any(|line| line.contains("[1] the proof"))); |
| 1973 | } |
| 1974 | |
| 1975 | #[test] |
| 1976 | fn oversized_web_run_output_round_trips_through_session_artifact() { |
| 1977 | let _lock = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD |
| 1978 | .lock() |
| 1979 | .unwrap_or_else(|error| error.into_inner()); |
| 1980 | let tmp = tempfile::tempdir().unwrap(); |
| 1981 | let prior = codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some( |
| 1982 | tmp.path().join("sessions"), |
| 1983 | )); |
| 1984 | let _restore = ArtifactRootRestore(prior); |
| 1985 | let context = ToolContext::new(".") |
| 1986 | .with_state_namespace("web-run-overflow") |
| 1987 | .with_route_context_window(10_000); |
| 1988 | let output = WebRunOutput { |
| 1989 | warnings: vec!["large receipt ".repeat(200)], |
| 1990 | ..WebRunOutput::default() |
| 1991 | }; |
| 1992 | |
| 1993 | let result = bounded_web_run_result(&output, &context).unwrap(); |
| 1994 | let metadata = result.metadata.expect("artifact metadata"); |
| 1995 | let path = metadata["spillover_path"].as_str().unwrap(); |
| 1996 | let full = std::fs::read_to_string(path).unwrap(); |
| 1997 | |
| 1998 | assert!(result.content.contains("retrieve_tool_result")); |
| 1999 | assert!(result.content.chars().count() <= inline_char_budget(&context)); |
| 2000 | assert_eq!( |
| 2001 | metadata["evidence_available"], |
| 2002 | json!(true), |
| 2003 | "overflow footer points at retrieve_tool_result; the metadata must \ |
| 2004 | flag the evidence so the engine auto-activates that tool:\n{metadata}" |
| 2005 | ); |
| 2006 | assert_eq!( |
| 2007 | serde_json::from_str::<Value>(&full).unwrap()["warnings"][0], |
| 2008 | output.warnings[0] |
| 2009 | ); |
| 2010 | } |
| 2011 | |
| 2012 | #[test] |
| 2013 | fn wrap_line_measures_display_width_not_bytes() { |
| 2014 | // Same shape, two scripts: twelve four-character words. Cyrillic is two |
| 2015 | // bytes per single-column character, so measuring `len()` wrapped the |
| 2016 | // Russian text at half the requested column budget and handed |
| 2017 | // `render_view` twice as many lines to page through. |
| 2018 | let latin = ["abcd"; 12].join(" "); |
| 2019 | let cyrillic = ["абвг"; 12].join(" "); |
| 2020 | assert_eq!( |
| 2021 | wrap_line(&cyrillic, 20).len(), |
| 2022 | wrap_line(&latin, 20).len(), |
| 2023 | "cyrillic: {:?}\nlatin: {:?}", |
| 2024 | wrap_line(&cyrillic, 20), |
| 2025 | wrap_line(&latin, 20) |
| 2026 | ); |
| 2027 | for line in wrap_line(&cyrillic, 20) { |
| 2028 | assert!( |
| 2029 | UnicodeWidthStr::width(line.as_str()) <= 20, |
| 2030 | "wrapped past the column budget: {line:?}" |
| 2031 | ); |
| 2032 | } |
| 2033 | } |
| 2034 | |
| 2035 | #[test] |
| 2036 | fn wrap_line_splits_long_lines() { |
| 2037 | let line = "This is a long line that should wrap cleanly at word boundaries"; |
| 2038 | let wrapped = wrap_line(line, 20); |
| 2039 | assert!(wrapped.len() > 1); |
| 2040 | assert!(wrapped.iter().all(|l| l.len() <= 20)); |
| 2041 | } |
| 2042 | |
| 2043 | #[test] |
| 2044 | fn extracts_duckduckgo_vqd_token() { |
| 2045 | let html_single = "<script>var x = {vqd='3-1234567890'};</script>"; |
| 2046 | assert_eq!( |
| 2047 | extract_duckduckgo_vqd(html_single), |
| 2048 | Some("3-1234567890".to_string()) |
| 2049 | ); |
| 2050 | |
| 2051 | let html_double = "<script>var x = {vqd=\"3-abcdef\"};</script>"; |
| 2052 | assert_eq!( |
| 2053 | extract_duckduckgo_vqd(html_double), |
| 2054 | Some("3-abcdef".to_string()) |
| 2055 | ); |
| 2056 | |
| 2057 | let html_plain = "https://duckduckgo.com/?q=test&vqd=3-xyz_123&ia=images"; |
| 2058 | assert_eq!( |
| 2059 | extract_duckduckgo_vqd(html_plain), |
| 2060 | Some("3-xyz_123".to_string()) |
| 2061 | ); |
| 2062 | } |
| 2063 | |
| 2064 | #[tokio::test] |
| 2065 | async fn text_search_uses_configured_shared_backend_and_exposes_receipt() { |
| 2066 | use crate::tools::spec::ToolSpec; |
| 2067 | use codewhale_runtime::config::SearchProvider; |
| 2068 | use wiremock::matchers::{method, path, query_param}; |
| 2069 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 2070 | |
| 2071 | let server = MockServer::start().await; |
| 2072 | Mock::given(method("GET")) |
| 2073 | .and(path("/search")) |
| 2074 | .and(query_param("q", "shared seam")) |
| 2075 | .and(query_param("format", "json")) |
| 2076 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 2077 | "results": [{ |
| 2078 | "title": "Shared result", |
| 2079 | "url": "https://docs.example.com/shared", |
| 2080 | "content": "one adapter path" |
| 2081 | }] |
| 2082 | }))) |
| 2083 | .mount(&server) |
| 2084 | .await; |
| 2085 | |
| 2086 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 2087 | let mut context = ToolContext::new(tmp.path().to_path_buf()); |
| 2088 | context.search_provider = SearchProvider::Searxng; |
| 2089 | context.search_base_url = Some(server.uri()); |
| 2090 | context.state_namespace = "shared-backend-test".to_string(); |
| 2091 | |
| 2092 | let result = WebRunTool |
| 2093 | .execute( |
| 2094 | json!({ |
| 2095 | "search_query": [{ |
| 2096 | "q": "shared seam", |
| 2097 | "recency": 7, |
| 2098 | "domains": ["example.com"] |
| 2099 | }] |
| 2100 | }), |
| 2101 | &context, |
| 2102 | ) |
| 2103 | .await |
| 2104 | .expect("web.run should use configured SearXNG backend"); |
| 2105 | let value: Value = serde_json::from_str(&result.content).expect("web.run json"); |
| 2106 | let search = &value["search_query"][0]; |
| 2107 | |
| 2108 | assert_eq!(search["source"], "searxng"); |
| 2109 | assert_eq!(search["count"], 1); |
| 2110 | assert_eq!(search["results"][0]["rank"], 1); |
| 2111 | assert_eq!(search["results"][0]["domain"], "docs.example.com"); |
| 2112 | assert_eq!(search["receipt"]["backend"], "searxng"); |
| 2113 | assert_eq!(search["receipt"]["honored"]["domains"], true); |
| 2114 | assert_eq!( |
| 2115 | search["receipt"]["honored"]["recency"], true, |
| 2116 | "SearXNG forwards recency as time_range" |
| 2117 | ); |
| 2118 | } |
| 2119 | |
| 2120 | #[tokio::test] |
| 2121 | async fn search_ref_ids_resolve_to_their_source_urls_for_open() { |
| 2122 | use crate::tools::spec::ToolSpec; |
| 2123 | use codewhale_runtime::config::SearchProvider; |
| 2124 | use wiremock::matchers::{method, path, query_param}; |
| 2125 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 2126 | |
| 2127 | let server = MockServer::start().await; |
| 2128 | Mock::given(method("GET")) |
| 2129 | .and(path("/search")) |
| 2130 | .and(query_param("q", "citation handoff")) |
| 2131 | .and(query_param("format", "json")) |
| 2132 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 2133 | "results": [{ |
| 2134 | "title": "Handoff target", |
| 2135 | "url": "https://docs.example.com/handoff", |
| 2136 | "content": "the page a later open command fetches" |
| 2137 | }] |
| 2138 | }))) |
| 2139 | .mount(&server) |
| 2140 | .await; |
| 2141 | |
| 2142 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 2143 | let mut context = ToolContext::new(tmp.path().to_path_buf()); |
| 2144 | context.search_provider = SearchProvider::Searxng; |
| 2145 | context.search_base_url = Some(server.uri()); |
| 2146 | context.state_namespace = "handoff-citation-test".to_string(); |
| 2147 | |
| 2148 | let result = WebRunTool |
| 2149 | .execute( |
| 2150 | json!({"search_query": [{"q": "citation handoff"}]}), |
| 2151 | &context, |
| 2152 | ) |
| 2153 | .await |
| 2154 | .expect("web.run search should succeed"); |
| 2155 | let value: Value = serde_json::from_str(&result.content).expect("web.run json"); |
| 2156 | let ref_id = value["search_query"][0]["results"][0]["ref_id"] |
| 2157 | .as_str() |
| 2158 | .expect("every search result carries a minted ref_id") |
| 2159 | .to_string(); |
| 2160 | |
| 2161 | // `open` resolves search-result refs through the shared citation |
| 2162 | // registry; the handoff must preserve the exact source URL. |
| 2163 | let citation = crate::tools::web::citations::resolve(&context.state_namespace, &ref_id) |
| 2164 | .expect("search result ref must resolve for a later open"); |
| 2165 | assert_eq!(citation.url, "https://docs.example.com/handoff"); |
| 2166 | assert_eq!(citation.title.as_deref(), Some("Handoff target")); |
| 2167 | assert!( |
| 2168 | crate::tools::web::citations::resolve("foreign-session", &ref_id).is_none(), |
| 2169 | "citation handles must stay session-scoped" |
| 2170 | ); |
| 2171 | } |
| 2172 | |
| 2173 | #[tokio::test] |
| 2174 | async fn open_failure_reports_url_and_status() { |
| 2175 | let payload = crate::tools::web::fetch::FetchedPayload { |
| 2176 | url: "https://example.com/missing".to_string(), |
| 2177 | status: 404, |
| 2178 | headers: std::collections::BTreeMap::new(), |
| 2179 | content_type: "text/html".to_string(), |
| 2180 | bytes: Arc::new(Vec::new()), |
| 2181 | truncated: false, |
| 2182 | cache_hit: false, |
| 2183 | retries: 0, |
| 2184 | redirects: 0, |
| 2185 | }; |
| 2186 | let context = ToolContext::new(PathBuf::from(".")); |
| 2187 | |
| 2188 | let error = document_from_fetched(&payload, &context) |
| 2189 | .await |
| 2190 | .expect_err("non-2xx pages must not be rendered"); |
| 2191 | let message = error.to_string(); |
| 2192 | assert!( |
| 2193 | message.contains("https://example.com/missing"), |
| 2194 | "transport failures must name the URL: {message}" |
| 2195 | ); |
| 2196 | assert!(message.contains("404"), "got `{message}`"); |
| 2197 | } |
| 2198 | |
| 2199 | #[test] |
| 2200 | fn response_length_result_counts_are_anchored_to_the_shared_contract() { |
| 2201 | assert_eq!(ResponseLength::Short.max_results(), DEFAULT_SEARCH_RESULTS); |
| 2202 | assert_eq!( |
| 2203 | ResponseLength::Long.max_results(), |
| 2204 | usize::from(MAX_SEARCH_RESULTS) |
| 2205 | ); |
| 2206 | assert!(ResponseLength::Medium.max_results() <= usize::from(MAX_SEARCH_RESULTS)); |
| 2207 | } |
| 2208 | |
| 2209 | #[test] |
| 2210 | fn parses_bing_results_and_decodes_redirect_url() { |
| 2211 | let html = r#" |
| 2212 | <ol> |
| 2213 | <li class="b_algo"> |
| 2214 | <h2><a href="https://www.bing.com/ck/a?u=a1aHR0cHM6Ly9leGFtcGxlLmNvbS9wYXRoP3E9MQ">Example & Result</a></h2> |
| 2215 | <div class="b_caption"><p>A <strong>useful</strong> snippet.</p></div> |
| 2216 | </li> |
| 2217 | </ol> |
| 2218 | "#; |
| 2219 | |
| 2220 | let results = parse_bing_results(html, 5); |
| 2221 | |
| 2222 | assert_eq!(results.len(), 1); |
| 2223 | assert_eq!(results[0].title, "Example & Result"); |
| 2224 | assert_eq!(results[0].url, "https://example.com/path?q=1"); |
| 2225 | assert_eq!(results[0].snippet.as_deref(), Some("A useful snippet.")); |
| 2226 | } |
| 2227 | |
| 2228 | #[test] |
| 2229 | fn web_run_search_path_filters_known_spam_domain() { |
| 2230 | // The shared scraper used by web_run filters the known #964 spam family. |
| 2231 | let html = r#" |
| 2232 | <a class="result__a" href="https://astralia.forumgratuit.org/a">A</a> |
| 2233 | <a class="result__snippet">spam</a> |
| 2234 | <a class="result__a" href="https://russia.forumgratuit.org/b">B</a> |
| 2235 | <a class="result__snippet">spam</a> |
| 2236 | <a class="result__a" href="https://other.forumgratuit.org/c">C</a> |
| 2237 | <a class="result__snippet">spam</a> |
| 2238 | <a class="result__a" href="https://hello.forumgratuit.org/d">D</a> |
| 2239 | <a class="result__snippet">spam</a> |
| 2240 | <a class="result__a" href="https://world.forumgratuit.org/e">E</a> |
| 2241 | <a class="result__snippet">spam</a> |
| 2242 | "#; |
| 2243 | let results = parse_duckduckgo_results(html, 10); |
| 2244 | assert!( |
| 2245 | results.is_empty(), |
| 2246 | "web_run path must drop the known spam family via the shared scraper" |
| 2247 | ); |
| 2248 | } |
| 2249 | |
| 2250 | #[test] |
| 2251 | fn domain_scoped_fixture_preserves_legitimate_same_site_results() { |
| 2252 | let html = r#" |
| 2253 | <a class="result__a" href="https://docs.example.co.uk/a">A</a> |
| 2254 | <a class="result__snippet">s</a> |
| 2255 | <a class="result__a" href="https://docs.example.co.uk/b">B</a> |
| 2256 | <a class="result__snippet">s</a> |
| 2257 | <a class="result__a" href="https://docs.example.co.uk/c">C</a> |
| 2258 | <a class="result__snippet">s</a> |
| 2259 | <a class="result__a" href="https://other.example/d">D</a> |
| 2260 | <a class="result__snippet">s</a> |
| 2261 | "#; |
| 2262 | let domains = vec!["docs.example.co.uk".to_string()]; |
| 2263 | let mut results = parse_duckduckgo_results(html, 10); |
| 2264 | results.retain(|entry| domain_matches(&entry.url, &domains)); |
| 2265 | |
| 2266 | assert_eq!(results.len(), 3); |
| 2267 | assert!( |
| 2268 | results |
| 2269 | .iter() |
| 2270 | .all(|entry| entry.url.contains("docs.example.co.uk")) |
| 2271 | ); |
| 2272 | } |
| 2273 | |
| 2274 | #[test] |
| 2275 | fn scoped_ref_prefix_is_session_specific() { |
| 2276 | let _lock = lock_web_run_test_state(); |
| 2277 | reset_web_run_state(); |
| 2278 | let alpha = scoped_ref_prefix("session-alpha"); |
| 2279 | let beta = scoped_ref_prefix("session-beta"); |
| 2280 | |
| 2281 | assert_ne!(alpha, beta); |
| 2282 | assert!(alpha.starts_with('s')); |
| 2283 | assert!(alpha.ends_with('_')); |
| 2284 | assert_eq!(alpha.len(), 18); |
| 2285 | } |
| 2286 | |
| 2287 | #[test] |
| 2288 | fn stored_pages_do_not_cross_scoped_sessions() { |
| 2289 | let _lock = lock_web_run_test_state(); |
| 2290 | reset_web_run_state(); |
| 2291 | let shared_suffix = "turn1search1"; |
| 2292 | let ref_alpha = format!("{}{}", scoped_ref_prefix("session-alpha"), shared_suffix); |
| 2293 | let ref_beta = format!("{}{}", scoped_ref_prefix("session-beta"), shared_suffix); |
| 2294 | |
| 2295 | store_page( |
| 2296 | "session-alpha", |
| 2297 | &ref_alpha, |
| 2298 | sample_page("https://example.com/alpha"), |
| 2299 | ); |
| 2300 | |
| 2301 | assert!(get_page("session-alpha", &ref_alpha).is_some()); |
| 2302 | assert!(get_page("session-beta", &ref_alpha).is_none()); |
| 2303 | assert!(get_page("session-beta", &ref_beta).is_none()); |
| 2304 | } |
| 2305 | |
| 2306 | #[tokio::test(flavor = "current_thread")] |
| 2307 | async fn execute_open_rejects_exact_foreign_session_ref() { |
| 2308 | let _lock = WEB_RUN_TEST_LOCK.lock().await; |
| 2309 | reset_web_run_state(); |
| 2310 | let ref_id = format!("{}turn0search1", scoped_ref_prefix("foreign-open-owner")); |
| 2311 | store_page( |
| 2312 | "foreign-open-owner", |
| 2313 | &ref_id, |
| 2314 | sample_page("https://example.com/private-session-page"), |
| 2315 | ); |
| 2316 | let context = |
| 2317 | ToolContext::new(PathBuf::from(".")).with_state_namespace("foreign-open-caller"); |
| 2318 | |
| 2319 | let err = WebRunTool |
| 2320 | .execute(json!({"open": [{"ref_id": ref_id}]}), &context) |
| 2321 | .await |
| 2322 | .expect_err("foreign exact ref must not open"); |
| 2323 | |
| 2324 | assert!(format!("{err}").contains("Unknown ref_id")); |
| 2325 | } |
| 2326 | |
| 2327 | #[tokio::test(flavor = "current_thread")] |
| 2328 | async fn execute_click_rejects_exact_foreign_session_ref() { |
| 2329 | let _lock = WEB_RUN_TEST_LOCK.lock().await; |
| 2330 | reset_web_run_state(); |
| 2331 | let ref_id = format!("{}turn0search1", scoped_ref_prefix("foreign-click-owner")); |
| 2332 | store_page( |
| 2333 | "foreign-click-owner", |
| 2334 | &ref_id, |
| 2335 | sample_page_with_link( |
| 2336 | "https://example.com/private-session-page", |
| 2337 | "https://example.com/target", |
| 2338 | ), |
| 2339 | ); |
| 2340 | let context = |
| 2341 | ToolContext::new(PathBuf::from(".")).with_state_namespace("foreign-click-caller"); |
| 2342 | |
| 2343 | let err = WebRunTool |
| 2344 | .execute(json!({"click": [{"ref_id": ref_id, "id": 1}]}), &context) |
| 2345 | .await |
| 2346 | .expect_err("foreign exact ref must not be clickable"); |
| 2347 | |
| 2348 | assert!(format!("{err}").contains("Unknown ref_id")); |
| 2349 | } |
| 2350 | |
| 2351 | #[tokio::test(flavor = "current_thread")] |
| 2352 | async fn execute_click_routes_target_through_shared_ssrf_guard() { |
| 2353 | let _lock = WEB_RUN_TEST_LOCK.lock().await; |
| 2354 | reset_web_run_state(); |
| 2355 | let namespace = "guarded-click-session"; |
| 2356 | let ref_id = format!("{}turn0search1", scoped_ref_prefix(namespace)); |
| 2357 | store_page( |
| 2358 | namespace, |
| 2359 | &ref_id, |
| 2360 | sample_page_with_link("https://example.com/source", "http://127.0.0.1/admin"), |
| 2361 | ); |
| 2362 | let context = ToolContext::new(PathBuf::from(".")).with_state_namespace(namespace); |
| 2363 | |
| 2364 | let err = WebRunTool |
| 2365 | .execute(json!({"click": [{"ref_id": ref_id, "id": 1}]}), &context) |
| 2366 | .await |
| 2367 | .expect_err("click target must be SSRF-guarded"); |
| 2368 | |
| 2369 | assert!(format!("{err}").contains("restricted address")); |
| 2370 | } |
| 2371 | |
| 2372 | #[test] |
| 2373 | fn cached_page_reads_share_page_arc() { |
| 2374 | let _lock = lock_web_run_test_state(); |
| 2375 | reset_web_run_state(); |
| 2376 | let namespace = "session-alpha"; |
| 2377 | let ref_id = format!("{}turn0search1", scoped_ref_prefix(namespace)); |
| 2378 | store_page(namespace, &ref_id, sample_page("https://example.com/alpha")); |
| 2379 | |
| 2380 | let first = get_page(namespace, &ref_id).expect("first page read"); |
| 2381 | let second = get_page(namespace, &ref_id).expect("second page read"); |
| 2382 | |
| 2383 | assert!(Arc::ptr_eq(&first, &second)); |
| 2384 | } |
| 2385 | |
| 2386 | #[test] |
| 2387 | fn turn_counters_are_scoped_per_session() { |
| 2388 | let _lock = lock_web_run_test_state(); |
| 2389 | reset_web_run_state(); |
| 2390 | |
| 2391 | assert_eq!(next_turn_for_namespace("session-alpha"), 0); |
| 2392 | assert_eq!(next_turn_for_namespace("session-alpha"), 1); |
| 2393 | assert_eq!(next_turn_for_namespace("session-beta"), 0); |
| 2394 | } |
| 2395 | |
| 2396 | #[test] |
| 2397 | fn with_state_restores_cache_after_panic() { |
| 2398 | let _lock = lock_web_run_test_state(); |
| 2399 | reset_web_run_state(); |
| 2400 | let namespace = "session-alpha"; |
| 2401 | let ref_id = format!("{}turn0search1", scoped_ref_prefix(namespace)); |
| 2402 | store_page(namespace, &ref_id, sample_page("https://example.com/alpha")); |
| 2403 | |
| 2404 | let panic_result = std::panic::catch_unwind(|| { |
| 2405 | with_state(|state| { |
| 2406 | let session = state |
| 2407 | .sessions |
| 2408 | .get_mut(namespace) |
| 2409 | .expect("session should exist"); |
| 2410 | session.next_turn = 42; |
| 2411 | panic!("exercise web_run write-back guard"); |
| 2412 | }); |
| 2413 | }); |
| 2414 | |
| 2415 | assert!(panic_result.is_err()); |
| 2416 | assert!(get_page(namespace, &ref_id).is_some()); |
| 2417 | assert_eq!(next_turn_for_namespace(namespace), 42); |
| 2418 | } |
| 2419 | |
| 2420 | #[test] |
| 2421 | fn stale_session_pages_are_evicted() { |
| 2422 | let _lock = lock_web_run_test_state(); |
| 2423 | reset_web_run_state(); |
| 2424 | let namespace = "session-alpha"; |
| 2425 | let ref_id = format!("{}turn0search1", scoped_ref_prefix(namespace)); |
| 2426 | store_page(namespace, &ref_id, sample_page("https://example.com/alpha")); |
| 2427 | |
| 2428 | // On Windows, Instant's epoch is system boot. If the CI runner has |
| 2429 | // been up for less than WEB_RUN_SESSION_TTL the subtraction would |
| 2430 | // underflow, so we skip the test in that case. |
| 2431 | let stale = WEB_RUN_SESSION_TTL + Duration::from_secs(1); |
| 2432 | let can_test = with_state(|state| { |
| 2433 | let session = state |
| 2434 | .sessions |
| 2435 | .get_mut(namespace) |
| 2436 | .expect("session should exist"); |
| 2437 | match Instant::now().checked_sub(stale) { |
| 2438 | Some(past) => { |
| 2439 | session.last_access = past; |
| 2440 | true |
| 2441 | } |
| 2442 | None => false, |
| 2443 | } |
| 2444 | }); |
| 2445 | if !can_test { |
| 2446 | // System uptime shorter than session TTL; can't test eviction. |
| 2447 | return; |
| 2448 | } |
| 2449 | |
| 2450 | let _ = next_turn_for_namespace("session-beta"); |
| 2451 | |
| 2452 | assert!(get_page(namespace, &ref_id).is_none()); |
| 2453 | } |
| 2454 | |
| 2455 | #[test] |
| 2456 | fn direct_urls_remain_compatible_open_refs() { |
| 2457 | assert!(looks_like_url("https://example.com")); |
| 2458 | assert!(looks_like_url("http://example.com")); |
| 2459 | assert!(!looks_like_url("turn0search0")); |
| 2460 | } |
| 2461 | |
| 2462 | #[tokio::test] |
| 2463 | async fn network_policy_denies_direct_open_url() { |
| 2464 | use codewhale_net::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 2465 | |
| 2466 | let policy = NetworkPolicy { |
| 2467 | default: Decision::Deny.into(), |
| 2468 | allow: vec!["api.deepseek.com".to_string()], |
| 2469 | deny: vec![], |
| 2470 | proxy: Vec::new(), |
| 2471 | proxy_fake_ip_cidrs: Vec::new(), |
| 2472 | audit: false, |
| 2473 | }; |
| 2474 | let decider = NetworkPolicyDecider::new(policy, None); |
| 2475 | let ctx = ToolContext::new(PathBuf::from(".")).with_network_policy(decider); |
| 2476 | |
| 2477 | let err = fetch_page("https://example.com/private", 5_000, &ctx) |
| 2478 | .await |
| 2479 | .expect_err("blocked host should fail"); |
| 2480 | assert!(format!("{err}").contains("blocked by network policy")); |
| 2481 | } |
| 2482 | |
| 2483 | fn ssrf_ctx() -> ToolContext { |
| 2484 | ToolContext::new(PathBuf::from(".")) |
| 2485 | } |
| 2486 | |
| 2487 | #[tokio::test] |
| 2488 | async fn open_refuses_loopback_ip_url() { |
| 2489 | let err = resolve_or_fetch_page("http://127.0.0.1/", 5_000, &ssrf_ctx()) |
| 2490 | .await |
| 2491 | .expect_err("loopback open must be refused"); |
| 2492 | assert!( |
| 2493 | format!("{err}").contains("restricted address"), |
| 2494 | "expected restricted-address error; got {err}" |
| 2495 | ); |
| 2496 | } |
| 2497 | |
| 2498 | #[tokio::test] |
| 2499 | async fn open_resolves_shared_citation_refs_only_in_their_session() { |
| 2500 | let namespace = "shared-citation-open-session"; |
| 2501 | let citation = crate::tools::web::citations::register( |
| 2502 | namespace, |
| 2503 | "http://127.0.0.1/private", |
| 2504 | Some("Private target"), |
| 2505 | ) |
| 2506 | .expect("valid HTTP citation metadata"); |
| 2507 | let owner_context = ToolContext::new(PathBuf::from(".")).with_state_namespace(namespace); |
| 2508 | let owner_error = resolve_or_fetch_page(&citation.ref_id, 5_000, &owner_context) |
| 2509 | .await |
| 2510 | .expect_err("resolved citation must still use the SSRF guard"); |
| 2511 | assert!(format!("{owner_error}").contains("restricted address")); |
| 2512 | |
| 2513 | let foreign_context = ToolContext::new(PathBuf::from(".")) |
| 2514 | .with_state_namespace("shared-citation-foreign-session"); |
| 2515 | let foreign_error = resolve_or_fetch_page(&citation.ref_id, 5_000, &foreign_context) |
| 2516 | .await |
| 2517 | .expect_err("foreign session must not resolve citation ref"); |
| 2518 | assert!(format!("{foreign_error}").contains("Unknown ref_id")); |
| 2519 | } |
| 2520 | |
| 2521 | #[tokio::test] |
| 2522 | async fn open_refuses_private_range_ip_url() { |
| 2523 | let err = resolve_or_fetch_page("http://192.168.1.50/admin", 5_000, &ssrf_ctx()) |
| 2524 | .await |
| 2525 | .expect_err("private-range open must be refused"); |
| 2526 | assert!( |
| 2527 | format!("{err}").contains("restricted address"), |
| 2528 | "expected restricted-address error; got {err}" |
| 2529 | ); |
| 2530 | } |
| 2531 | |
| 2532 | #[tokio::test] |
| 2533 | async fn open_refuses_metadata_endpoint_ip_url() { |
| 2534 | let err = resolve_or_fetch_page( |
| 2535 | "http://169.254.169.254/latest/meta-data", |
| 2536 | 5_000, |
| 2537 | &ssrf_ctx(), |
| 2538 | ) |
| 2539 | .await |
| 2540 | .expect_err("cloud metadata open must be refused"); |
| 2541 | assert!( |
| 2542 | format!("{err}").contains("restricted address"), |
| 2543 | "expected restricted-address error; got {err}" |
| 2544 | ); |
| 2545 | } |
| 2546 | |
| 2547 | #[tokio::test] |
| 2548 | async fn open_refuses_redirect_from_public_host_to_private_ip() { |
| 2549 | use wiremock::matchers::method; |
| 2550 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 2551 | |
| 2552 | // Use a public-looking hostname pinned to the local fixture for the |
| 2553 | // already-validated first hop. The redirect itself still goes through |
| 2554 | // the real shared guard inside fetch_page's redirect loop. |
| 2555 | let server = MockServer::start().await; |
| 2556 | let private_location = "http://10.0.0.5/internal"; |
| 2557 | Mock::given(method("GET")) |
| 2558 | .respond_with(ResponseTemplate::new(302).insert_header("Location", private_location)) |
| 2559 | .mount(&server) |
| 2560 | .await; |
| 2561 | let host = "public-redirect.example.test"; |
| 2562 | let initial_url = format!("http://{host}:{}/", server.address().port()); |
| 2563 | let pin = Some((host.to_string(), "127.0.0.1".parse().unwrap())); |
| 2564 | |
| 2565 | let err = fetch_page_with_initial_pin(&initial_url, 5_000, &ssrf_ctx(), Some(pin)) |
| 2566 | .await |
| 2567 | .expect_err("guarded redirect to private IP must be refused"); |
| 2568 | assert!( |
| 2569 | format!("{err}").contains("restricted address"), |
| 2570 | "redirect loop must surface the shared guard rejection; got {err}" |
| 2571 | ); |
| 2572 | } |
| 2573 | |
| 2574 | #[tokio::test(flavor = "current_thread")] |
| 2575 | async fn execute_fails_fast_when_no_op_key_matches() { |
| 2576 | // #5123-class: the natural {"query": …} shape matched no op key and |
| 2577 | // previously returned an empty SUCCESS ({"warnings":[]}). |
| 2578 | let _lock = WEB_RUN_TEST_LOCK.lock().await; |
| 2579 | reset_web_run_state(); |
| 2580 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 2581 | let context = ToolContext::new(tmp.path()); |
| 2582 | |
| 2583 | let err = WebRunTool |
| 2584 | .execute(json!({"query": "rust async runtime"}), &context) |
| 2585 | .await |
| 2586 | .expect_err("unmatched op keys must fail, not return empty success"); |
| 2587 | let message = format!("{err}"); |
| 2588 | assert!(message.contains("performed no operation"), "{message}"); |
| 2589 | assert!(message.contains("search_query"), "{message}"); |
| 2590 | assert!(message.contains("query"), "{message}"); |
| 2591 | |
| 2592 | let err = WebRunTool |
| 2593 | .execute(json!({}), &context) |
| 2594 | .await |
| 2595 | .expect_err("empty input must fail fast"); |
| 2596 | assert!(format!("{err}").contains("performed no operation"), "{err}"); |
| 2597 | } |
| 2598 | |
| 2599 | #[tokio::test] |
| 2600 | async fn open_retries_as_browser_once_after_a_refusal() { |
| 2601 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 2602 | use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate, matchers::method}; |
| 2603 | |
| 2604 | #[derive(Clone)] |
| 2605 | struct RefuseBots(Arc<AtomicUsize>); |
| 2606 | impl Respond for RefuseBots { |
| 2607 | fn respond(&self, request: &Request) -> ResponseTemplate { |
| 2608 | self.0.fetch_add(1, Ordering::SeqCst); |
| 2609 | let agent = request |
| 2610 | .headers |
| 2611 | .get("user-agent") |
| 2612 | .and_then(|value| value.to_str().ok()) |
| 2613 | .unwrap_or_default(); |
| 2614 | if agent.contains("codewhale") { |
| 2615 | ResponseTemplate::new(403) |
| 2616 | } else { |
| 2617 | ResponseTemplate::new(200) |
| 2618 | .insert_header("content-type", "text/plain") |
| 2619 | .set_body_string("review body") |
| 2620 | } |
| 2621 | } |
| 2622 | } |
| 2623 | |
| 2624 | let server = MockServer::start().await; |
| 2625 | let calls = Arc::new(AtomicUsize::new(0)); |
| 2626 | Mock::given(method("GET")) |
| 2627 | .respond_with(RefuseBots(Arc::clone(&calls))) |
| 2628 | .mount(&server) |
| 2629 | .await; |
| 2630 | let host = "refuses-bots.example.test"; |
| 2631 | let url = format!("http://{host}:{}/review", server.address().port()); |
| 2632 | let pin = Some((host.to_string(), "127.0.0.1".parse().unwrap())); |
| 2633 | let context = ToolContext::new(PathBuf::from(".")).with_state_namespace("refuse-bots"); |
| 2634 | |
| 2635 | let page = fetch_page_with_initial_pin(&url, 5_000, &context, Some(pin)) |
| 2636 | .await |
| 2637 | .expect("browser-agent fallback loads the page"); |
| 2638 | assert!(page.lines.iter().any(|line| line.contains("review body"))); |
| 2639 | assert_eq!( |
| 2640 | calls.load(Ordering::SeqCst), |
| 2641 | 2, |
| 2642 | "exactly one fallback request" |
| 2643 | ); |
| 2644 | } |
| 2645 | |
| 2646 | #[tokio::test] |
| 2647 | async fn open_does_not_retry_a_missing_page_as_browser() { |
| 2648 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 2649 | use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate, matchers::method}; |
| 2650 | |
| 2651 | #[derive(Clone)] |
| 2652 | struct Missing(Arc<AtomicUsize>); |
| 2653 | impl Respond for Missing { |
| 2654 | fn respond(&self, _request: &Request) -> ResponseTemplate { |
| 2655 | self.0.fetch_add(1, Ordering::SeqCst); |
| 2656 | ResponseTemplate::new(404) |
| 2657 | } |
| 2658 | } |
| 2659 | |
| 2660 | let server = MockServer::start().await; |
| 2661 | let calls = Arc::new(AtomicUsize::new(0)); |
| 2662 | Mock::given(method("GET")) |
| 2663 | .respond_with(Missing(Arc::clone(&calls))) |
| 2664 | .mount(&server) |
| 2665 | .await; |
| 2666 | let host = "missing.example.test"; |
| 2667 | let url = format!("http://{host}:{}/gone", server.address().port()); |
| 2668 | let pin = Some((host.to_string(), "127.0.0.1".parse().unwrap())); |
| 2669 | let context = ToolContext::new(PathBuf::from(".")).with_state_namespace("missing-page"); |
| 2670 | |
| 2671 | let err = fetch_page_with_initial_pin(&url, 5_000, &context, Some(pin)) |
| 2672 | .await |
| 2673 | .expect_err("404 stays a failure"); |
| 2674 | assert_eq!(http_status_of(&err.to_string()), Some(404)); |
| 2675 | assert_eq!(calls.load(Ordering::SeqCst), 1); |
| 2676 | } |
| 2677 | |
| 2678 | #[test] |
| 2679 | fn source_failures_are_classified_and_gates_pass_through() { |
| 2680 | let _lock = lock_web_run_test_state(); |
| 2681 | reset_web_run_state(); |
| 2682 | let namespace = "source-failure-session"; |
| 2683 | |
| 2684 | let refused = source_failure( |
| 2685 | namespace, |
| 2686 | "https://reviews.example.com/espresso", |
| 2687 | ToolError::execution_failed( |
| 2688 | "Web request to https://reviews.example.com/espresso failed: HTTP 403", |
| 2689 | ), |
| 2690 | ) |
| 2691 | .expect("a refusal is a source outcome"); |
| 2692 | assert_eq!(refused.status, SourceStatus::Unavailable); |
| 2693 | assert!( |
| 2694 | with_state(|state| state.refusing_hosts(namespace)).contains("reviews.example.com"), |
| 2695 | "a refusing host is remembered for this session" |
| 2696 | ); |
| 2697 | |
| 2698 | let flaky = source_failure( |
| 2699 | namespace, |
| 2700 | "https://slow.example.com/", |
| 2701 | ToolError::execution_failed( |
| 2702 | "Web request to https://slow.example.com/ failed: HTTP 503", |
| 2703 | ), |
| 2704 | ) |
| 2705 | .expect("a 5xx is a source outcome"); |
| 2706 | assert_eq!(flaky.status, SourceStatus::Transient); |
| 2707 | let timeout = source_failure( |
| 2708 | namespace, |
| 2709 | "https://slow.example.com/", |
| 2710 | ToolError::execution_failed("request timed out before retry completed"), |
| 2711 | ) |
| 2712 | .expect("a timeout is a source outcome"); |
| 2713 | assert_eq!(timeout.status, SourceStatus::Transient); |
| 2714 | |
| 2715 | let gate = source_failure( |
| 2716 | namespace, |
| 2717 | "http://10.0.0.5/", |
| 2718 | ToolError::permission_denied("IP 10.0.0.5 is a restricted address"), |
| 2719 | ); |
| 2720 | assert!( |
| 2721 | gate.is_err(), |
| 2722 | "gates must never be softened into source outcomes" |
| 2723 | ); |
| 2724 | let bad_ref = source_failure( |
| 2725 | namespace, |
| 2726 | "turn9search9", |
| 2727 | ToolError::invalid_input("Unknown ref_id 'turn9search9'"), |
| 2728 | ); |
| 2729 | assert!(bad_ref.is_err(), "caller mistakes stay errors"); |
| 2730 | } |
| 2731 | |
| 2732 | #[test] |
| 2733 | fn search_results_prefer_hosts_that_load() { |
| 2734 | let mut results = vec![ |
| 2735 | NormalizedSearchResult::new( |
| 2736 | 1, |
| 2737 | "a".into(), |
| 2738 | "https://blocked.example/a".into(), |
| 2739 | None, |
| 2740 | None, |
| 2741 | ), |
| 2742 | NormalizedSearchResult::new(2, "b".into(), "https://open.example/b".into(), None, None), |
| 2743 | NormalizedSearchResult::new(3, "c".into(), "https://open.example/c".into(), None, None), |
| 2744 | ]; |
| 2745 | let refusing = HashSet::from(["blocked.example".to_string()]); |
| 2746 | prefer_loading_sources(&mut results, &refusing); |
| 2747 | let order: Vec<_> = results.iter().map(|r| (r.rank, r.url.as_str())).collect(); |
| 2748 | assert_eq!( |
| 2749 | order, |
| 2750 | vec![ |
| 2751 | (1, "https://open.example/b"), |
| 2752 | (2, "https://open.example/c"), |
| 2753 | (3, "https://blocked.example/a"), |
| 2754 | ] |
| 2755 | ); |
| 2756 | } |
| 2757 | } |
| 2758 |