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