1use std::collections::BTreeMap;
7use std::sync::Arc;
8use std::time::{Duration, Instant};
9
10use pagesift_api::types::{Document, Metadata, PagesiftMeta, ScrapeOptions};
11use pagesift_api::{ApiError, BoxFuture, Engine, ErrorCode};
12use pagesift_cdp::{
13 AllowListGuard, BlockResources, BrowserPool, NetworkAllowList, PoolConfig, PrivateNetworkGuard,
14 RenderOptions, RenderedPage, RequestGuard, SubRequest, Verdict,
15};
16use pagesift_net::{FetchRequest, Fetcher, FetcherConfig, Url};
17use pagesift_policy::{Policy, PolicyConfig, RequestKind, RobotsMode};
18use tokio::sync::OnceCell;
19
20tokio::task_local! {
21 static ITNA_NETWORK_BUDGET: Arc<pagesift_itna::NetworkBudget>;
22 static ITNA_COOKIE_SESSION: Option<Arc<pagesift_net::CookieSession>>;
23 static ITNA_EXPECTED_DIRECT: Option<bool>;
24 static ITNA_DEFAULT_PROXY: Option<String>;
25}
26
27pub mod agent;
28mod autoschema;
29mod cache;
30mod cpu;
31mod csv_text;
32mod egress_route;
33mod extract;
34mod feed;
35mod fetch;
36mod frames;
37mod hooked;
38mod http_extract;
39mod image_file;
40mod images;
41mod interact;
42mod office;
43mod output;
44mod parse;
45mod pdf;
46pub mod planner;
47mod render;
48mod render_stats;
49mod scraper;
50mod speculate;
51pub use autoschema::ActionSecret;
52pub use hooked::ScraperBuilder;
53pub use interact::InteractLimits;
54mod similar;
55mod structured;
56use cpu::{CONTENT_WORKSPACE, cpu_task};
57pub use cpu::{set_cpu_capacity, set_cpu_groups};
58use extract::*;
59use frames::*;
60use http_extract::*;
61use office::*;
62pub use office::{office_markdown, office_markdown_from};
63pub use output::*;
64use render::*;
65
66pub const AUTO_RENDER_MIN_CHARS: usize = 1200;
69pub const AUTO_RENDER_ARTICLE_MIN_CHARS: usize = 300;
73pub const CJK_WEIGHT: usize = 3;
74
75pub fn text_weight(s: &str) -> usize {
77 s.chars()
78 .filter(|c| !c.is_whitespace())
79 .map(|c| if is_cjk(c) { CJK_WEIGHT } else { 1 })
80 .sum()
81}
82
83fn is_cjk(c: char) -> bool {
84 matches!(c as u32,
85 0x3040..=0x30FF | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xAC00..=0xD7AF | 0xF900..=0xFAFF | 0x20000..=0x2FA1F)
91}
92
93pub fn needs_render(doc: &pagesift_content::Document) -> bool {
95 let w = text_weight(&doc.markdown);
96 if w >= AUTO_RENDER_MIN_CHARS {
97 return false;
98 }
99 let m = &doc.metadata;
100 let article = m.published_time.is_some()
101 || m.extra
102 .iter()
103 .any(|(k, v)| k == "og:type" && v.eq_ignore_ascii_case("article"));
104 !(article && w >= AUTO_RENDER_ARTICLE_MIN_CHARS)
105}
106pub const RENDER_FALLBACK_MIN_CHARS: usize = 200;
109
110#[derive(Debug, Clone)]
112pub struct EngineProbe {
113 pub engine: &'static str,
114 pub location: String,
116 pub result: Result<(), String>,
117}
118
119#[derive(Clone, Default)]
120pub struct ScraperConfig {
121 pub fetcher: FetcherConfig,
122 pub policy: PolicyConfig,
123 pub itna: bool,
125 pub browser: PoolConfig,
126 pub store: Option<pagesift_store::Store>,
128 pub llm: Option<pagesift_llm::LlmConfig>,
130 pub search: Option<Arc<dyn pagesift_search::SearchBackend>>,
132 pub egress: Vec<(String, String)>,
135 pub egress_classes: std::collections::HashMap<String, pagesift_policy::EgressClass>,
137 pub audit: Option<Arc<crate::audit::Audit>>,
139 pub hooks: pagesift_hooks::Hooks,
141 pub secrets: std::collections::BTreeMap<String, ActionSecret>,
143 pub ocr: Option<Arc<dyn pagesift_pdf::PageOcr>>,
145 pub interact: InteractLimits,
147}
148
149#[derive(Debug)]
151pub enum ScraperError {
152 Fetcher(pagesift_net::Error),
153 Llm(pagesift_llm::LlmError),
154}
155
156impl std::fmt::Display for ScraperError {
157 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158 match self {
159 Self::Fetcher(e) => write!(f, "fetcher configuration: {e}"),
160 Self::Llm(e) => write!(f, "LLM configuration: {e}"),
161 }
162 }
163}
164
165impl std::error::Error for ScraperError {
166 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
167 match self {
168 Self::Fetcher(e) => Some(e),
169 Self::Llm(e) => Some(e),
170 }
171 }
172}
173
174pub struct Scraper {
175 policy: Arc<Policy>,
176 itna: bool,
177 identities: pagesift_policy::identity_pool::IdentityPool,
180 store: Option<pagesift_store::Store>,
181 llm: Option<pagesift_llm::ChatClient>,
182 search: Option<Arc<dyn pagesift_search::SearchBackend>>,
183 ocr: Option<Arc<dyn pagesift_pdf::PageOcr>>,
184 browser_private_network: bool,
186 browser_allow: NetworkAllowList,
188 browsers: Vec<(PoolConfig, OnceCell<Option<Arc<BrowserPool>>>)>,
191 launch_failed: Vec<std::sync::Mutex<Option<Instant>>>,
193 launch_notes: Vec<std::sync::Mutex<Option<String>>>,
195 launch_broken: std::sync::atomic::AtomicBool,
197 crawl_slots: pagesift_policy::AdaptiveConcurrencyGate,
201 learner: crate::learn::HostLearner,
202 planner: planner::RenderPlanner,
204 render_stats: render_stats::RenderStats,
206 audit: Option<Arc<crate::audit::Audit>>,
207 hooks: pagesift_hooks::Hooks,
208 secrets: std::collections::BTreeMap<String, ActionSecret>,
209 pages: std::sync::OnceLock<Arc<dyn crate::PageRunner>>,
211 sessions: Arc<interact::Sessions>,
213}
214
215pub(super) enum Source<'a> {
217 Url(&'a str, RobotsMode),
218 Upload(pagesift_api::types::Upload),
219}
220
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222enum EngineChoice {
223 Http,
224 Browser,
225 Auto,
226}
227
228impl Engine for Scraper {
229 fn scrape<'a>(
230 &'a self,
231 url: &'a str,
232 opts: &'a ScrapeOptions,
233 ) -> BoxFuture<'a, Result<Document, ApiError>> {
234 Box::pin(Scraper::scrape(self, url, opts))
235 }
236
237 fn parse<'a>(
238 &'a self,
239 file: pagesift_api::types::Upload,
240 opts: &'a ScrapeOptions,
241 ) -> BoxFuture<'a, Result<Document, ApiError>> {
242 Box::pin(Scraper::parse(self, file, opts))
243 }
244
245 fn map<'a>(
246 &'a self,
247 req: &'a pagesift_api::types::MapRequest,
248 ) -> BoxFuture<'a, Result<Vec<pagesift_api::types::MapLink>, ApiError>> {
249 Box::pin(Scraper::map(self, req))
250 }
251
252 fn crawl<'a>(
253 &'a self,
254 req: &'a pagesift_api::types::CrawlRequest,
255 sink: Arc<dyn pagesift_api::CrawlSink>,
256 ) -> BoxFuture<'a, Result<(), ApiError>> {
257 Box::pin(Scraper::crawl(self, req, sink))
258 }
259
260 fn search<'a>(
261 &'a self,
262 req: &'a pagesift_api::types::SearchRequest,
263 ) -> BoxFuture<'a, Result<serde_json::Value, ApiError>> {
264 Box::pin(Scraper::search(self, req))
265 }
266
267 fn extract<'a>(
268 &'a self,
269 req: &'a pagesift_api::types::ExtractRequest,
270 ) -> BoxFuture<'a, Result<serde_json::Value, ApiError>> {
271 Box::pin(Scraper::extract(self, req))
272 }
273
274 fn supports_interact(&self) -> bool {
275 self.interact_available()
276 }
277
278 fn supports_actions(&self) -> bool {
280 self.interact_available()
281 }
282
283 fn actions_unavailable(&self) -> &'static str {
284 "actions need Chrome: no Chrome or Chromium was found on this machine (run `pagesift doctor`)"
285 }
286
287 fn scrape_session<'a>(
288 &'a self,
289 url: &'a str,
290 opts: &'a ScrapeOptions,
291 keep: bool,
292 owner: Option<&'a str>,
293 ) -> BoxFuture<'a, Result<Document, ApiError>> {
294 Box::pin(Scraper::scrape_session(self, url, opts, keep, owner))
295 }
296
297 fn observe<'a>(
298 &'a self,
299 url: &'a str,
300 instruction: &'a str,
301 ) -> BoxFuture<'a, Result<pagesift_api::types::Observed, ApiError>> {
302 Box::pin(async move {
303 let (found, used) = Scraper::observe(self, url, instruction).await?;
304 let usage = format!("llm_usage: {} calls, {} tokens", used.calls, used.tokens);
305 Ok((found, vec![usage]))
306 })
307 }
308
309 fn find_similar<'a>(
310 &'a self,
311 url: &'a str,
312 selector: &'a str,
313 opts: &'a ScrapeOptions,
314 ) -> BoxFuture<'a, Result<pagesift_api::types::SimilarData, ApiError>> {
315 Box::pin(Scraper::find_similar(self, url, selector, opts))
316 }
317
318 fn interact<'a>(
319 &'a self,
320 id: &'a str,
321 req: &'a pagesift_api::types::InteractRequest,
322 owner: Option<&'a str>,
323 ) -> BoxFuture<'a, Result<pagesift_api::types::InteractResponse, ApiError>> {
324 Box::pin(Scraper::interact(self, id, req, owner))
325 }
326
327 fn stop_interact<'a>(
328 &'a self,
329 id: &'a str,
330 owner: Option<&'a str>,
331 ) -> BoxFuture<'a, Result<pagesift_api::types::InteractStopped, ApiError>> {
332 Box::pin(Scraper::stop_interact(self, id, owner))
333 }
334
335 fn agent_check(&self, req: &pagesift_api::types::AgentRequest) -> Result<(), ApiError> {
336 agent::check(self.llm.is_some(), self.search.is_some(), req)
337 }
338
339 fn agent<'a>(
340 &'a self,
341 req: &'a pagesift_api::types::AgentRequest,
342 sink: Arc<dyn pagesift_api::AgentSink>,
343 ) -> BoxFuture<'a, pagesift_api::types::AgentOutcome> {
344 Box::pin(async move {
345 match &self.llm {
346 Some(llm) => agent::run(self, llm, self.search.is_some(), req, sink.as_ref()).await,
347 None => pagesift_api::types::AgentOutcome {
348 finish_reason: "error".into(),
349 error: Some(pagesift_api::types::AgentFailure::from(
350 &ApiError::unsupported("agent needs an LLM: set [llm] in pagesift.toml"),
351 )),
352 ..Default::default()
353 },
354 }
355 })
356 }
357
358 fn admitted_concurrency(&self) -> Option<usize> {
360 Some(self.concurrency())
361 }
362
363 fn supported_formats(&self) -> &'static [&'static str] {
364 match (self.llm.is_some(), self.store.is_some()) {
365 (true, true) => &[
366 "markdown",
367 "html",
368 "rawHtml",
369 "links",
370 "images",
371 "extract",
372 "summary",
373 "json",
374 "changeTracking",
375 ],
376 (true, false) => &[
377 "markdown", "html", "rawHtml", "links", "images", "extract", "summary", "json",
378 ],
379 (false, true) => &[
380 "markdown",
381 "html",
382 "rawHtml",
383 "links",
384 "images",
385 "extract",
386 "changeTracking",
387 ],
388 (false, false) => &["markdown", "html", "rawHtml", "links", "images", "extract"],
389 }
390 }
391}
392
393struct SchemeGuard;
395
396impl RequestGuard for SchemeGuard {
397 fn check<'a>(&'a self, req: &'a SubRequest) -> pagesift_cdp::BoxFuture<'a, Verdict> {
398 let ok = Url::parse(&req.url)
399 .is_ok_and(|u| matches!(u.scheme(), "http" | "https" | "data" | "blob" | "about"));
400 Box::pin(async move {
401 if ok {
402 Verdict::Allow
403 } else {
404 Verdict::Block("scheme not allowed".into())
405 }
406 })
407 }
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413
414 fn content(md: &str, published: bool, og_article: bool) -> pagesift_content::Document {
415 let mut d = pagesift_content::process("<p>x</p>", &Default::default());
416 d.markdown = md.to_string();
417 d.metadata.published_time = published.then(|| "2026-10-21T00:00:00Z".into());
418 if og_article {
419 d.metadata.extra.push(("og:type".into(), "article".into()));
420 }
421 d
422 }
423
424 #[test]
425 fn static_learning_cannot_suppress_client_code() {
426 for html in [
427 "<script>hydrate()</script>",
428 "<script src='/app.js'></script>",
429 "<SCRIPT TYPE='module' src='/view.js'></SCRIPT>",
430 "<body onload='hydrate()'>",
431 "<button onclick='hydrate()'>Open</button>",
432 ] {
433 assert!(has_client_code(html), "{html}");
434 }
435 for html in [
436 "<article><p>Short but complete.</p></article>",
437 "<script type='application/ld+json'>{}</script>",
438 "<script type='APPLICATION/JSON; charset=utf-8'>{}</script>",
439 "<script type='text/plain'>inert sample</script>",
440 ] {
441 assert!(!has_client_code(html), "{html}");
442 }
443 }
444
445 #[test]
446 fn render_rule_weights_cjk_and_trusts_short_articles() {
447 assert_eq!(text_weight("ab c\n"), 3);
448 assert_eq!(text_weight("日本語のニュース"), 8 * CJK_WEIGHT);
449 assert!(!needs_render(&content(&"字".repeat(500), false, false)));
451 assert!(needs_render(&content(&"a".repeat(500), false, false)));
452 assert!(!needs_render(&content(&"a".repeat(400), true, false)));
454 assert!(!needs_render(&content(&"a".repeat(400), false, true)));
455 assert!(needs_render(&content(&"a".repeat(100), true, true)));
456 }
457
458 #[test]
459 fn render_errors_are_classified() {
460 use pagesift_cdp::Error as E;
461 for (e, code) in [
462 (
463 E::Action {
464 index: 0,
465 message: "no element".into(),
466 },
467 ErrorCode::InvalidRequest,
468 ),
469 (E::InvalidOptions("x".into()), ErrorCode::InvalidRequest),
470 (E::ExecuteJavascriptDisabled, ErrorCode::UnsupportedOption),
471 (E::Timeout, ErrorCode::Timeout),
472 (E::Busy, ErrorCode::Busy),
473 (
474 E::Navigation("net::ERR_NAME_NOT_RESOLVED".into()),
475 ErrorCode::DnsFailure,
476 ),
477 (
478 E::Navigation("net::ERR_CONNECTION_RESET".into()),
479 ErrorCode::NetworkError,
480 ),
481 (
482 E::Navigation("net::ERR_CERT_DATE_INVALID".into()),
483 ErrorCode::TlsCertExpired,
484 ),
485 (
486 E::Navigation("net::ERR_CERT_COMMON_NAME_INVALID".into()),
487 ErrorCode::TlsHostnameMismatch,
488 ),
489 (
490 E::Navigation("net::ERR_CERT_AUTHORITY_INVALID".into()),
491 ErrorCode::TlsUntrustedRoot,
492 ),
493 (
494 E::Navigation("net::ERR_CERT_REVOKED".into()),
495 ErrorCode::TlsError,
496 ),
497 (E::ConnectionClosed, ErrorCode::UpstreamError),
498 ] {
499 assert_eq!(render_error_code(&e), code, "{e}");
500 }
501 }
502
503 #[test]
504 fn finds_only_visible_same_origin_and_srcdoc_iframes() {
505 let base = Url::parse("https://a.test/page").unwrap();
506 let html = r#"<body>
507 <iframe src="https://www.googletagmanager.com/ns.html"></iframe>
508 <iframe src="/pixel" style="display: none"></iframe>
509 <iframe src="/hidden" aria-hidden="true"></iframe>
510 <iframe src="/tiny" width="1" height="1"></iframe>
511 <iframe src="about:blank"></iframe>
512 <iframe src="/comments?id=1&x=2" height="160"></iframe>
513 <iframe srcdoc="<p>inline</p>"></iframe>
514 <iframe srcdoc="<p>x</p>" style="visibility:hidden"></iframe>
515 </body>"#;
516 let frames = content_iframes(html, &base);
517 assert_eq!(frames.len(), 2, "{frames:?}");
518 assert_eq!(frames[0].0, "/comments?id=1&x=2");
519 assert_eq!(
520 frames[0].1.as_ref().map(Url::as_str),
521 Some("https://a.test/comments?id=1&x=2")
522 );
523 assert_eq!(frames[1], ("<p>inline</p>".to_string(), None));
524 assert!(content_iframes("<p>no frames</p>", &base).is_empty());
525 }
526
527 #[test]
528 fn replaces_the_matching_iframe_element() {
529 let mut html = r#"<p>a</p><IFRAME src="/x" hidden></IFRAME><iframe src="/x">fallback</iframe><p>b</p>"#
530 .to_string();
531 assert!(replace_iframe(&mut html, "<div>X</div>", |el| {
532 !hidden_frame(el) && src_is(el, "/x")
533 }));
534 assert_eq!(
535 html,
536 r#"<p>a</p><IFRAME src="/x" hidden></IFRAME><div>X</div><p>b</p>"#
537 );
538 assert!(!replace_iframe(&mut html, "", |el| src_is(el, "/missing")));
539 }
540
541 #[test]
542 fn takes_the_body_of_an_iframe_document() {
543 assert_eq!(
544 body_inner("<html><head><title>t</title></head><BODY class=x><p>hi</p></body></html>"),
545 "<p>hi</p>"
546 );
547 assert_eq!(body_inner("<p>fragment</p>"), "<p>fragment</p>");
548 }
549
550 #[test]
551 fn meta_keys_follow_firecrawl_style() {
552 assert_eq!(pagesift_sink::meta::key("og:image"), "ogImage");
553 assert_eq!(pagesift_sink::meta::key("og:site_name"), "ogSiteName");
554 assert_eq!(
555 pagesift_sink::meta::key("article:published_time"),
556 "articlePublishedTime"
557 );
558 assert_eq!(pagesift_sink::meta::key("dc.title"), "dcTitle");
559 }
560}