/** * LLM Browser SDK * * Programmatic SDK for using the LLM Browser as a library. * This allows applications to integrate intelligent browsing capabilities * directly without going through the MCP server. * * Features: * - SmartBrowser: Intelligent browsing with automatic learning * - TieredFetcher: Fast content fetching (intelligence → lightweight → playwright) * - ProceduralMemory: Skill-based learning for browsing patterns * - ContentExtractor: HTML to markdown/text extraction * - SessionManager: Session persistence across requests * * Usage: * ```typescript * import { createLLMBrowser, SmartBrowser } from 'llm-browser/sdk'; * * const browser = await createLLMBrowser(); * const result = await browser.browse('https://example.com'); * await browser.cleanup(); * ``` */ import { BrowserManager, type BrowserConfig } from './core/browser-manager.js'; import { ContentExtractor } from './utils/content-extractor.js'; import { ApiAnalyzer } from './core/api-analyzer.js'; import { SessionManager } from './core/session-manager.js'; import { SmartBrowser, type SmartBrowseOptions, type SmartBrowseResult } from './core/smart-browser.js'; import { TieredFetcher, type TieredFetchOptions, type TieredFetchResult } from './core/tiered-fetcher.js'; import { ProceduralMemory } from './core/procedural-memory.js'; import { LearningEngine } from './core/learning-engine.js'; import type { SkillMatch } from './types/index.js'; export type { SmartBrowseOptions, SmartBrowseResult } from './core/smart-browser.js'; export type { TieredFetchOptions, TieredFetchResult, RenderTier } from './core/tiered-fetcher.js'; export type { BrowserConfig } from './core/browser-manager.js'; export type { BrowserPoolConfig, PooledSession, PoolStats } from './core/browser-pool.js'; export { BrowserPool, getDefaultPool, resetDefaultPool } from './core/browser-pool.js'; export type { NetworkRequest, ConsoleMessage, ApiPattern, EnhancedApiPattern, BrowseResult, BrowseOptions, BrowsingAction, BrowsingSkill, BrowsingTrajectory, PageContext, SkillMatch, BrowseProgressStage, BrowseProgressEvent, OnProgressCallback, } from './types/index.js'; export { createProgressEvent, estimateProgressPercent, } from './types/progress.js'; export { SmartBrowser, TieredFetcher, ProceduralMemory, LearningEngine, ContentExtractor, BrowserManager, SessionManager, ApiAnalyzer, }; export type { IdentityProvider, SSOFlowInfo, DomainSSORelationship, SSODetectorOptions, } from './core/sso-flow-detector.js'; export type { SessionShareResult, SessionCandidate, SessionSharingOptions, SessionSharingConfig, } from './core/session-sharing.js'; export type { DomainGroup, CorrelationStats, CorrelatorState, } from './core/domain-correlator.js'; export { SSOFlowDetector, KNOWN_PROVIDERS } from './core/sso-flow-detector.js'; export { SessionSharingService } from './core/session-sharing.js'; export { DomainCorrelator } from './core/domain-correlator.js'; /** * General-purpose research engine that combines web search with intelligent * browsing to answer research questions with citations. * * This is the core abstraction that makes Unbrowser a "research engine" * rather than just a browser automation tool. * * @example * ```typescript * import { research, ResearchEngine } from 'llm-browser/sdk'; * * // Simple usage with default engine * const result = await research({ * scope: "current IPREM rates in Spain for 2025", * outputSchema: { * type: "object", * properties: { * monthly: { type: "number", description: "Monthly IPREM in EUR" }, * annual14: { type: "number", description: "Annual IPREM (14 payments)" } * } * }, * strategy: "authoritative" * }); * * console.log(result.data); // { monthly: 600, annual14: 8400 } * console.log(result.confidence); // 0.85 * console.log(result.sources); // [{ url: "boe.es/...", ... }] * * // Advanced usage with custom engine * const engine = new ResearchEngine(); * await engine.initialize({ braveApiKey: process.env.BRAVE_API_KEY }); * const result = await engine.research({ scope: "..." }); * await engine.close(); * ``` */ export { ResearchEngine, BraveSearchProvider, research, getResearchEngine, } from './core/research-engine.js'; export type { ResearchRequest, ResearchResult as ResearchEngineResult, ResearchSource, JsonSchema, JsonSchemaProperty, SearchProvider, SearchOptions, SearchResult, VerificationResult as ResearchVerificationResult, ChangeDetection, } from './core/research-engine.js'; /** * @deprecated Use the general-purpose ResearchEngine instead. * This indicator-specific API will be removed in a future version. */ export { researchIndicator, researchIndicatorsBatch, getIndicatorConfig, INDICATOR_CONFIGS, } from './core/indicator-research.js'; /** * @deprecated Use ResearchRequest/ResearchResult from research-engine.js instead. */ export type { IndicatorType, ExtractionHints, IndicatorResearchRequest, ExtractedIndicator, IndicatorChange, SourceInfo, IndicatorResearchResult, } from './core/indicator-research.js'; export interface LLMBrowserConfig { /** Directory for storing session data (default: './sessions') */ sessionsDir?: string; /** Path to learning engine JSON file (default: './enhanced-knowledge-base.json') */ learningEnginePath?: string; /** Browser configuration */ browser?: BrowserConfig; /** Enable procedural memory / skill learning (default: true) */ enableProceduralMemory?: boolean; /** Enable content learning (default: true) */ enableLearning?: boolean; } /** * LLM Browser SDK Client * * High-level interface for intelligent web browsing with automatic learning. */ export declare class LLMBrowserClient { private browserManager; private contentExtractor; private apiAnalyzer; private sessionManager; private learningEngine; private smartBrowser; private initialized; private config; constructor(config?: LLMBrowserConfig); /** * Initialize the browser and learning systems */ initialize(): Promise; /** * Ensure the client is initialized */ private ensureInitialized; /** * Browse a URL with intelligent learning and optimization * * This is the main entry point for browsing. It automatically: * - Uses learned selectors for reliable content extraction * - Applies tiered rendering (fast static → lightweight → full browser) * - Validates responses against learned patterns * - Learns from successes and failures * - Applies cross-domain patterns */ browse(url: string, options?: SmartBrowseOptions): Promise; /** * Preview what would happen when browsing a URL without executing */ previewBrowse(url: string, options?: SmartBrowseOptions): Promise; /** * Fetch content using tiered rendering (fast path) * * Tries intelligence tier first (framework extraction, APIs), * then lightweight (HTTP + JS), then full browser. */ fetch(url: string, options?: TieredFetchOptions): Promise; /** * Get domain intelligence summary */ getDomainIntelligence(domain: string): Promise<{ knownPatterns: number; selectorChains: number; validators: number; paginationPatterns: number; recentFailures: number; successRate: number; domainGroup: string | null; recommendedWaitStrategy: string; shouldUseSession: boolean; }>; /** * Find applicable browsing skills for a URL */ findApplicableSkills(url: string, topK?: number): SkillMatch[]; /** * Get procedural memory statistics */ getProceduralMemoryStats(): { totalSkills: number; totalTrajectories: number; skillsByDomain: Record; avgSuccessRate: number; mostUsedSkills: Array<{ name: string; uses: number; }>; }; /** * Get learning statistics */ getLearningStats(): { totalDomains: number; totalApiPatterns: number; bypassablePatterns: number; totalSelectors: number; totalValidators: number; domainGroups: string[]; recentLearningEvents: Array<{ type: string; domain: string; timestamp: number; }>; }; /** * Get tiered fetcher statistics */ getTieredFetcherStats(): { totalDomains: number; byTier: Record; avgResponseTimes: Record; playwrightAvailable: boolean; }; /** * Access the underlying SmartBrowser for advanced operations */ getSmartBrowser(): SmartBrowser; /** * Access the procedural memory system */ getProceduralMemory(): ProceduralMemory; /** * Access the learning engine */ getLearningEngine(): LearningEngine; /** * Access the tiered fetcher */ getTieredFetcher(): TieredFetcher; /** * Access the content extractor */ getContentExtractor(): ContentExtractor; /** * Detect SSO flow from a URL and learn domain relationships * Call this when navigating to capture OAuth/SAML/OIDC flows * * @param url - The URL to check for SSO flow * @param initiatingDomain - The domain that initiated the SSO flow * @returns SSO flow info if detected, null otherwise * * @example * ```typescript * // Check if a URL is an SSO redirect * const flow = browser.detectSSOFlow( * 'https://accounts.google.com/o/oauth2/auth?client_id=...', * 'myapp.com' * ); * if (flow) { * console.log(`Detected ${flow.provider.name} SSO for ${flow.initiatingDomain}`); * } * ``` */ detectSSOFlow(url: string, initiatingDomain?: string): import('./core/sso-flow-detector.js').SSOFlowInfo | null; /** * Find and share a session from a related domain that uses the same identity provider * * @param targetDomain - The domain to get a session for * @param options - Session sharing options * @returns Result including success status and source domain * * @example * ```typescript * // Try to reuse an existing session from a related domain * const result = await browser.shareSessionFromRelatedDomain('app2.com'); * if (result.success) { * console.log(`Shared session from ${result.sourceDomain} via ${result.providerId}`); * } * ``` */ shareSessionFromRelatedDomain(targetDomain: string, options?: { sessionProfile?: string; minConfidence?: number; }): Promise<{ success: boolean; sourceDomain?: string; providerId?: string; }>; /** * Get domains that share the same identity provider with the given domain * * @param domain - The domain to find related domains for * @param minConfidence - Minimum confidence threshold (0-1) * @returns Array of related domain names * * @example * ```typescript * // Find domains using the same SSO provider * const related = browser.getRelatedDomains('app1.com'); * console.log(`Related domains: ${related.join(', ')}`); * ``` */ getRelatedDomains(domain: string, minConfidence?: number): string[]; /** * Get domain groups organized by identity provider * * @param minConfidence - Minimum confidence threshold (0-1) * @returns Array of domain groups * * @example * ```typescript * // See which domains share SSO providers * const groups = browser.getDomainGroups(); * for (const group of groups) { * console.log(`${group.providerName}: ${group.domains.join(', ')}`); * } * ``` */ getDomainGroups(minConfidence?: number): import('./core/domain-correlator.js').DomainGroup[]; /** * Clear cached content * * @param domain - Optional domain to clear cache for (e.g., 'example.com'). * If not provided, clears all cached content. * @returns Number of cache entries cleared * * @example * ```typescript * // Clear all cache * const cleared = browser.clearCache(); * console.log(`Cleared ${cleared} entries`); * * // Clear cache for a specific domain * const domainCleared = browser.clearCache('example.com'); * console.log(`Cleared ${domainCleared} entries for example.com`); * ``` */ clearCache(domain?: string): number; /** * Get cache statistics * * @returns Combined cache statistics including: * - totalEntries: Total number of cached items * - pageCache: Page/HTML content cache stats * - apiCache: API response cache stats * - domains: List of domains with cached content * * @example * ```typescript * const stats = browser.getCacheStats(); * console.log(`Cache has ${stats.totalEntries} entries across ${stats.domains.length} domains`); * console.log(`Page cache: ${stats.pageCache.size} entries`); * console.log(`API cache: ${stats.apiCache.size} entries`); * ``` */ getCacheStats(): { totalEntries: number; pageCache: { size: number; maxEntries: number; ttlMs: number; oldestEntry: number | null; newestEntry: number | null; }; apiCache: { size: number; maxEntries: number; ttlMs: number; oldestEntry: number | null; newestEntry: number | null; }; domains: string[]; }; /** * Clean up browser resources */ cleanup(): Promise; /** * Check if Playwright is available */ static isPlaywrightAvailable(): boolean; } /** * Create and initialize an LLM Browser client * * @param config - Configuration options * @returns Initialized LLM Browser client * * @example * ```typescript * const browser = await createLLMBrowser(); * const result = await browser.browse('https://example.com'); * console.log(result.content.markdown); * await browser.cleanup(); * ``` */ export declare function createLLMBrowser(config?: LLMBrowserConfig): Promise; /** * Create a simple content fetcher without full browser capabilities * * Uses tiered fetching for fast content extraction. * * @example * ```typescript * const fetcher = createContentFetcher(); * const content = await fetcher.fetch('https://example.com'); * console.log(content.text); * ``` */ export declare function createContentFetcher(): { fetch: (url: string, options?: TieredFetchOptions) => Promise; extract: (html: string, url: string) => { markdown: string; text: string; title: string; }; }; import type { VerifyOptions, VerificationCheck, VerificationAssertion } from './types/verification.js'; export { WORKFLOW_TEMPLATES, COUNTRY_PORTALS, VISA_TYPE_PATHS, VISA_RESEARCH_TEMPLATE, DOCUMENT_EXTRACTION_TEMPLATE, FEE_TRACKING_TEMPLATE, CROSS_COUNTRY_COMPARISON_TEMPLATE, TAX_OBLIGATIONS_TEMPLATE, resolveUrlTemplate, prepareVariables, validateVariables, extractFindings, buildWorkflowSummary, listTemplates, getTemplate, } from './core/workflow-templates.js'; export type { WorkflowTemplate, WorkflowTemplateStep, WorkflowTemplateResult, WorkflowTemplateStepResult, WorkflowTemplateSummary, WorkflowFinding, } from './core/workflow-templates.js'; export { GOVERNMENT_SKILL_PACK, SPAIN_SKILLS, PORTUGAL_SKILLS, GERMANY_SKILLS, getSkillsForCountry, getSkillById, getSkillsByCategory, getSkillsForDomain, searchSkills, listGovernmentSkills, skillToPattern, exportSkillPack, importSkillPack, getSkillPackSummary, } from './core/government-skill-pack.js'; export type { GovernmentSkill, GovernmentSkillStep, GovernmentServiceCategory, GovernmentSkillPack, } from './core/government-skill-pack.js'; /** * Dynamic refresh scheduler for intelligent content update scheduling. * Replaces fixed staleness thresholds with learned update patterns. * * @example * ```typescript * import { createDynamicRefreshScheduler, CONTENT_TYPE_PRESETS } from 'llm-browser/sdk'; * * const scheduler = createDynamicRefreshScheduler(); * * // Record content observations * scheduler.recordContentCheck( * 'https://exteriores.gob.es/visa-requirements', * 'abc123hash', * true, // content changed * 'requirements' * ); * * // Get optimal refresh schedule * const schedule = scheduler.getRefreshSchedule(url); * console.log(schedule.recommendedRefreshHours); // e.g., 168 (weekly) * console.log(schedule.nextCheckAt); // timestamp when to check next * console.log(schedule.isLearned); // true if based on observed patterns * * // Get URLs needing refresh * const needsRefresh = scheduler.getUrlsNeedingRefresh(); * for (const { url, recommendation } of needsRefresh) { * console.log(`${url}: ${recommendation.reason}`); * } * ``` */ export { DynamicRefreshScheduler, createDynamicRefreshScheduler, CONTENT_TYPE_PRESETS, KNOWN_DOMAIN_PATTERNS, } from './core/dynamic-refresh-scheduler.js'; export type { GovernmentContentType, ContentTypePreset, DomainPattern, RefreshSchedule, DynamicRefreshSchedulerConfig, } from './core/dynamic-refresh-scheduler.js'; export { ContentChangePredictor } from './core/content-change-predictor.js'; export type { ContentChangePattern, ContentChangeAnalysis, PollRecommendation, ContentChangePredictionConfig, ChangePatternType, ChangeObservation, TemporalPattern, ChangeFrequencyStats, ChangePrediction, } from './types/content-change.js'; export { DEFAULT_CHANGE_PREDICTION_CONFIG } from './types/content-change.js'; export { StructuredGovDataExtractor, createGovDataExtractor, extractGovData, validateGovData, type GovContentType, type MonetaryValue, type TimelineValue, type DocumentRequirement, type EligibilityRequirement, type FeeEntry, type ProcessingStep, type ContactInfo, type AppointmentInfo, type FormInfo, type StructuredGovData, type ExtractionOptions, type ValidationResult, type ValidationError, type ValidationWarning, } from './core/structured-gov-data-extractor.js'; /** * Appointment availability detector for government and service portals. * Detects booking systems, extracts available time slots, and provides * monitoring suggestions for slot openings. * * @example * ```typescript * import { * detectAppointmentAvailability, * hasAppointmentSystem, * getAvailabilityStatus * } from 'llm-browser/sdk'; * * // Check if page has appointment system * if (hasAppointmentSystem(html, 'es')) { * const result = detectAppointmentAvailability(html, { * language: 'es', * url: 'https://sede.gob.es/cita-previa' * }); * * console.log(`Detected: ${result.detected}`); * console.log(`Availability: ${result.availability}`); * console.log(`Systems: ${result.systems.map(s => s.name).join(', ')}`); * console.log(`Slots: ${result.slots.length}`); * * // Get monitoring suggestions * for (const suggestion of result.monitoringSuggestions) { * console.log(`Check every ${suggestion.checkIntervalMinutes} minutes`); * console.log(`Reason: ${suggestion.reason}`); * } * } * * // Quick availability check * const status = getAvailabilityStatus(html, 'es'); * if (status === 'unavailable') { * console.log('No slots available - set up monitoring'); * } * ``` */ export { AppointmentAvailabilityDetector, createAvailabilityDetector, detectAppointmentAvailability, hasAppointmentSystem, getAvailabilityStatus, type AppointmentSystemType, type SlotAvailability, type TimeSlot, type BookingSystem, type AppointmentAvailabilityResult, type MonitoringSuggestion, type AvailabilityDetectionOptions, } from './core/appointment-availability-detector.js'; /** * Field-level change tracker for government content monitoring. * Tracks specific field changes with severity classification and * structured before/after diffs. * * @example * ```typescript * import { * trackFieldChanges, * hasBreakingChanges, * getBreakingChanges * } from 'llm-browser/sdk'; * * // Track changes between two data snapshots * const result = trackFieldChanges(oldData, newData, { * url: 'https://gov.example.com/visa', * language: 'es', * }); * * // Check for breaking changes * if (result.breakingChanges.length > 0) { * console.log('Breaking changes detected:'); * for (const change of result.breakingChanges) { * console.log(` - ${change.description}`); * console.log(` Impact: ${change.impact}`); * } * } * * // Quick check for breaking changes * if (hasBreakingChanges(oldData, newData)) { * console.log('Action required!'); * } * * // Get all breaking changes * const breaking = getBreakingChanges(oldData, newData); * for (const change of breaking) { * console.log(`${change.fieldName}: ${change.oldValueFormatted} -> ${change.newValueFormatted}`); * } * ``` */ export { FieldLevelChangeTracker, createFieldLevelChangeTracker, getFieldLevelChangeTracker, trackFieldChanges, getBreakingChanges, hasBreakingChanges, type ChangeSeverity, type FieldCategory, type ChangeType, type FieldChange, type ChangeTrackingResult, type TrackingOptions, type ChangeHistoryRecord, type FieldLevelChangeTrackerConfig, } from './core/field-level-change-tracker.js'; /** * Cross-source verifier for comparing data across multiple sources. * Detects contradictions and provides confidence-scored verified facts. * * @example * ```typescript * import { * verifySources, * hasContradictions, * getHighConfidenceFacts * } from 'llm-browser/sdk'; * * // Define sources to verify * const sources = [ * { url: 'https://gov.example.com/visa', data: { fee: 100 } }, * { url: 'https://embassy.example.com/visa', data: { fee: 100 } }, * { url: 'https://blog.example.com/visa', data: { fee: 150 } }, * ]; * * // Verify data from multiple sources * const result = verifySources(sources); * * // Check for contradictions * if (result.hasContradictions) { * for (const c of result.contradictions) { * console.log(`${c.field}: ${c.explanation}`); * console.log(`Recommended: ${c.recommendedValue}`); * } * } * * // Get verified facts * for (const fact of result.verifiedFacts) { * console.log(`${fact.field}: ${fact.value}`); * console.log(` Agreement: ${fact.agreementLevel}`); * console.log(` Confidence: ${fact.confidence}`); * } * * // Quick checks * if (hasContradictions(sources)) { * console.log('Sources disagree - verify manually'); * } * * // Get only high-confidence facts * const reliable = getHighConfidenceFacts(sources); * ``` */ export { CrossSourceVerifier, createCrossSourceVerifier, getCrossSourceVerifier, verifySources, hasContradictions, getContradictions, getHighConfidenceFacts, type SourceCredibility, type AgreementLevel, type ConfidenceLevel, type VerificationSource, type Contradiction, type VerifiedFact, type VerificationResult as CrossSourceVerificationResult, type VerificationOptions, type VerificationHistoryRecord, type CrossSourceVerifierConfig, } from './core/cross-source-verifier.js'; /** * Research topic categories with associated verification presets */ export type ResearchTopic = 'government_portal' | 'legal_document' | 'visa_immigration' | 'tax_finance' | 'official_registry' | 'general_research'; /** * Pre-built verification checks for government content validation. * These can be composed into custom verification presets. * * @example * ```typescript * import { VERIFICATION_CHECKS } from 'llm-browser/sdk'; * * const customPreset = { * checks: [ * VERIFICATION_CHECKS.hasFees, * VERIFICATION_CHECKS.hasTimeline, * VERIFICATION_CHECKS.excludeErrorPages, * ] * }; * ``` */ export declare const VERIFICATION_CHECKS: { /** * Checks for presence of fee-related content. * Matches common fee patterns in multiple currencies. */ readonly hasFees: { type: "content"; assertion: { fieldMatches: { content: RegExp; }; }; severity: "warning"; retryable: false; }; /** * Validates that fee amounts are reasonable (between 0 and 10,000). */ readonly feeAmountReasonable: { type: "content"; assertion: { fieldMatches: { content: RegExp; }; }; severity: "warning"; retryable: false; }; /** * Checks for presence of timeline/duration information. * Matches patterns like "2-3 weeks", "30 days", "3 meses". */ readonly hasTimeline: { type: "content"; assertion: { fieldMatches: { content: RegExp; }; }; severity: "warning"; retryable: false; }; /** * Checks for deadline or due date information. */ readonly hasDeadline: { type: "content"; assertion: { fieldMatches: { content: RegExp; }; }; severity: "warning"; retryable: false; }; /** * Checks for required documents list. */ readonly hasRequiredDocuments: { type: "content"; assertion: { fieldMatches: { content: RegExp; }; }; severity: "warning"; retryable: false; }; /** * Checks for passport/ID requirements. */ readonly hasIdentityRequirements: { type: "content"; assertion: { fieldMatches: { content: RegExp; }; }; severity: "warning"; retryable: false; }; /** * Checks for article/section numbering typical in legal documents. */ readonly hasLegalStructure: { type: "content"; assertion: { fieldMatches: { content: RegExp; }; }; severity: "warning"; retryable: false; }; /** * Checks for effective date in legal documents. */ readonly hasEffectiveDate: { type: "content"; assertion: { fieldMatches: { content: RegExp; }; }; severity: "warning"; retryable: false; }; /** * Checks for tax rate information. */ readonly hasTaxRates: { type: "content"; assertion: { fieldMatches: { content: RegExp; }; }; severity: "warning"; retryable: false; }; /** * Checks for tax filing deadline information. */ readonly hasTaxDeadlines: { type: "content"; assertion: { fieldMatches: { content: RegExp; }; }; severity: "warning"; retryable: false; }; /** * Excludes common error page patterns. */ readonly excludeErrorPages: { type: "content"; assertion: { excludesText: string; }; severity: "critical"; retryable: true; }; /** * Excludes "page not found" variations. */ readonly excludePageNotFound: { type: "content"; assertion: { excludesText: string; }; severity: "critical"; retryable: true; }; /** * Excludes access denied pages. */ readonly excludeAccessDenied: { type: "content"; assertion: { excludesText: string; }; severity: "critical"; retryable: true; }; /** * Excludes service unavailable pages. */ readonly excludeServiceUnavailable: { type: "content"; assertion: { excludesText: string; }; severity: "critical"; retryable: true; }; /** * Excludes session expired pages. */ readonly excludeSessionExpired: { type: "content"; assertion: { excludesText: string; }; severity: "critical"; retryable: true; }; /** * Checks for email contact information. */ readonly hasEmailContact: { type: "content"; assertion: { fieldMatches: { content: RegExp; }; }; severity: "warning"; retryable: false; }; /** * Checks for phone contact information. */ readonly hasPhoneContact: { type: "content"; assertion: { fieldMatches: { content: RegExp; }; }; severity: "warning"; retryable: false; }; /** * Requires at least 200 characters of content. */ readonly minLength200: { type: "content"; assertion: { minLength: number; }; severity: "error"; retryable: true; }; /** * Requires at least 500 characters of content. */ readonly minLength500: { type: "content"; assertion: { minLength: number; }; severity: "error"; retryable: true; }; /** * Requires at least 1000 characters of content. */ readonly minLength1000: { type: "content"; assertion: { minLength: number; }; severity: "error"; retryable: true; }; }; /** * Create a custom verification check with the specified assertion. * * @param assertion - The verification assertion to apply * @param severity - Check severity (default: 'warning') * @param retryable - Whether failures can be retried (default: false) * @returns A verification check object * * @example * ```typescript * const customCheck = createVerificationCheck( * { fieldExists: ['visa_type', 'processing_time'] }, * 'error', * true * ); * ``` */ export declare function createVerificationCheck(assertion: VerificationAssertion, severity?: 'warning' | 'error' | 'critical', retryable?: boolean): VerificationCheck; /** * Compose multiple verification checks into a single array. * Useful for building custom verification presets. * * @param checks - Verification checks to compose * @returns Array of verification checks * * @example * ```typescript * const visaChecks = composeChecks( * VERIFICATION_CHECKS.hasFees, * VERIFICATION_CHECKS.hasTimeline, * VERIFICATION_CHECKS.hasRequiredDocuments, * VERIFICATION_CHECKS.excludeErrorPages, * VERIFICATION_CHECKS.excludePageNotFound * ); * ``` */ export declare function composeChecks(...checks: VerificationCheck[]): VerificationCheck[]; /** * Type definition for verification preset configuration. * Used by RESEARCH_VERIFICATION_PRESETS and custom presets. */ export interface VerificationPreset { /** Human-readable description of this preset */ description: string; /** Expected fields to check for (legacy, used by buildVerificationChecks) */ expectedFields: string[]; /** Text patterns that should NOT appear in content (legacy, used by buildVerificationChecks) */ excludePatterns: string[]; /** Minimum content length required */ minContentLength: number; /** Verification options to apply */ verifyOptions: Partial; /** * Pre-built verification checks to include (INT-004). * These are applied in addition to checks built from expectedFields/excludePatterns. * Use VERIFICATION_CHECKS constants or create custom checks. */ checks?: VerificationCheck[]; } export declare const RESEARCH_VERIFICATION_PRESETS: Record; /** * Session profile mappings for government portals. * Maps domain patterns to session profile names for SSO reuse. */ export declare const GOVERNMENT_SESSION_PROFILES: Record; /** * Configuration options for the Research Browser */ export interface ResearchConfig extends LLMBrowserConfig { /** * Default research topic for verification presets. * Can be overridden per-request. * @default 'general_research' */ defaultTopic?: ResearchTopic; /** * Enable automatic pagination following for legal documents. * @default true */ followPagination?: boolean; /** * Maximum pages to follow when pagination is enabled. * @default 10 */ maxPages?: number; /** * Enable session persistence for government portals. * When enabled, sessions are automatically saved and reused. * @default true */ persistSessions?: boolean; /** * Enable SSO detection and cross-domain session sharing. * @default true */ enableSSOSharing?: boolean; /** * Minimum confidence threshold for session sharing. * @default 0.6 */ ssoMinConfidence?: number; /** * Enable API discovery before browser fallback. * When APIs are found, they're used for faster data extraction. * @default true */ preferApiDiscovery?: boolean; /** * Custom session profiles for domains not in the default list. * Merged with GOVERNMENT_SESSION_PROFILES. */ customSessionProfiles?: Record; /** * Custom verification presets for topics not in the default list. * Merged with RESEARCH_VERIFICATION_PRESETS. */ customVerificationPresets?: Record; } /** * Research-specific browse options */ export interface ResearchBrowseOptions extends SmartBrowseOptions { /** * Research topic for applying verification presets. * Overrides the default topic from config. */ topic?: ResearchTopic; /** * Expected fields to verify in the content. * Merged with preset fields if a topic is specified. */ expectedFields?: string[]; /** * Text patterns that indicate an error page. * Merged with preset patterns if a topic is specified. */ excludePatterns?: string[]; /** * Minimum content length for validation. * Overrides preset value if specified. */ minContentLength?: number; /** * Whether to save the session after browsing. * Useful for authenticated portals. * @default false */ saveSession?: boolean; /** * Session profile to use/save. * Auto-detected from domain if not specified. */ sessionProfile?: string; } /** * Research result with additional metadata */ export interface ResearchResult extends SmartBrowseResult { /** Research-specific metadata */ research: { /** Topic used for verification */ topic: ResearchTopic; /** Session profile used */ sessionProfile?: string; /** Whether session was shared from another domain */ sessionSharedFrom?: string; /** API used instead of browser (if discovered) */ apiUsed?: boolean; /** Whether browser rendering was bypassed via direct API call (INT-003) */ bypassedBrowser?: boolean; /** API endpoint used if browser was bypassed (INT-003) */ apiEndpoint?: string; /** Time saved by using API instead of browser in ms (INT-003) */ timeSavedMs?: number; /** Error message if the research operation failed */ error?: string; /** Verification result summary */ verificationSummary: { passed: boolean; confidence: number; checkedFields: string[]; missingFields: string[]; excludedPatternFound?: string; }; }; } /** * Research Browser Client * * Specialized SDK client for research use cases with presets for: * - Government portal navigation * - Legal document extraction * - Visa/immigration information * - Cross-domain session sharing (SSO) * * @example * ```typescript * const browser = await createResearchBrowser({ * defaultTopic: 'visa_immigration', * persistSessions: true, * }); * * // Browse with research presets * const result = await browser.research('https://extranjeros.inclusion.gob.es/visados', { * topic: 'visa_immigration', * expectedFields: ['requirements', 'documents', 'fees'], * }); * * console.log(result.research.verificationSummary); * await browser.cleanup(); * ``` */ export declare class ResearchBrowserClient extends LLMBrowserClient { /** Conservative estimate for browser render time in ms */ private static readonly ESTIMATED_BROWSER_RENDER_TIME_MS; /** Fields to skip during content extraction (internal/metadata fields) */ private static readonly IRRELEVANT_FIELDS; /** Minimum length for a string to be considered relevant content */ private static readonly MIN_RELEVANT_STRING_LENGTH; /** Fields to check for title extraction, in priority order */ private static readonly CANDIDATE_TITLE_FIELDS; /** Maximum length of first line to use as title */ private static readonly MAX_TITLE_LENGTH_FROM_FIRST_LINE; private researchConfig; private sessionProfiles; private verificationPresets; constructor(config?: ResearchConfig); /** * Get session profile for a domain */ getSessionProfileForDomain(domain: string): string | undefined; /** * Build verification checks from research options (INT-004) * * Combines checks from multiple sources in order: * 1. Pre-built checks from the preset (VERIFICATION_CHECKS) * 2. Field existence check from expectedFields * 3. Exclude pattern checks from excludePatterns * 4. Minimum content length check */ private buildVerificationChecks; /** * Research a URL with verification presets and session management * * This is the main research method that: * - Applies verification presets based on topic * - Attempts SSO session sharing when applicable * - Follows pagination for legal documents * - Prefers API discovery when available * * @param url - The URL to research * @param options - Research-specific options * @returns Research result with verification summary */ research(url: string, options?: ResearchBrowseOptions): Promise; /** * Try to bypass browser rendering using discovered APIs (INT-003) * * This method checks if there are high-confidence APIs that can be called * directly instead of rendering the page in a browser. This can provide * 10-50x speedup for domains with discovered APIs. * * @param url - The URL to research * @param domain - The domain extracted from the URL * @param topic - The research topic for content extraction * @param options - Research browse options * @returns API bypass result if successful, null if should fall back to browser */ private tryApiBypass; /** * Extract readable content from API JSON response (INT-003) */ private extractContentFromApiResponse; /** * Get nested value from object using dot notation or exact match */ private getNestedValue; /** * Format a value for display */ private formatValue; /** * Check if a field is relevant for content extraction */ private isRelevantField; /** * Extract title from content or structured data */ private extractTitleFromContent; /** * Build verification summary from browse result */ private buildVerificationSummary; /** * Research multiple URLs with the same topic * * @param urls - Array of URLs to research * @param options - Research options applied to all URLs * @returns Array of research results */ researchBatch(urls: string[], options?: ResearchBrowseOptions): Promise; /** * Get research statistics */ getResearchStats(): { sessionProfiles: number; verificationPresets: number; governmentDomains: string[]; ssoEnabled: boolean; defaultTopic: ResearchTopic; }; /** * Execute a workflow template with the given variables * * Workflow templates provide pre-built research patterns for common use cases: * - Visa research across countries * - Document extraction from legal databases * - Fee tracking for immigration/tax procedures * * @param template - The workflow template to execute * @param variables - Variables to substitute in the template * @returns Workflow execution result with findings and summary * * @example * ```typescript * import { createResearchBrowser, WORKFLOW_TEMPLATES } from 'llm-browser/sdk'; * * const browser = await createResearchBrowser(); * * // Execute visa research workflow * const result = await browser.executeTemplate(WORKFLOW_TEMPLATES.visaResearch, { * country: 'ES', * visaType: 'digital_nomad', * }); * * console.log(`Success: ${result.success}`); * console.log(`Findings: ${result.summary.findings.length}`); * ``` */ executeTemplate(template: import('./core/workflow-templates.js').WorkflowTemplate, variables: Record): Promise; /** * List available workflow templates * * @returns Array of template metadata */ listWorkflowTemplates(): Array<{ id: string; name: string; description: string; tags: string[]; requiredVariables: string[]; }>; /** * Get a workflow template by ID * * @param id - Template ID * @returns Template or undefined if not found */ getWorkflowTemplate(id: string): import('./core/workflow-templates.js').WorkflowTemplate | undefined; } /** * Create and initialize a Research Browser client * * Factory function for creating a research-optimized browser with presets for: * - Government portal navigation * - Legal document extraction * - Visa/immigration information * - Cross-domain session sharing * * @param config - Research configuration options * @returns Initialized Research Browser client * * @example * ```typescript * // Create with defaults * const browser = await createResearchBrowser(); * * // Research a government portal * const result = await browser.research('https://extranjeros.inclusion.gob.es/visados', { * topic: 'visa_immigration', * }); * * // Check verification * if (result.research.verificationSummary.passed) { * console.log('Content verified:', result.content.markdown); * } else { * console.log('Missing fields:', result.research.verificationSummary.missingFields); * } * * await browser.cleanup(); * ``` * * @example * ```typescript * // Create with custom presets * const browser = await createResearchBrowser({ * defaultTopic: 'government_portal', * customSessionProfiles: { * 'customs.gov': 'customs-portal', * }, * customVerificationPresets: { * customs_declaration: { * description: 'Customs declaration forms', * expectedFields: ['declaration', 'items', 'value', 'origin'], * excludePatterns: ['404', 'Error'], * minContentLength: 300, * verifyOptions: { enabled: true, mode: 'thorough' }, * }, * }, * }); * ``` */ export declare function createResearchBrowser(config?: ResearchConfig): Promise; /** * Dynamic Handler System for automatic site pattern learning. * * The dynamic handler system learns from every browse operation: * 1. Repeatable patterns (Shopify-like, WooCommerce, Next.js SSR, etc.) * 2. Site-specific quirks (headers, rate limits, anti-bot detection) * * @example * ```typescript * import { * initializeDynamicHandlers, * dynamicHandlerIntegration, * shutdownDynamicHandlers, * } from 'llm-browser/sdk'; * * // Initialize at app startup (loads persisted handlers) * initializeDynamicHandlers(); * * // Get recommendations for a URL * const recommendation = dynamicHandlerIntegration.getRecommendation({ * url: 'https://example-store.com/products/test', * domain: 'example-store.com', * }); * console.log(`Template: ${recommendation.template}`); * * // Get learned stats * const stats = dynamicHandlerIntegration.getStats(); * console.log(`Learned handlers: ${stats.totalHandlers}`); * console.log(`Quirks learned: ${stats.totalQuirks}`); * * // Shutdown gracefully (saves handlers) * shutdownDynamicHandlers(); * ``` */ export { DynamicHandlerIntegration, dynamicHandlerIntegration, initializeDynamicHandlers, shutdownDynamicHandlers, applyQuirksToFetchOptions, templateToStrategy, DynamicHandlerRegistry, dynamicHandlerRegistry, detectTemplate, getTemplateConfig, PATTERN_TEMPLATES, mergeTemplateWithQuirks, saveRegistry, loadRegistry, AutoSaveRegistry, createPersistentRegistry, } from './core/dynamic-handlers/index.js'; export type { DynamicHandler, LearnedSiteHandler, HandlerTemplate, HandlerMatch, LearningConfig, ExtractionRule, ExtractionMethod, ApiPattern as DynamicApiPattern, UrlPattern, PatternTemplate, PatternSignal, ExtractionObservation, SiteQuirks, ExtractionContext, ExtractionRecommendation, SerializedHandlerRegistry, } from './core/dynamic-handlers/index.js'; //# sourceMappingURL=sdk.d.ts.map