polyrob 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agents/README.md +453 -0
- agents/__init__.py +164 -0
- agents/base_agent.py +743 -0
- agents/personality/character.py +119 -0
- agents/personality/character_manager.py +309 -0
- agents/personality/characters/rob.character.json +56 -0
- agents/personality/characters/trump.character.json +63 -0
- agents/personality/persona_render.py +78 -0
- agents/personality/persona_resolver.py +115 -0
- agents/prompt/__init__.py +58 -0
- agents/prompt/base_prompt.py +92 -0
- agents/prompt/system.py +417 -0
- agents/task/README_PATH_MANAGEMENT.md +141 -0
- agents/task/__init__.py +162 -0
- agents/task/agent/__init__.py +70 -0
- agents/task/agent/agent_state.py +408 -0
- agents/task/agent/async_delegation.py +274 -0
- agents/task/agent/autonomy_state.py +275 -0
- agents/task/agent/conversation.py +75 -0
- agents/task/agent/core/__init__.py +6 -0
- agents/task/agent/core/aux_metering.py +61 -0
- agents/task/agent/core/background_review.py +157 -0
- agents/task/agent/core/construction.py +1179 -0
- agents/task/agent/core/conversational_exit.py +49 -0
- agents/task/agent/core/correspondent_gate.py +227 -0
- agents/task/agent/core/curator.py +246 -0
- agents/task/agent/core/episodic_digest.py +103 -0
- agents/task/agent/core/error_recovery.py +480 -0
- agents/task/agent/core/history_io.py +257 -0
- agents/task/agent/core/llm_provisioning.py +287 -0
- agents/task/agent/core/llm_runner.py +547 -0
- agents/task/agent/core/logging_io.py +276 -0
- agents/task/agent/core/loop_detection.py +262 -0
- agents/task/agent/core/memory_prefetch.py +325 -0
- agents/task/agent/core/memory_writer.py +667 -0
- agents/task/agent/core/model_introspection.py +82 -0
- agents/task/agent/core/model_swap.py +177 -0
- agents/task/agent/core/next_action_internal.py +1331 -0
- agents/task/agent/core/output_validation.py +303 -0
- agents/task/agent/core/project_context.py +272 -0
- agents/task/agent/core/resources.py +93 -0
- agents/task/agent/core/result_processing.py +389 -0
- agents/task/agent/core/run_loop.py +661 -0
- agents/task/agent/core/safety_lifecycle.py +228 -0
- agents/task/agent/core/secret_guard.py +293 -0
- agents/task/agent/core/self_wake.py +280 -0
- agents/task/agent/core/session_metadata.py +104 -0
- agents/task/agent/core/step.py +781 -0
- agents/task/agent/core/step_execution.py +398 -0
- agents/task/agent/core/step_telemetry.py +222 -0
- agents/task/agent/core/test_aux_metering.py +50 -0
- agents/task/agent/core/test_billing_failover.py +68 -0
- agents/task/agent/core/test_fatal_error_classifier.py +38 -0
- agents/task/agent/core/test_judge_validation.py +275 -0
- agents/task/agent/core/test_model_swap.py +190 -0
- agents/task/agent/core/test_reflection_offload.py +54 -0
- agents/task/agent/core/turn_input.py +8 -0
- agents/task/agent/core/untrusted_wrap.py +103 -0
- agents/task/agent/core/user_ingress.py +228 -0
- agents/task/agent/hitl_manager.py +396 -0
- agents/task/agent/log_sanitize.py +36 -0
- agents/task/agent/message_manager/config.py +97 -0
- agents/task/agent/message_manager/service.py +758 -0
- agents/task/agent/message_manager/tests.py +305 -0
- agents/task/agent/message_manager/tool_call_builder.py +539 -0
- agents/task/agent/message_manager/tool_message_repair.py +364 -0
- agents/task/agent/message_manager/views.py +143 -0
- agents/task/agent/messages/__init__.py +8 -0
- agents/task/agent/messages/builders.py +309 -0
- agents/task/agent/messages/compactor.py +611 -0
- agents/task/agent/messages/context_references.py +271 -0
- agents/task/agent/messages/filters.py +333 -0
- agents/task/agent/messages/guidance.py +328 -0
- agents/task/agent/messages/persistence.py +448 -0
- agents/task/agent/messages/retrieval.py +506 -0
- agents/task/agent/messages/sqlite_persistence.py +85 -0
- agents/task/agent/messages/test_compaction_upgrade.py +349 -0
- agents/task/agent/messages/test_persistence_subdir_fix.py +28 -0
- agents/task/agent/messages/test_sqlite_persistence.py +54 -0
- agents/task/agent/messages/token_counter.py +532 -0
- agents/task/agent/orchestrator.py +776 -0
- agents/task/agent/profile_manager.py +105 -0
- agents/task/agent/profile_registry.py +173 -0
- agents/task/agent/prompts.py +1090 -0
- agents/task/agent/scenario_registry.py +226 -0
- agents/task/agent/service.py +509 -0
- agents/task/agent/session.py +984 -0
- agents/task/agent/skill_discovery.py +110 -0
- agents/task/agent/skill_frontmatter.py +94 -0
- agents/task/agent/skill_manager.py +1201 -0
- agents/task/agent/skill_store.py +627 -0
- agents/task/agent/skill_validation.py +56 -0
- agents/task/agent/skill_writer.py +492 -0
- agents/task/agent/sub_agent_manager.py +1137 -0
- agents/task/agent/test_session_disk_recovery.py +34 -0
- agents/task/agent/tests.py +513 -0
- agents/task/agent/tool_call_tracker.py +511 -0
- agents/task/agent/views.py +469 -0
- agents/task/config.py +432 -0
- agents/task/constants.py +1384 -0
- agents/task/flag_defaults.py +63 -0
- agents/task/goals/__init__.py +1 -0
- agents/task/goals/autonomy_marker.py +28 -0
- agents/task/goals/board.py +690 -0
- agents/task/goals/completion_judge.py +247 -0
- agents/task/goals/context.py +62 -0
- agents/task/goals/dispatcher.py +848 -0
- agents/task/goals/escalation.py +102 -0
- agents/task/goals/planner.py +114 -0
- agents/task/logging_config.py +155 -0
- agents/task/path.py +991 -0
- agents/task/robust_parse_config.py +400 -0
- agents/task/runtime/__init__.py +0 -0
- agents/task/runtime/run_as_session.py +130 -0
- agents/task/runtime_safety.py +308 -0
- agents/task/session/__init__.py +5 -0
- agents/task/session/browser_pool.py +130 -0
- agents/task/session/cleanup.py +612 -0
- agents/task/session/execution.py +397 -0
- agents/task/session/feed.py +200 -0
- agents/task/session/hitl_ingress.py +201 -0
- agents/task/session/hooks.py +83 -0
- agents/task/session/multi_agent.py +243 -0
- agents/task/session/workspace.py +91 -0
- agents/task/session_registry.py +91 -0
- agents/task/session_route.py +35 -0
- agents/task/sqlite_session_registry.py +261 -0
- agents/task/surface_config.py +185 -0
- agents/task/telemetry/__init__.py +58 -0
- agents/task/telemetry/event_log.py +180 -0
- agents/task/telemetry/formatters.py +642 -0
- agents/task/telemetry/manager.py +571 -0
- agents/task/telemetry/memory_events.py +66 -0
- agents/task/telemetry/self_events.py +53 -0
- agents/task/telemetry/sequence.py +160 -0
- agents/task/telemetry/service.py +1265 -0
- agents/task/telemetry/views.py +882 -0
- agents/task/templates.py +98 -0
- agents/task/test_aux_chain.py +151 -0
- agents/task/test_aux_router.py +41 -0
- agents/task/tests/test_parse_robustness.py +170 -0
- agents/task/tool_defaults.py +110 -0
- agents/task/utils.py +762 -0
- agents/task/utils_json.py +768 -0
- agents/task/utils_webview.py +86 -0
- agents/task/workspace_context.py +229 -0
- agents/task_agent_lite.py +2398 -0
- api/README.md +683 -0
- api/TASK_API_DOCS.md +151 -0
- api/__init__.py +0 -0
- api/a2a/__init__.py +37 -0
- api/a2a/agent_card.py +337 -0
- api/a2a/client.py +657 -0
- api/a2a/endpoints.py +375 -0
- api/a2a/models.py +268 -0
- api/a2a/streaming.py +419 -0
- api/a2a/task_handler.py +929 -0
- api/admin_endpoints.py +1584 -0
- api/app.py +923 -0
- api/auth_constants.py +28 -0
- api/auth_endpoints.py +402 -0
- api/auth_state.py +36 -0
- api/chat_via_task.py +42 -0
- api/conversation_manager.py +231 -0
- api/dependencies.py +186 -0
- api/eip8004_endpoints.py +452 -0
- api/hyperliquid_models.py +174 -0
- api/hyperliquid_routes.py +450 -0
- api/interfaces.py +207 -0
- api/jwt_middleware.py +83 -0
- api/kb/__init__.py +1 -0
- api/kb/endpoints.py +314 -0
- api/mcp_models.py +279 -0
- api/mcp_routes.py +438 -0
- api/middleware.py +526 -0
- api/models.py +176 -0
- api/openai_compat/__init__.py +0 -0
- api/openai_compat/model_map.py +25 -0
- api/openai_compat/models.py +59 -0
- api/openai_compat/router.py +140 -0
- api/payment_endpoints.py +444 -0
- api/payment_verification.py +138 -0
- api/polymarket_models.py +155 -0
- api/polymarket_routes.py +501 -0
- api/pricing_endpoints.py +89 -0
- api/session_routing.py +54 -0
- api/skill_endpoints.py +453 -0
- api/task_http_api.py +1856 -0
- api/webhooks.py +52 -0
- api/x402_endpoints.py +280 -0
- avatar/README.md +44 -0
- avatar/__init__.py +1 -0
- avatar/config/rob.json +7 -0
- avatar/mindprint.js +395 -0
- avatar/renders/rob.meta.json +20 -0
- avatar/renders/rob.png +0 -0
- avatar/studio.html +373 -0
- avatar/webview/avatar-live.js +44 -0
- cli/README.md +89 -0
- cli/__init__.py +0 -0
- cli/cli_surface.py +67 -0
- cli/commands/__init__.py +0 -0
- cli/commands/_bootstrap.py +49 -0
- cli/commands/_errors.py +53 -0
- cli/commands/chat.py +973 -0
- cli/commands/config.py +100 -0
- cli/commands/dashboard.py +103 -0
- cli/commands/doctor.py +222 -0
- cli/commands/email.py +174 -0
- cli/commands/gateway.py +346 -0
- cli/commands/goals.py +509 -0
- cli/commands/init.py +276 -0
- cli/commands/journey.py +30 -0
- cli/commands/kb.py +280 -0
- cli/commands/model.py +107 -0
- cli/commands/owner.py +431 -0
- cli/commands/pfp.py +232 -0
- cli/commands/run.py +414 -0
- cli/commands/serve.py +41 -0
- cli/commands/session.py +684 -0
- cli/commands/skill_install.py +786 -0
- cli/commands/skills.py +128 -0
- cli/commands/subagents.py +100 -0
- cli/commands/surface.py +81 -0
- cli/commands/telegram.py +185 -0
- cli/commands/todos.py +209 -0
- cli/commands/tools.py +102 -0
- cli/commands/update.py +316 -0
- cli/commands/whatsapp.py +175 -0
- cli/config_store.py +276 -0
- cli/gitignore.py +43 -0
- cli/inventory.py +46 -0
- cli/keys.py +101 -0
- cli/persona.py +17 -0
- cli/polyrob.py +137 -0
- cli/ui/__init__.py +64 -0
- cli/ui/activity.py +141 -0
- cli/ui/app.py +538 -0
- cli/ui/banner.py +233 -0
- cli/ui/blocks.py +534 -0
- cli/ui/bootstrap_notice.py +47 -0
- cli/ui/commands/__init__.py +41 -0
- cli/ui/commands/h_cron.py +64 -0
- cli/ui/commands/h_journey.py +164 -0
- cli/ui/commands/h_kb.py +121 -0
- cli/ui/commands/h_learn.py +100 -0
- cli/ui/commands/h_mcp.py +215 -0
- cli/ui/commands/h_self.py +113 -0
- cli/ui/commands/h_skills.py +314 -0
- cli/ui/commands/handlers.py +1672 -0
- cli/ui/commands/registry.py +426 -0
- cli/ui/dialog.py +425 -0
- cli/ui/event_registry.py +110 -0
- cli/ui/event_specs.py +45 -0
- cli/ui/events.py +433 -0
- cli/ui/identity.py +15 -0
- cli/ui/lifecycle.py +159 -0
- cli/ui/live_hooks.py +43 -0
- cli/ui/model_selector.py +532 -0
- cli/ui/persistent_loop.py +181 -0
- cli/ui/pick.py +113 -0
- cli/ui/plain_renderer.py +351 -0
- cli/ui/renderer.py +384 -0
- cli/ui/rich_renderer.py +533 -0
- cli/ui/secrets.py +115 -0
- cli/ui/state.py +376 -0
- cli/ui/statusbar.py +231 -0
- cli/ui/streaming.py +254 -0
- cli/ui/terminal_render.py +105 -0
- cli/ui/theme.py +132 -0
- cli/update/__init__.py +6 -0
- cli/update/context.py +121 -0
- cli/update/detect.py +176 -0
- cli/update/engine.py +95 -0
- cli/update/migrate_guarded.py +55 -0
- cli/update/process_guard.py +215 -0
- cli/update/runners.py +78 -0
- cli/update/snapshot.py +270 -0
- cli/update/versions.py +205 -0
- core/README.md +377 -0
- core/__init__.py +174 -0
- core/assets.py +87 -0
- core/async_bridge.py +76 -0
- core/autonomy_runtime.py +259 -0
- core/base_component.py +302 -0
- core/bootstrap.py +681 -0
- core/bot.py +310 -0
- core/config.py +833 -0
- core/constants.py +126 -0
- core/container.py +462 -0
- core/db_manifest.py +101 -0
- core/embedding.py +57 -0
- core/env.py +39 -0
- core/exceptions.py +287 -0
- core/flags.py +144 -0
- core/flags_catalog.py +345 -0
- core/home_migration.py +62 -0
- core/identity.py +118 -0
- core/initialization.py +1004 -0
- core/instance.py +537 -0
- core/interactive_gate.py +96 -0
- core/logging.py +436 -0
- core/owner_doc_writer.py +176 -0
- core/pairing.py +193 -0
- core/path_safety.py +20 -0
- core/paths.py +27 -0
- core/payment_config.py +21 -0
- core/permissions.py +322 -0
- core/runtime_config.py +96 -0
- core/runtime_paths.py +135 -0
- core/seams.py +35 -0
- core/secret_scan.py +25 -0
- core/secret_scrub.py +71 -0
- core/secrets.py +35 -0
- core/security_logging_filter.py +148 -0
- core/self_context_writer.py +333 -0
- core/self_evolution.py +294 -0
- core/session_context.py +47 -0
- core/sqlite_util.py +59 -0
- core/surfaces/__init__.py +16 -0
- core/surfaces/access.py +118 -0
- core/surfaces/binding.py +88 -0
- core/surfaces/bootstrap.py +78 -0
- core/surfaces/circuit.py +168 -0
- core/surfaces/continuity.py +77 -0
- core/surfaces/correspondents.py +228 -0
- core/surfaces/dispatcher.py +216 -0
- core/surfaces/envelopes.py +75 -0
- core/surfaces/gc.py +30 -0
- core/surfaces/idempotency.py +57 -0
- core/surfaces/inbound_webhook.py +124 -0
- core/surfaces/media.py +32 -0
- core/surfaces/message_router.py +91 -0
- core/surfaces/outbound_allowlist.py +80 -0
- core/surfaces/outbound_dispatcher.py +110 -0
- core/surfaces/outbound_mirror.py +37 -0
- core/surfaces/outbound_queue.py +107 -0
- core/surfaces/outbound_target.py +12 -0
- core/surfaces/owner_admin.py +29 -0
- core/surfaces/proactive.py +78 -0
- core/surfaces/progress.py +108 -0
- core/surfaces/rate_bucket.py +21 -0
- core/surfaces/registry.py +51 -0
- core/surfaces/rendering.py +53 -0
- core/surfaces/send_policy.py +14 -0
- core/surfaces/serialize.py +24 -0
- core/surfaces/session_chat_registry.py +112 -0
- core/surfaces/session_policy.py +60 -0
- core/surfaces/surface.py +288 -0
- core/surfaces/transcription.py +88 -0
- core/surfaces/voice_echo.py +26 -0
- core/surfaces/voice_guard.py +23 -0
- core/tickers.py +174 -0
- core/tool_catalog.py +192 -0
- core/version.py +75 -0
- core/wallet/__init__.py +5 -0
- core/wallet/agent_wallet.py +59 -0
- core/wallet/audit_sink.py +61 -0
- core/wallet/config.py +70 -0
- core/wallet/factory.py +87 -0
- core/wallet/policy.py +104 -0
- core/wallet/signer.py +51 -0
- cron/README.md +65 -0
- cron/__init__.py +0 -0
- cron/delivery.py +277 -0
- cron/digest.py +124 -0
- cron/jobs.py +207 -0
- cron/runner.py +297 -0
- cron/schedule.py +194 -0
- cron/scheduler.py +201 -0
- cron/service.py +57 -0
- cron/wake_gate.py +223 -0
- data/__init__.py +1 -0
- data/prompts/autov2_prompts.json +87 -0
- data/prompts/skills/browser-automation/SKILL.md +43 -0
- data/prompts/skills/coding-workflow/SKILL.md +36 -0
- data/prompts/skills/crypto-trading-safety/SKILL.md +53 -0
- data/prompts/skills/document-writing/SKILL.md +33 -0
- data/prompts/skills/email-comms/SKILL.md +33 -0
- data/prompts/skills/file-data-ops/SKILL.md +35 -0
- data/prompts/skills/hyperliquid-account-review/SKILL.md +48 -0
- data/prompts/skills/hyperliquid-market-data/SKILL.md +52 -0
- data/prompts/skills/hyperliquid-trading/SKILL.md +59 -0
- data/prompts/skills/lead-research/SKILL.md +86 -0
- data/prompts/skills/market-research-brief/SKILL.md +104 -0
- data/prompts/skills/person-analyzer/SKILL.md +124 -0
- data/prompts/skills/polymarket-market-research/SKILL.md +54 -0
- data/prompts/skills/polymarket-portfolio-review/SKILL.md +50 -0
- data/prompts/skills/polymarket-trading/SKILL.md +55 -0
- data/prompts/skills/presentation-creator/SKILL.md +36 -0
- data/prompts/skills/project-analyzer/SKILL.md +169 -0
- data/prompts/skills/rules.json +268 -0
- data/prompts/skills/secret-handling/SKILL.md +20 -0
- data/prompts/skills/skill-authoring/SKILL.md +31 -0
- data/prompts/skills/skill-security-review/SKILL.md +27 -0
- data/prompts/skills/social-discovery/SKILL.md +57 -0
- data/prompts/skills/task-planning/SKILL.md +33 -0
- data/prompts/skills/web-research/SKILL.md +39 -0
- data/prompts/skills/web-scraping/SKILL.md +73 -0
- data/prompts/skills/x-engagement/SKILL.md +69 -0
- data/prompts/system_prompts.json +4 -0
- data/subscription_channels.json +5 -0
- modules/README.md +503 -0
- modules/__init__.py +124 -0
- modules/auth/__init__.py +13 -0
- modules/auth/api_key_manager.py +157 -0
- modules/auth/identity_mapper.py +380 -0
- modules/auth/siwe_auth.py +273 -0
- modules/auth/tier_manager.py +173 -0
- modules/base_module.py +190 -0
- modules/credits/__init__.py +29 -0
- modules/credits/balance_manager.py +237 -0
- modules/credits/cost_utils.py +129 -0
- modules/credits/pricing.py +139 -0
- modules/credits/unified_ledger.py +148 -0
- modules/credits/usage_meter.py +310 -0
- modules/credits/usage_tracker.py +674 -0
- modules/database/__init__.py +33 -0
- modules/database/audit_log.py +322 -0
- modules/database/auth_tables.py +276 -0
- modules/database/connection.py +644 -0
- modules/database/connection_pool.py +305 -0
- modules/database/conversation_contexts.py +446 -0
- modules/database/database_manager.py +237 -0
- modules/database/hyperliquid.py +375 -0
- modules/database/polymarket.py +574 -0
- modules/database/user_mcp_servers.py +728 -0
- modules/database/user_profiles.py +562 -0
- modules/database/utils.py +107 -0
- modules/database/x402_tables.py +92 -0
- modules/eip8004/README.md +1069 -0
- modules/eip8004/__init__.py +65 -0
- modules/eip8004/contracts.py +498 -0
- modules/eip8004/models.py +271 -0
- modules/eip8004/registration.py +148 -0
- modules/eip8004/reputation.py +367 -0
- modules/eip8004/validation.py +277 -0
- modules/llm/__init__.py +97 -0
- modules/llm/adapters.py +963 -0
- modules/llm/anthropic_client.py +831 -0
- modules/llm/available_models.py +106 -0
- modules/llm/brain_scrubber.py +137 -0
- modules/llm/cache_hints.py +162 -0
- modules/llm/deepseek_client.py +562 -0
- modules/llm/gemini_client.py +1367 -0
- modules/llm/llm_client.py +1139 -0
- modules/llm/llm_client_registry.py +188 -0
- modules/llm/llm_factory.py +237 -0
- modules/llm/llm_manager.py +1036 -0
- modules/llm/messages.py +374 -0
- modules/llm/model_registry.py +1935 -0
- modules/llm/nvidia_client.py +125 -0
- modules/llm/openai_client.py +800 -0
- modules/llm/openrouter_client.py +969 -0
- modules/llm/profiles.py +178 -0
- modules/llm/test_anthropic_cache_capture.py +35 -0
- modules/llm/test_cached_pricing_derivation.py +24 -0
- modules/llm/think_scrubber.py +444 -0
- modules/llm/token_counter.py +268 -0
- modules/memory/__init__.py +35 -0
- modules/memory/backend_factory.py +83 -0
- modules/memory/cache_manager.py +186 -0
- modules/memory/episodic.py +108 -0
- modules/memory/local_vector_memory_provider.py +552 -0
- modules/memory/memory_manager.py +225 -0
- modules/memory/models.py +312 -0
- modules/memory/provider.py +210 -0
- modules/memory/registry.py +205 -0
- modules/memory/sqlite_memory_provider.py +767 -0
- modules/memory/task/__init__.py +52 -0
- modules/memory/task/compaction_manager.py +157 -0
- modules/memory/task/context_retriever.py +809 -0
- modules/memory/task/hierarchical_memory.py +1002 -0
- modules/memory/task/lexical_retriever.py +71 -0
- modules/memory/task/null_context_manager.py +213 -0
- modules/memory/task/phase_manager.py +625 -0
- modules/memory/task/reflection_service.py +157 -0
- modules/memory/task/semantic_retriever.py +218 -0
- modules/memory/task/task_context_manager.py +1165 -0
- modules/memory/task/test_forgetting_engages.py +24 -0
- modules/memory/task/test_reflection_llm.py +39 -0
- modules/memory/task/test_threat_scan.py +53 -0
- modules/memory/task/threat_scan.py +90 -0
- modules/memory/test_sqlite_memory_provider.py +106 -0
- modules/memory/user_profile_manager.py +527 -0
- modules/payments/__init__.py +11 -0
- modules/payments/deposit_monitor.py +478 -0
- modules/payments/price_oracle.py +70 -0
- modules/payments/treasury_sweeper.py +401 -0
- modules/payments/wallet_generator.py +145 -0
- modules/pfp/__init__.py +1 -0
- modules/pfp/config.py +92 -0
- modules/pfp/mesh.py +565 -0
- modules/pfp/push.py +69 -0
- modules/pfp/renderer.py +85 -0
- modules/pfp/store.py +82 -0
- modules/skills/__init__.py +1 -0
- modules/skills/skill_usage.py +248 -0
- modules/transcription/__init__.py +24 -0
- modules/transcription/base.py +20 -0
- modules/transcription/faster_whisper_transcriber.py +55 -0
- modules/x402/README.md +249 -0
- modules/x402/__init__.py +22 -0
- modules/x402/invoicing.py +416 -0
- modules/x402/middleware.py +364 -0
- modules/x402/settlement_watcher.py +145 -0
- modules/x402/x402_integration.py +344 -0
- polyrob-0.5.0.dist-info/METADATA +482 -0
- polyrob-0.5.0.dist-info/RECORD +745 -0
- polyrob-0.5.0.dist-info/WHEEL +5 -0
- polyrob-0.5.0.dist-info/entry_points.txt +2 -0
- polyrob-0.5.0.dist-info/licenses/LICENSE +21 -0
- polyrob-0.5.0.dist-info/top_level.txt +12 -0
- surfaces/README.md +70 -0
- surfaces/__init__.py +0 -0
- surfaces/email/__init__.py +0 -0
- surfaces/email/dedup.py +44 -0
- surfaces/email/harness.py +187 -0
- surfaces/email/inbound.py +159 -0
- surfaces/email/seed.py +60 -0
- surfaces/email/surface.py +105 -0
- surfaces/telegram/__init__.py +0 -0
- surfaces/telegram/dedup.py +83 -0
- surfaces/telegram/harness.py +886 -0
- surfaces/telegram/inbound.py +145 -0
- surfaces/telegram/interactive_tools.py +49 -0
- surfaces/telegram/markdown.py +347 -0
- surfaces/telegram/rate_limit.py +167 -0
- surfaces/telegram/surface.py +187 -0
- surfaces/telegram/voice.py +52 -0
- surfaces/whatsapp/__init__.py +0 -0
- surfaces/whatsapp/client.py +51 -0
- surfaces/whatsapp/harness.py +62 -0
- surfaces/whatsapp/inbound.py +132 -0
- surfaces/whatsapp/surface.py +64 -0
- surfaces/whatsapp/window.py +34 -0
- tools/README.md +578 -0
- tools/__init__.py +424 -0
- tools/alchemy/__init__.py +5 -0
- tools/alchemy/alchemy_tool.py +389 -0
- tools/anysite/__init__.py +17 -0
- tools/anysite/client.py +88 -0
- tools/anysite/tool.py +89 -0
- tools/base_tool.py +468 -0
- tools/browser/__init__.py +22 -0
- tools/browser/actions.py +118 -0
- tools/browser/browser.py +1457 -0
- tools/browser/browser_manager.py +690 -0
- tools/browser/context.py +1748 -0
- tools/browser/playwright_utils.py +137 -0
- tools/browser/views.py +56 -0
- tools/code_exec/SANDBOX_SECURITY.md +144 -0
- tools/code_exec/__init__.py +178 -0
- tools/code_exec/backend.py +73 -0
- tools/code_exec/backends/__init__.py +1 -0
- tools/code_exec/backends/docker.py +779 -0
- tools/code_exec/backends/local_subprocess.py +154 -0
- tools/code_exec/env_policy.py +45 -0
- tools/code_exec/result.py +42 -0
- tools/code_exec/sandbox_guard.py +59 -0
- tools/code_exec/tool.py +227 -0
- tools/coding/__init__.py +50 -0
- tools/coding/edit.py +107 -0
- tools/coding/search.py +113 -0
- tools/coding/tool.py +353 -0
- tools/collabland/__init__.py +5 -0
- tools/collabland/collabland_tool.py +471 -0
- tools/controller/__init__.py +0 -0
- tools/controller/_helpers.py +165 -0
- tools/controller/action_registration.py +1765 -0
- tools/controller/approval.py +244 -0
- tools/controller/approval_interactive.py +90 -0
- tools/controller/delegation.py +195 -0
- tools/controller/execution.py +797 -0
- tools/controller/execution_context.py +141 -0
- tools/controller/hooks.py +135 -0
- tools/controller/introspection.py +344 -0
- tools/controller/mcp_registrar.py +190 -0
- tools/controller/message_send.py +31 -0
- tools/controller/registry/__init__.py +4 -0
- tools/controller/registry/schema_generators.py +395 -0
- tools/controller/registry/schema_sanitizer.py +406 -0
- tools/controller/registry/service.py +1266 -0
- tools/controller/registry/views.py +151 -0
- tools/controller/service.py +409 -0
- tools/controller/tool_management.py +334 -0
- tools/controller/types.py +28 -0
- tools/controller/views.py +450 -0
- tools/cronjob_tools.py +166 -0
- tools/crypto_trade_gate.py +59 -0
- tools/descriptors.py +452 -0
- tools/dom/__init__.py +0 -0
- tools/dom/history_tree_processor/service.py +244 -0
- tools/dom/history_tree_processor/view.py +99 -0
- tools/dom/service.py +471 -0
- tools/dom/views.py +346 -0
- tools/email_tool.py +403 -0
- tools/exceptions.py +169 -0
- tools/filesystem.py +1038 -0
- tools/filesystem_docproc.py +331 -0
- tools/filesystem_pdf.py +755 -0
- tools/git/__init__.py +42 -0
- tools/git/tool.py +258 -0
- tools/github/__init__.py +33 -0
- tools/github/client.py +94 -0
- tools/github/tool.py +237 -0
- tools/goal_tools.py +309 -0
- tools/hyperliquid/__init__.py +56 -0
- tools/hyperliquid/models.py +233 -0
- tools/hyperliquid/service.py +1680 -0
- tools/knowledge_ingest.py +950 -0
- tools/mcp/README.md +535 -0
- tools/mcp/__init__.py +52 -0
- tools/mcp/catalog.py +115 -0
- tools/mcp/config.py +337 -0
- tools/mcp/mcp_tool.py +1415 -0
- tools/mcp/param_coercion.py +289 -0
- tools/mcp/protocol.py +1520 -0
- tools/mcp/rate_limit.py +50 -0
- tools/mcp/security.py +424 -0
- tools/mcp/self_install.py +111 -0
- tools/mcp/server_manager.py +829 -0
- tools/mcp/subscriptions.py +72 -0
- tools/mcp/user_mcp_service.py +899 -0
- tools/mcp/validation_tracker.py +89 -0
- tools/mcp/views.py +346 -0
- tools/oauth/__init__.py +17 -0
- tools/oauth/manager.py +75 -0
- tools/oauth/provider.py +69 -0
- tools/oauth/providers/__init__.py +1 -0
- tools/oauth/providers/generic_oauth2.py +96 -0
- tools/perplexity_tool.py +280 -0
- tools/polymarket/__init__.py +41 -0
- tools/polymarket/clob_adapter.py +76 -0
- tools/polymarket/models.py +182 -0
- tools/polymarket/service.py +2082 -0
- tools/self_env/__init__.py +61 -0
- tools/self_env/tool.py +274 -0
- tools/shell/__init__.py +80 -0
- tools/shell/backend_pool.py +118 -0
- tools/shell/discipline.py +62 -0
- tools/shell/executor.py +157 -0
- tools/shell/loopback_allow.py +87 -0
- tools/shell/process_registry.py +113 -0
- tools/shell/process_tool.py +131 -0
- tools/shell/state.py +129 -0
- tools/shell/tool.py +151 -0
- tools/task_tool.py +637 -0
- tools/twitter_tool.py +2086 -0
- tools/user_directory.py +179 -0
- tools/web_fetch/__init__.py +3 -0
- tools/web_fetch/fetcher.py +144 -0
- tools/web_fetch/render.py +44 -0
- tools/web_fetch/tool.py +60 -0
- tools/x402/__init__.py +60 -0
- tools/x402/client.py +47 -0
- tools/x402/invoice_tool.py +143 -0
- tools/x402/real_client.py +250 -0
- tools/x402/service.py +131 -0
- utils/README.md +498 -0
- utils/__init__.py +46 -0
- utils/auth_utils.py +114 -0
- utils/bounded_collections.py +162 -0
- utils/circuit_breaker.py +389 -0
- utils/gif_utils.py +435 -0
- utils/markdown_utils.py +291 -0
- utils/message_utils.py +147 -0
- utils/metrics.py +36 -0
- utils/path_validator.py +227 -0
- utils/rate_limit_manager.py +399 -0
- utils/result_size.py +296 -0
- utils/time_utils.py +206 -0
- utils/user_utils.py +188 -0
- webview/README.md +111 -0
- webview/RENAME_AND_ALIGN_HANDOFF.md +200 -0
- webview/__init__.py +8 -0
- webview/activity.py +636 -0
- webview/owner_auth.py +108 -0
- webview/pages.py +448 -0
- webview/repair_sessions.py +399 -0
- webview/server.py +4323 -0
- webview/server_launcher.py +112 -0
- webview/static/css/activity.css +89 -0
- webview/static/css/chat.css +1772 -0
- webview/static/css/components.css +1190 -0
- webview/static/css/config-panel.css +651 -0
- webview/static/css/pages/admin.css +766 -0
- webview/static/css/pages/profile.css +231 -0
- webview/static/css/pages/settings.css +297 -0
- webview/static/css/pages/signin.css +316 -0
- webview/static/css/style.css +4250 -0
- webview/static/css/variables.css +147 -0
- webview/static/css/workspace-fullwidth-fix.css +109 -0
- webview/static/img/favicon.ico +0 -0
- webview/static/js/activity.js +394 -0
- webview/static/js/admin/activity.js +186 -0
- webview/static/js/admin/dashboard.js +163 -0
- webview/static/js/admin/user_detail.js +400 -0
- webview/static/js/admin/users.js +174 -0
- webview/static/js/admin/utils.js +214 -0
- webview/static/js/chat.js +3178 -0
- webview/static/js/config-panel.js +522 -0
- webview/static/js/constants.js +20 -0
- webview/static/js/error-handler.js +226 -0
- webview/static/js/ethers.min.js +1 -0
- webview/static/js/event-filter.js +137 -0
- webview/static/js/event-store.js +351 -0
- webview/static/js/file-attachments.js +374 -0
- webview/static/js/file-loader.js +163 -0
- webview/static/js/index.js +103 -0
- webview/static/js/performance-utils.js +196 -0
- webview/static/js/profile.js +396 -0
- webview/static/js/screenshot.js +386 -0
- webview/static/js/session.js +1527 -0
- webview/static/js/settings.js +1288 -0
- webview/static/js/sidebar-data.js +766 -0
- webview/static/js/sidebar-toggle.js +296 -0
- webview/static/js/socket.io.min.js +7 -0
- webview/static/js/stats.js +355 -0
- webview/static/js/ui-utils.js +420 -0
- webview/static/js/workspace.js +966 -0
- webview/stats_service.py +613 -0
- webview/templates/__init__.py +1 -0
- webview/templates/__pycache__/__init__.cpython-311.pyc +0 -0
- webview/templates/activity.html +36 -0
- webview/templates/admin/activity.html +122 -0
- webview/templates/admin/dashboard.html +112 -0
- webview/templates/admin/user_detail.html +228 -0
- webview/templates/admin/users.html +105 -0
- webview/templates/autonomy.html +60 -0
- webview/templates/error.html +133 -0
- webview/templates/finance.html +90 -0
- webview/templates/identity.html +73 -0
- webview/templates/index.html +42 -0
- webview/templates/layout.html +125 -0
- webview/templates/memory.html +59 -0
- webview/templates/owner_login.html +15 -0
- webview/templates/profile.html +121 -0
- webview/templates/session.html +312 -0
- webview/templates/settings.html +534 -0
- webview/templates/sidebar.html +112 -0
- webview/templates/signin.html +213 -0
- webview/templates/status.html +14 -0
- webview/templates/system.html +45 -0
- webview/webgate.py +196 -0
tools/browser/context.py
ADDED
|
@@ -0,0 +1,1748 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Playwright browser on steroids.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import base64
|
|
7
|
+
import gc
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import time
|
|
13
|
+
import uuid
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import TYPE_CHECKING, Optional, TypedDict
|
|
16
|
+
from datetime import datetime
|
|
17
|
+
|
|
18
|
+
from playwright.async_api import TimeoutError
|
|
19
|
+
from playwright.async_api import Browser as PlaywrightBrowser
|
|
20
|
+
from playwright.async_api import (
|
|
21
|
+
BrowserContext as PlaywrightBrowserContext,
|
|
22
|
+
)
|
|
23
|
+
from playwright.async_api import (
|
|
24
|
+
ElementHandle,
|
|
25
|
+
FrameLocator,
|
|
26
|
+
Page,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
from tools.browser.views import (
|
|
30
|
+
BrowserError,
|
|
31
|
+
BrowserState,
|
|
32
|
+
TabInfo,
|
|
33
|
+
URLNotAllowedError,
|
|
34
|
+
)
|
|
35
|
+
from tools.dom.service import DomService
|
|
36
|
+
from tools.dom.views import DOMElementNode, SelectorMap
|
|
37
|
+
from utils.time_utils import time_execution_sync
|
|
38
|
+
|
|
39
|
+
if TYPE_CHECKING:
|
|
40
|
+
from tools.browser.browser import Browser
|
|
41
|
+
|
|
42
|
+
logger = logging.getLogger(__name__)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class BrowserContextWindowSize(TypedDict):
|
|
46
|
+
width: int
|
|
47
|
+
height: int
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class BrowserContextConfig:
|
|
52
|
+
"""
|
|
53
|
+
Configuration for the BrowserContext.
|
|
54
|
+
|
|
55
|
+
Default values:
|
|
56
|
+
cookies_file: None
|
|
57
|
+
Path to cookies file for persistence
|
|
58
|
+
|
|
59
|
+
disable_security: False
|
|
60
|
+
Disable browser security features (safe default - opt-in relaxations only)
|
|
61
|
+
|
|
62
|
+
minimum_wait_page_load_time: 0.5
|
|
63
|
+
Minimum time to wait before getting page state for LLM input
|
|
64
|
+
|
|
65
|
+
wait_for_network_idle_page_load_time: 1.0
|
|
66
|
+
Time to wait for network requests to finish before getting page state.
|
|
67
|
+
Lower values may result in incomplete page loads.
|
|
68
|
+
|
|
69
|
+
maximum_wait_page_load_time: 5.0
|
|
70
|
+
Maximum time to wait for page load before proceeding anyway
|
|
71
|
+
|
|
72
|
+
wait_between_actions: 1.0
|
|
73
|
+
Time to wait between multiple per step actions
|
|
74
|
+
|
|
75
|
+
browser_window_size: {
|
|
76
|
+
'width': 1280,
|
|
77
|
+
'height': 1100,
|
|
78
|
+
}
|
|
79
|
+
Default browser window size
|
|
80
|
+
|
|
81
|
+
no_viewport: False
|
|
82
|
+
Disable viewport
|
|
83
|
+
|
|
84
|
+
save_recording_path: None
|
|
85
|
+
Path to save video recordings
|
|
86
|
+
|
|
87
|
+
save_downloads_path: None
|
|
88
|
+
Path to save downloads to
|
|
89
|
+
|
|
90
|
+
trace_path: None
|
|
91
|
+
Path to save trace files. It will auto name the file with the TRACE_PATH/{context_id}.zip
|
|
92
|
+
|
|
93
|
+
locale: None
|
|
94
|
+
Specify user locale, for example en-GB, de-DE, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting rules. If not provided, defaults to the system default locale.
|
|
95
|
+
|
|
96
|
+
user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
|
|
97
|
+
custom user agent to use.
|
|
98
|
+
|
|
99
|
+
highlight_elements: True
|
|
100
|
+
Highlight elements in the DOM on the screen
|
|
101
|
+
|
|
102
|
+
viewport_expansion: 500
|
|
103
|
+
Viewport expansion in pixels. This amount will increase the number of elements which are included in the state what the LLM will see. If set to -1, all elements will be included (this leads to high token usage). If set to 0, only the elements which are visible in the viewport will be included.
|
|
104
|
+
|
|
105
|
+
allowed_domains: None
|
|
106
|
+
List of allowed domains that can be accessed. If None, all domains are allowed.
|
|
107
|
+
Example: ['example.com', 'api.example.com']
|
|
108
|
+
|
|
109
|
+
include_dynamic_attributes: bool = True
|
|
110
|
+
Include dynamic attributes in the CSS selector. If you want to reuse the css_selectors, it might be better to set this to False.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
cookies_file: str | None = None
|
|
114
|
+
minimum_wait_page_load_time: float = 0.5
|
|
115
|
+
wait_for_network_idle_page_load_time: float = 1
|
|
116
|
+
maximum_wait_page_load_time: float = 5
|
|
117
|
+
wait_between_actions: float = 1
|
|
118
|
+
|
|
119
|
+
disable_security: bool = False
|
|
120
|
+
|
|
121
|
+
browser_window_size: BrowserContextWindowSize = field(default_factory=lambda: {'width': 1280, 'height': 1100})
|
|
122
|
+
no_viewport: Optional[bool] = None
|
|
123
|
+
|
|
124
|
+
save_recording_path: str | None = None
|
|
125
|
+
save_downloads_path: str | None = None
|
|
126
|
+
trace_path: str | None = None
|
|
127
|
+
locale: str | None = None
|
|
128
|
+
user_agent: str = (
|
|
129
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
highlight_elements: bool = True
|
|
133
|
+
viewport_expansion: int = 500
|
|
134
|
+
allowed_domains: list[str] | None = None
|
|
135
|
+
include_dynamic_attributes: bool = True
|
|
136
|
+
|
|
137
|
+
_force_keep_context_alive: bool = False
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass
|
|
141
|
+
class BrowserSession:
|
|
142
|
+
context: PlaywrightBrowserContext
|
|
143
|
+
current_page: Page
|
|
144
|
+
cached_state: BrowserState
|
|
145
|
+
session_id: Optional[str] = None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class BrowserContext:
|
|
149
|
+
def __init__(
|
|
150
|
+
self,
|
|
151
|
+
browser: 'Browser',
|
|
152
|
+
config: BrowserContextConfig = BrowserContextConfig(),
|
|
153
|
+
session_id: Optional[str] = None
|
|
154
|
+
):
|
|
155
|
+
# Set up logger with session ID
|
|
156
|
+
logger_name = "task.context"
|
|
157
|
+
if session_id:
|
|
158
|
+
short_id = session_id[:8]
|
|
159
|
+
logger_name = f"{logger_name}[{short_id}]"
|
|
160
|
+
self.logger = logging.getLogger(logger_name)
|
|
161
|
+
|
|
162
|
+
self.browser = browser
|
|
163
|
+
self.config = config
|
|
164
|
+
self.session_id = session_id # Store the session ID
|
|
165
|
+
|
|
166
|
+
# Initialize these as None - they'll be set up when needed
|
|
167
|
+
self.session: BrowserSession | None = None
|
|
168
|
+
|
|
169
|
+
async def __aenter__(self):
|
|
170
|
+
"""Async context manager entry"""
|
|
171
|
+
await self._initialize_session()
|
|
172
|
+
return self
|
|
173
|
+
|
|
174
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
175
|
+
"""Async context manager exit - enhanced for proper WebSocket cleanup"""
|
|
176
|
+
self.logger.debug(f"BrowserContext.__aexit__ called with exc_type={exc_type}")
|
|
177
|
+
|
|
178
|
+
# First close all pages explicitly to ensure WebSocket connections close properly
|
|
179
|
+
try:
|
|
180
|
+
if self.session and self.session.context and self.session.context.pages:
|
|
181
|
+
for page in self.session.context.pages:
|
|
182
|
+
try:
|
|
183
|
+
await page.close(timeout=3000)
|
|
184
|
+
except Exception as e:
|
|
185
|
+
self.logger.debug(f"Error closing page during __aexit__: {e}")
|
|
186
|
+
except Exception as e:
|
|
187
|
+
self.logger.warning(f"Error closing pages during __aexit__: {e}")
|
|
188
|
+
|
|
189
|
+
# Then close the whole browser context
|
|
190
|
+
try:
|
|
191
|
+
await asyncio.wait_for(self.close(), timeout=15.0)
|
|
192
|
+
except asyncio.TimeoutError:
|
|
193
|
+
self.logger.warning("Context close timed out in __aexit__, resources may not be fully cleaned up")
|
|
194
|
+
except Exception as e:
|
|
195
|
+
self.logger.warning(f"Error during __aexit__ context close: {e}")
|
|
196
|
+
|
|
197
|
+
# Make sure any orphaned WebSocket connections are closed
|
|
198
|
+
try:
|
|
199
|
+
# Wait a moment for any connections to finish closing
|
|
200
|
+
await asyncio.sleep(0.5)
|
|
201
|
+
except Exception:
|
|
202
|
+
pass
|
|
203
|
+
|
|
204
|
+
async def close(self):
|
|
205
|
+
"""Close the browser instance and properly clean up all resources"""
|
|
206
|
+
self.logger.debug('Closing browser context')
|
|
207
|
+
|
|
208
|
+
try:
|
|
209
|
+
# check if already closed
|
|
210
|
+
if self.session is None:
|
|
211
|
+
return
|
|
212
|
+
|
|
213
|
+
# Save cookies before closing
|
|
214
|
+
try:
|
|
215
|
+
await self.save_cookies()
|
|
216
|
+
except Exception as e:
|
|
217
|
+
self.logger.debug(f'Failed to save cookies during closure: {e}')
|
|
218
|
+
|
|
219
|
+
# Save trace if configured
|
|
220
|
+
if self.config.trace_path:
|
|
221
|
+
try:
|
|
222
|
+
trace_path = os.path.join(self.config.trace_path, f'{self.session_id or uuid.uuid4()}.zip')
|
|
223
|
+
await self.session.context.tracing.stop(path=trace_path)
|
|
224
|
+
self.logger.debug(f'Saved trace to {trace_path}')
|
|
225
|
+
except Exception as e:
|
|
226
|
+
self.logger.debug(f'Failed to stop tracing: {e}')
|
|
227
|
+
|
|
228
|
+
# Close all pages first to ensure clean disconnection of websockets
|
|
229
|
+
try:
|
|
230
|
+
if self.session.context and self.session.context.pages:
|
|
231
|
+
for page in self.session.context.pages:
|
|
232
|
+
try:
|
|
233
|
+
await page.close(timeout=5000) # Higher timeout for page closing
|
|
234
|
+
except Exception as page_error:
|
|
235
|
+
self.logger.debug(f'Error closing page: {page_error}')
|
|
236
|
+
except Exception as pages_error:
|
|
237
|
+
self.logger.debug(f'Error closing pages: {pages_error}')
|
|
238
|
+
|
|
239
|
+
# Close the context more forcefully if needed
|
|
240
|
+
if not self.config._force_keep_context_alive:
|
|
241
|
+
try:
|
|
242
|
+
# Set a reasonable timeout for context closure
|
|
243
|
+
await asyncio.wait_for(self.session.context.close(), timeout=10.0)
|
|
244
|
+
self.logger.debug('Browser context closed successfully')
|
|
245
|
+
except asyncio.TimeoutError:
|
|
246
|
+
self.logger.warning('Context close timed out, attempting force close')
|
|
247
|
+
try:
|
|
248
|
+
# Force close using lower-level APIs if available
|
|
249
|
+
if hasattr(self.session.context, '_impl_obj'):
|
|
250
|
+
await self.session.context._impl_obj.close()
|
|
251
|
+
except Exception as force_close_error:
|
|
252
|
+
self.logger.warning(f'Force close failed: {force_close_error}')
|
|
253
|
+
except Exception as e:
|
|
254
|
+
self.logger.warning(f'Failed to close context gracefully: {e}')
|
|
255
|
+
# Try to force close anyway
|
|
256
|
+
try:
|
|
257
|
+
if hasattr(self.session.context, '_impl_obj'):
|
|
258
|
+
await self.session.context._impl_obj.close()
|
|
259
|
+
except Exception:
|
|
260
|
+
pass
|
|
261
|
+
except Exception as e:
|
|
262
|
+
self.logger.warning(f'Exception during browser context closure: {e}')
|
|
263
|
+
finally:
|
|
264
|
+
# Always ensure session is set to None
|
|
265
|
+
self.session = None
|
|
266
|
+
|
|
267
|
+
# Force garbage collection to release resources
|
|
268
|
+
try:
|
|
269
|
+
import gc
|
|
270
|
+
gc.collect()
|
|
271
|
+
except Exception:
|
|
272
|
+
pass
|
|
273
|
+
|
|
274
|
+
async def __aenter__(self):
|
|
275
|
+
"""Async context manager entry - allows `async with BrowserContext() as ctx:`"""
|
|
276
|
+
await self._initialize_session()
|
|
277
|
+
return self
|
|
278
|
+
|
|
279
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
280
|
+
"""Async context manager exit - ensures proper cleanup."""
|
|
281
|
+
await self.close()
|
|
282
|
+
return False # Don't suppress exceptions
|
|
283
|
+
|
|
284
|
+
def __del__(self):
|
|
285
|
+
"""Cleanup when object is destroyed through garbage collection.
|
|
286
|
+
|
|
287
|
+
WARNING: This is a last resort cleanup. Always prefer using:
|
|
288
|
+
- `async with BrowserContext() as context:` (context manager)
|
|
289
|
+
- Explicit `await context.close()` call
|
|
290
|
+
|
|
291
|
+
Async operations in __del__ are problematic and unreliable.
|
|
292
|
+
This method just logs a warning and nullifies references.
|
|
293
|
+
"""
|
|
294
|
+
if self.session is not None:
|
|
295
|
+
self.logger.warning(
|
|
296
|
+
'BrowserContext was not properly closed before being garbage collected. '
|
|
297
|
+
'Use "async with BrowserContext()" or call "await context.close()" explicitly.'
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
# Just nullify references - don't attempt async operations in __del__
|
|
301
|
+
# This prevents deadlocks and event loop issues
|
|
302
|
+
self.session = None
|
|
303
|
+
|
|
304
|
+
# Explicit garbage collection to help clean up
|
|
305
|
+
try:
|
|
306
|
+
import gc
|
|
307
|
+
gc.collect()
|
|
308
|
+
except Exception:
|
|
309
|
+
pass # Swallow exceptions in __del__
|
|
310
|
+
|
|
311
|
+
async def _initialize_session(self):
|
|
312
|
+
"""Initialize the browser session with improved WebSocket handling"""
|
|
313
|
+
self.logger.debug('Initializing browser context')
|
|
314
|
+
|
|
315
|
+
try:
|
|
316
|
+
playwright_browser = await self.browser.get_playwright_browser()
|
|
317
|
+
|
|
318
|
+
# Configure better connection parameters
|
|
319
|
+
context_options = {}
|
|
320
|
+
|
|
321
|
+
# Add connection timeout settings to prevent hanging connections
|
|
322
|
+
context_options["viewport"] = self.config.browser_window_size
|
|
323
|
+
context_options["no_viewport"] = False
|
|
324
|
+
context_options["user_agent"] = self.config.user_agent
|
|
325
|
+
context_options["java_script_enabled"] = True
|
|
326
|
+
context_options["bypass_csp"] = self.config.disable_security
|
|
327
|
+
context_options["ignore_https_errors"] = self.config.disable_security
|
|
328
|
+
context_options["record_video_dir"] = self.config.save_recording_path
|
|
329
|
+
context_options["record_video_size"] = self.config.browser_window_size
|
|
330
|
+
context_options["locale"] = self.config.locale
|
|
331
|
+
|
|
332
|
+
# Create context with improved options
|
|
333
|
+
context = await self._create_context(playwright_browser, context_options)
|
|
334
|
+
|
|
335
|
+
# Set timeouts after context creation
|
|
336
|
+
# These methods are supported on the context object
|
|
337
|
+
context.set_default_timeout(60000) # 60 seconds default timeout
|
|
338
|
+
context.set_default_navigation_timeout(60000) # 60 seconds for navigation
|
|
339
|
+
|
|
340
|
+
# Set up listeners and connection handlers
|
|
341
|
+
self._add_new_page_listener(context)
|
|
342
|
+
|
|
343
|
+
# Configure proper error handling for WebSocket connections
|
|
344
|
+
self._add_error_listeners(context)
|
|
345
|
+
|
|
346
|
+
# Check if there's an existing page we can use
|
|
347
|
+
existing_pages = context.pages
|
|
348
|
+
if existing_pages:
|
|
349
|
+
page = existing_pages[-1] # Use the last existing page
|
|
350
|
+
self.logger.debug('Reusing existing page')
|
|
351
|
+
else:
|
|
352
|
+
try:
|
|
353
|
+
page = await context.new_page()
|
|
354
|
+
self.logger.debug('Created new page')
|
|
355
|
+
except Exception as e:
|
|
356
|
+
self.logger.error(f"Error creating new page: {e}")
|
|
357
|
+
# Attempt to recover
|
|
358
|
+
self.logger.info("Attempting recovery by reusing context pages")
|
|
359
|
+
pages = context.pages
|
|
360
|
+
if not pages:
|
|
361
|
+
self.logger.error("No pages available for recovery")
|
|
362
|
+
raise
|
|
363
|
+
page = pages[0] # Use the first page
|
|
364
|
+
|
|
365
|
+
# Create a controller with the initialized services
|
|
366
|
+
initial_state = self._get_initial_state(page)
|
|
367
|
+
|
|
368
|
+
self.session = BrowserSession(
|
|
369
|
+
context=context,
|
|
370
|
+
current_page=page,
|
|
371
|
+
cached_state=initial_state,
|
|
372
|
+
session_id=self.session_id # Pass session ID to BrowserSession
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
# Set the page title to include the full session ID
|
|
376
|
+
if self.session_id:
|
|
377
|
+
try:
|
|
378
|
+
await page.evaluate(f'document.title = "SESSION {self.session_id}"')
|
|
379
|
+
except Exception as e:
|
|
380
|
+
self.logger.debug(f"Failed to set page title: {e}")
|
|
381
|
+
|
|
382
|
+
return self.session
|
|
383
|
+
except Exception as e:
|
|
384
|
+
self.logger.error(f"Failed to initialize browser session: {e}")
|
|
385
|
+
raise
|
|
386
|
+
|
|
387
|
+
def _add_error_listeners(self, context: PlaywrightBrowserContext):
|
|
388
|
+
"""Add error handlers to properly manage WebSocket connections"""
|
|
389
|
+
async def on_error(error):
|
|
390
|
+
self.logger.warning(f"Browser context error: {error}")
|
|
391
|
+
|
|
392
|
+
# Add error listener
|
|
393
|
+
context.on("error", on_error)
|
|
394
|
+
|
|
395
|
+
# Add close listener
|
|
396
|
+
async def on_close():
|
|
397
|
+
self.logger.debug("Browser context closed")
|
|
398
|
+
|
|
399
|
+
context.on("close", on_close)
|
|
400
|
+
|
|
401
|
+
async def _ssrf_route_guard(self, route):
|
|
402
|
+
"""Abort a top-level navigation whose (possibly redirected) URL resolves to an
|
|
403
|
+
internal / metadata address. Runs per request, so redirect hops are re-checked.
|
|
404
|
+
|
|
405
|
+
Only ``document`` requests are validated (the SSRF-to-metadata vector); all other
|
|
406
|
+
resource types continue immediately to keep interception overhead low. Fail-open
|
|
407
|
+
on the guard's own error (the initial-URL guard in browser.py still applies) so a
|
|
408
|
+
handler bug can't wedge all browsing.
|
|
409
|
+
"""
|
|
410
|
+
try:
|
|
411
|
+
request = route.request
|
|
412
|
+
if request.resource_type == 'document':
|
|
413
|
+
from tools.browser.browser import _check_url_ssrf
|
|
414
|
+
err = await asyncio.get_running_loop().run_in_executor(
|
|
415
|
+
None, _check_url_ssrf, request.url)
|
|
416
|
+
if err:
|
|
417
|
+
self.logger.warning(f"SSRF: aborting navigation to {request.url}: {err}")
|
|
418
|
+
await route.abort('blockedbyclient')
|
|
419
|
+
return
|
|
420
|
+
await route.continue_()
|
|
421
|
+
except Exception as e:
|
|
422
|
+
self.logger.debug(f"SSRF route guard error (continuing): {e}")
|
|
423
|
+
try:
|
|
424
|
+
await route.continue_()
|
|
425
|
+
except Exception:
|
|
426
|
+
pass
|
|
427
|
+
|
|
428
|
+
async def _create_context(self, browser: PlaywrightBrowser, context_options: dict = None):
|
|
429
|
+
"""Creates a new browser context with anti-detection measures and loads cookies if available."""
|
|
430
|
+
if context_options is None:
|
|
431
|
+
context_options = {}
|
|
432
|
+
|
|
433
|
+
if self.browser.config.cdp_url and len(browser.contexts) > 0:
|
|
434
|
+
context = browser.contexts[0]
|
|
435
|
+
elif self.browser.config.chrome_instance_path and len(browser.contexts) > 0:
|
|
436
|
+
# Connect to existing Chrome instance instead of creating new one
|
|
437
|
+
context = browser.contexts[0]
|
|
438
|
+
else:
|
|
439
|
+
# Original code for creating new context
|
|
440
|
+
context = await browser.new_context(**context_options)
|
|
441
|
+
|
|
442
|
+
# SSRF: validate EVERY top-level navigation at request time — including redirect
|
|
443
|
+
# hops — so a public URL that 302-redirects to a link-local / cloud-metadata
|
|
444
|
+
# address is aborted. page.goto only checks the initial URL; with route
|
|
445
|
+
# interception active, Playwright re-fires this handler for each redirect target.
|
|
446
|
+
# Gated by BROWSER_ALLOW_PRIVATE_URLS (same switch as the initial-URL guard).
|
|
447
|
+
if os.getenv('BROWSER_ALLOW_PRIVATE_URLS', 'false').strip().lower() not in ('1', 'true', 'yes', 'on'):
|
|
448
|
+
await context.route("**/*", self._ssrf_route_guard)
|
|
449
|
+
|
|
450
|
+
# Load cookies if they exist
|
|
451
|
+
if self.config.cookies_file and os.path.exists(self.config.cookies_file):
|
|
452
|
+
with open(self.config.cookies_file, 'r') as f:
|
|
453
|
+
cookies = json.load(f)
|
|
454
|
+
self.logger.info(f'Loaded {len(cookies)} cookies from {self.config.cookies_file}')
|
|
455
|
+
await context.add_cookies(cookies)
|
|
456
|
+
|
|
457
|
+
# Expose anti-detection scripts
|
|
458
|
+
await context.add_init_script(
|
|
459
|
+
"""
|
|
460
|
+
// Webdriver property
|
|
461
|
+
Object.defineProperty(navigator, 'webdriver', {
|
|
462
|
+
get: () => undefined
|
|
463
|
+
});
|
|
464
|
+
|
|
465
|
+
// Languages
|
|
466
|
+
Object.defineProperty(navigator, 'languages', {
|
|
467
|
+
get: () => ['en-US']
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
// Plugins
|
|
471
|
+
Object.defineProperty(navigator, 'plugins', {
|
|
472
|
+
get: () => [1, 2, 3, 4, 5]
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
// Chrome runtime
|
|
476
|
+
window.chrome = { runtime: {} };
|
|
477
|
+
|
|
478
|
+
// Permissions
|
|
479
|
+
const originalQuery = window.navigator.permissions.query;
|
|
480
|
+
window.navigator.permissions.query = (parameters) => (
|
|
481
|
+
parameters.name === 'notifications' ?
|
|
482
|
+
Promise.resolve({ state: Notification.permission }) :
|
|
483
|
+
originalQuery(parameters)
|
|
484
|
+
);
|
|
485
|
+
(function () {
|
|
486
|
+
const originalAttachShadow = Element.prototype.attachShadow;
|
|
487
|
+
Element.prototype.attachShadow = function attachShadow(options) {
|
|
488
|
+
return originalAttachShadow.call(this, { ...options, mode: "open" });
|
|
489
|
+
};
|
|
490
|
+
})();
|
|
491
|
+
"""
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
return context
|
|
495
|
+
|
|
496
|
+
def _add_new_page_listener(self, context: PlaywrightBrowserContext):
|
|
497
|
+
async def on_page(page: Page):
|
|
498
|
+
if self.browser.config.cdp_url:
|
|
499
|
+
await page.reload() # Reload the page to avoid timeout errors
|
|
500
|
+
await page.wait_for_load_state()
|
|
501
|
+
self.logger.debug(f'New page opened: {page.url}')
|
|
502
|
+
if self.session is not None:
|
|
503
|
+
self.session.current_page = page
|
|
504
|
+
|
|
505
|
+
context.on('page', on_page)
|
|
506
|
+
|
|
507
|
+
async def get_session(self) -> BrowserSession:
|
|
508
|
+
"""Lazy initialization of the browser and related components"""
|
|
509
|
+
if self.session is None:
|
|
510
|
+
return await self._initialize_session()
|
|
511
|
+
return self.session
|
|
512
|
+
|
|
513
|
+
async def get_current_page(self) -> Page:
|
|
514
|
+
"""Get the current page"""
|
|
515
|
+
session = await self.get_session()
|
|
516
|
+
return session.current_page
|
|
517
|
+
|
|
518
|
+
async def _wait_for_stable_network(self):
|
|
519
|
+
page = await self.get_current_page()
|
|
520
|
+
|
|
521
|
+
pending_requests = set()
|
|
522
|
+
last_activity = asyncio.get_event_loop().time()
|
|
523
|
+
|
|
524
|
+
# Define relevant resource types and content types
|
|
525
|
+
RELEVANT_RESOURCE_TYPES = {
|
|
526
|
+
'document',
|
|
527
|
+
'stylesheet',
|
|
528
|
+
'image',
|
|
529
|
+
'font',
|
|
530
|
+
'script',
|
|
531
|
+
'iframe',
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
RELEVANT_CONTENT_TYPES = {
|
|
535
|
+
'text/html',
|
|
536
|
+
'text/css',
|
|
537
|
+
'application/javascript',
|
|
538
|
+
'image/',
|
|
539
|
+
'font/',
|
|
540
|
+
'application/json',
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
# Additional patterns to filter out
|
|
544
|
+
IGNORED_URL_PATTERNS = {
|
|
545
|
+
# Analytics and tracking
|
|
546
|
+
'analytics',
|
|
547
|
+
'tracking',
|
|
548
|
+
'telemetry',
|
|
549
|
+
'beacon',
|
|
550
|
+
'metrics',
|
|
551
|
+
# Ad-related
|
|
552
|
+
'doubleclick',
|
|
553
|
+
'adsystem',
|
|
554
|
+
'adserver',
|
|
555
|
+
'advertising',
|
|
556
|
+
# Social media widgets
|
|
557
|
+
'facebook.com/plugins',
|
|
558
|
+
'platform.twitter',
|
|
559
|
+
'linkedin.com/embed',
|
|
560
|
+
# Live chat and support
|
|
561
|
+
'livechat',
|
|
562
|
+
'zendesk',
|
|
563
|
+
'intercom',
|
|
564
|
+
'crisp.chat',
|
|
565
|
+
'hotjar',
|
|
566
|
+
# Push notifications
|
|
567
|
+
'push-notifications',
|
|
568
|
+
'onesignal',
|
|
569
|
+
'pushwoosh',
|
|
570
|
+
# Background sync/heartbeat
|
|
571
|
+
'heartbeat',
|
|
572
|
+
'ping',
|
|
573
|
+
'alive',
|
|
574
|
+
# WebRTC and streaming
|
|
575
|
+
'webrtc',
|
|
576
|
+
'rtmp://',
|
|
577
|
+
'wss://',
|
|
578
|
+
# Common CDNs for dynamic content
|
|
579
|
+
'cloudfront.net',
|
|
580
|
+
'fastly.net',
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
async def on_request(request):
|
|
584
|
+
# Filter by resource type
|
|
585
|
+
if request.resource_type not in RELEVANT_RESOURCE_TYPES:
|
|
586
|
+
return
|
|
587
|
+
|
|
588
|
+
# Filter out streaming, websocket, and other real-time requests
|
|
589
|
+
if request.resource_type in {
|
|
590
|
+
'websocket',
|
|
591
|
+
'media',
|
|
592
|
+
'eventsource',
|
|
593
|
+
'manifest',
|
|
594
|
+
'other',
|
|
595
|
+
}:
|
|
596
|
+
return
|
|
597
|
+
|
|
598
|
+
# Filter out by URL patterns
|
|
599
|
+
url = request.url.lower()
|
|
600
|
+
if any(pattern in url for pattern in IGNORED_URL_PATTERNS):
|
|
601
|
+
return
|
|
602
|
+
|
|
603
|
+
# Filter out data URLs and blob URLs
|
|
604
|
+
if url.startswith(('data:', 'blob:')):
|
|
605
|
+
return
|
|
606
|
+
|
|
607
|
+
# Filter out requests with certain headers
|
|
608
|
+
headers = request.headers
|
|
609
|
+
if headers.get('purpose') == 'prefetch' or headers.get('sec-fetch-dest') in [
|
|
610
|
+
'video',
|
|
611
|
+
'audio',
|
|
612
|
+
]:
|
|
613
|
+
return
|
|
614
|
+
|
|
615
|
+
nonlocal last_activity
|
|
616
|
+
pending_requests.add(request)
|
|
617
|
+
last_activity = asyncio.get_event_loop().time()
|
|
618
|
+
# logger.debug(f'Request started: {request.url} ({request.resource_type})')
|
|
619
|
+
|
|
620
|
+
async def on_response(response):
|
|
621
|
+
request = response.request
|
|
622
|
+
if request not in pending_requests:
|
|
623
|
+
return
|
|
624
|
+
|
|
625
|
+
# Filter by content type if available
|
|
626
|
+
content_type = response.headers.get('content-type', '').lower()
|
|
627
|
+
|
|
628
|
+
# Skip if content type indicates streaming or real-time data
|
|
629
|
+
if any(
|
|
630
|
+
t in content_type
|
|
631
|
+
for t in [
|
|
632
|
+
'streaming',
|
|
633
|
+
'video',
|
|
634
|
+
'audio',
|
|
635
|
+
'webm',
|
|
636
|
+
'mp4',
|
|
637
|
+
'event-stream',
|
|
638
|
+
'websocket',
|
|
639
|
+
'protobuf',
|
|
640
|
+
]
|
|
641
|
+
):
|
|
642
|
+
pending_requests.remove(request)
|
|
643
|
+
return
|
|
644
|
+
|
|
645
|
+
# Only process relevant content types
|
|
646
|
+
if not any(ct in content_type for ct in RELEVANT_CONTENT_TYPES):
|
|
647
|
+
pending_requests.remove(request)
|
|
648
|
+
return
|
|
649
|
+
|
|
650
|
+
# Skip if response is too large (likely not essential for page load)
|
|
651
|
+
content_length = response.headers.get('content-length')
|
|
652
|
+
if content_length and int(content_length) > 5 * 1024 * 1024: # 5MB
|
|
653
|
+
pending_requests.remove(request)
|
|
654
|
+
return
|
|
655
|
+
|
|
656
|
+
nonlocal last_activity
|
|
657
|
+
pending_requests.remove(request)
|
|
658
|
+
last_activity = asyncio.get_event_loop().time()
|
|
659
|
+
# logger.debug(f'Request resolved: {request.url} ({content_type})')
|
|
660
|
+
|
|
661
|
+
# Attach event listeners
|
|
662
|
+
page.on('request', on_request)
|
|
663
|
+
page.on('response', on_response)
|
|
664
|
+
|
|
665
|
+
try:
|
|
666
|
+
# Wait for idle time
|
|
667
|
+
start_time = asyncio.get_event_loop().time()
|
|
668
|
+
while True:
|
|
669
|
+
await asyncio.sleep(0.1)
|
|
670
|
+
now = asyncio.get_event_loop().time()
|
|
671
|
+
if len(pending_requests) == 0 and (now - last_activity) >= self.config.wait_for_network_idle_page_load_time:
|
|
672
|
+
break
|
|
673
|
+
if now - start_time > self.config.maximum_wait_page_load_time:
|
|
674
|
+
self.logger.debug(
|
|
675
|
+
f'Network timeout after {self.config.maximum_wait_page_load_time}s with {len(pending_requests)} '
|
|
676
|
+
f'pending requests: {[r.url for r in pending_requests]}'
|
|
677
|
+
)
|
|
678
|
+
break
|
|
679
|
+
|
|
680
|
+
finally:
|
|
681
|
+
# Clean up event listeners
|
|
682
|
+
page.remove_listener('request', on_request)
|
|
683
|
+
page.remove_listener('response', on_response)
|
|
684
|
+
|
|
685
|
+
self.logger.debug(f'Network stabilized for {self.config.wait_for_network_idle_page_load_time} seconds')
|
|
686
|
+
|
|
687
|
+
async def _wait_for_page_and_frames_load(self, timeout_overwrite: float | None = None):
|
|
688
|
+
"""
|
|
689
|
+
Ensures page is fully loaded before continuing.
|
|
690
|
+
Waits for either network to be idle or minimum WAIT_TIME, whichever is longer.
|
|
691
|
+
Also checks if the loaded URL is allowed.
|
|
692
|
+
"""
|
|
693
|
+
# Start timing
|
|
694
|
+
start_time = time.time()
|
|
695
|
+
|
|
696
|
+
# Wait for page load
|
|
697
|
+
try:
|
|
698
|
+
await self._wait_for_stable_network()
|
|
699
|
+
|
|
700
|
+
# Check if the loaded URL is allowed
|
|
701
|
+
page = await self.get_current_page()
|
|
702
|
+
await self._check_and_handle_navigation(page)
|
|
703
|
+
except URLNotAllowedError as e:
|
|
704
|
+
raise e
|
|
705
|
+
except Exception:
|
|
706
|
+
self.logger.warning('Page load failed, continuing...')
|
|
707
|
+
pass
|
|
708
|
+
|
|
709
|
+
# Calculate remaining time to meet minimum WAIT_TIME
|
|
710
|
+
elapsed = time.time() - start_time
|
|
711
|
+
remaining = max((timeout_overwrite or self.config.minimum_wait_page_load_time) - elapsed, 0)
|
|
712
|
+
|
|
713
|
+
self.logger.debug(f'--Page loaded in {elapsed:.2f} seconds, waiting for additional {remaining:.2f} seconds')
|
|
714
|
+
|
|
715
|
+
# Sleep remaining time if needed
|
|
716
|
+
if remaining > 0:
|
|
717
|
+
await asyncio.sleep(remaining)
|
|
718
|
+
|
|
719
|
+
def _is_url_allowed(self, url: str) -> bool:
|
|
720
|
+
"""Check if a URL is allowed based on the whitelist configuration."""
|
|
721
|
+
if not self.config.allowed_domains:
|
|
722
|
+
return True
|
|
723
|
+
|
|
724
|
+
try:
|
|
725
|
+
from urllib.parse import urlparse
|
|
726
|
+
|
|
727
|
+
parsed_url = urlparse(url)
|
|
728
|
+
domain = parsed_url.netloc.lower()
|
|
729
|
+
|
|
730
|
+
# Remove port number if present
|
|
731
|
+
if ':' in domain:
|
|
732
|
+
domain = domain.split(':')[0]
|
|
733
|
+
|
|
734
|
+
# Check if domain matches any allowed domain pattern
|
|
735
|
+
return any(
|
|
736
|
+
domain == allowed_domain.lower() or domain.endswith('.' + allowed_domain.lower())
|
|
737
|
+
for allowed_domain in self.config.allowed_domains
|
|
738
|
+
)
|
|
739
|
+
except Exception as e:
|
|
740
|
+
self.logger.error(f'Error checking URL allowlist: {str(e)}')
|
|
741
|
+
return False
|
|
742
|
+
|
|
743
|
+
async def _check_and_handle_navigation(self, page: Page) -> None:
|
|
744
|
+
"""Check if current page URL is allowed and handle if not."""
|
|
745
|
+
if not self._is_url_allowed(page.url):
|
|
746
|
+
self.logger.warning(f'Navigation to non-allowed URL detected: {page.url}')
|
|
747
|
+
try:
|
|
748
|
+
await self.go_back()
|
|
749
|
+
except Exception as e:
|
|
750
|
+
self.logger.error(f'Failed to go back after detecting non-allowed URL: {str(e)}')
|
|
751
|
+
raise URLNotAllowedError(f'Navigation to non-allowed URL: {page.url}')
|
|
752
|
+
|
|
753
|
+
async def navigate_to(self, url: str):
|
|
754
|
+
"""Navigate to a URL"""
|
|
755
|
+
if not self._is_url_allowed(url):
|
|
756
|
+
raise BrowserError(f'Navigation to non-allowed URL: {url}')
|
|
757
|
+
|
|
758
|
+
page = await self.get_current_page()
|
|
759
|
+
await page.goto(url)
|
|
760
|
+
await page.wait_for_load_state()
|
|
761
|
+
|
|
762
|
+
async def refresh_page(self):
|
|
763
|
+
"""Refresh the current page"""
|
|
764
|
+
page = await self.get_current_page()
|
|
765
|
+
await page.reload()
|
|
766
|
+
await page.wait_for_load_state()
|
|
767
|
+
|
|
768
|
+
async def go_back(self):
|
|
769
|
+
"""Navigate back in history"""
|
|
770
|
+
page = await self.get_current_page()
|
|
771
|
+
try:
|
|
772
|
+
# 10 ms timeout
|
|
773
|
+
await page.go_back(timeout=10, wait_until='domcontentloaded')
|
|
774
|
+
# await self._wait_for_page_and_frames_load(timeout_overwrite=1.0)
|
|
775
|
+
except Exception as e:
|
|
776
|
+
# Continue even if its not fully loaded, because we wait later for the page to load
|
|
777
|
+
self.logger.debug(f'During go_back: {e}')
|
|
778
|
+
|
|
779
|
+
async def go_forward(self):
|
|
780
|
+
"""Navigate forward in history"""
|
|
781
|
+
page = await self.get_current_page()
|
|
782
|
+
try:
|
|
783
|
+
await page.go_forward(timeout=10, wait_until='domcontentloaded')
|
|
784
|
+
except Exception as e:
|
|
785
|
+
# Continue even if its not fully loaded, because we wait later for the page to load
|
|
786
|
+
self.logger.debug(f'During go_forward: {e}')
|
|
787
|
+
pass
|
|
788
|
+
|
|
789
|
+
async def close_current_tab(self):
|
|
790
|
+
"""Close the current tab"""
|
|
791
|
+
session = await self.get_session()
|
|
792
|
+
page = session.current_page
|
|
793
|
+
await page.close()
|
|
794
|
+
|
|
795
|
+
# Switch to the first available tab if any exist
|
|
796
|
+
if session.context.pages:
|
|
797
|
+
await self.switch_to_tab(0)
|
|
798
|
+
|
|
799
|
+
# otherwise the browser will be closed
|
|
800
|
+
|
|
801
|
+
async def get_page_html(self) -> str:
|
|
802
|
+
"""Get the current page HTML content"""
|
|
803
|
+
page = await self.get_current_page()
|
|
804
|
+
return await page.content()
|
|
805
|
+
|
|
806
|
+
async def execute_javascript(self, script: str):
|
|
807
|
+
"""Execute JavaScript code on the page"""
|
|
808
|
+
page = await self.get_current_page()
|
|
809
|
+
return await page.evaluate(script)
|
|
810
|
+
|
|
811
|
+
# Removed decorator - time_execution_async doesn't exist yet
|
|
812
|
+
async def get_state(self, capture_screenshot: bool = True) -> BrowserState:
|
|
813
|
+
"""Get the current state of the browser.
|
|
814
|
+
|
|
815
|
+
Args:
|
|
816
|
+
capture_screenshot: Whether to capture a screenshot. Set to False for non-vision
|
|
817
|
+
tasks to save ~100-200ms per step. Default True for backward compat.
|
|
818
|
+
|
|
819
|
+
Returns:
|
|
820
|
+
BrowserState with current page information
|
|
821
|
+
"""
|
|
822
|
+
try:
|
|
823
|
+
await self._wait_for_page_and_frames_load()
|
|
824
|
+
session = await self.get_session()
|
|
825
|
+
|
|
826
|
+
try:
|
|
827
|
+
updated_state = await self._update_state(capture_screenshot=capture_screenshot)
|
|
828
|
+
session.cached_state = updated_state
|
|
829
|
+
except Exception as e:
|
|
830
|
+
logger.error(f"Error updating state: {str(e)}")
|
|
831
|
+
# If we have a cached state, use it instead of failing
|
|
832
|
+
if hasattr(session, 'cached_state') and session.cached_state:
|
|
833
|
+
logger.debug(f"Using cached state instead due to error")
|
|
834
|
+
# Mark this state as cached so agent can handle it differently
|
|
835
|
+
if not hasattr(session.cached_state, '_is_cached'):
|
|
836
|
+
session.cached_state._is_cached = True
|
|
837
|
+
return session.cached_state
|
|
838
|
+
else:
|
|
839
|
+
# Create minimal valid state
|
|
840
|
+
page = await self.get_current_page()
|
|
841
|
+
minimal_root_node = DOMElementNode(
|
|
842
|
+
tag_name="html",
|
|
843
|
+
is_visible=True,
|
|
844
|
+
parent=None,
|
|
845
|
+
xpath="",
|
|
846
|
+
attributes={},
|
|
847
|
+
children=[]
|
|
848
|
+
)
|
|
849
|
+
session.cached_state = BrowserState(
|
|
850
|
+
element_tree=minimal_root_node,
|
|
851
|
+
selector_map={},
|
|
852
|
+
url=page.url if page else "",
|
|
853
|
+
title=await page.title() if page else "",
|
|
854
|
+
tabs=await self.get_tabs_info() if page else [],
|
|
855
|
+
screenshot=None
|
|
856
|
+
)
|
|
857
|
+
# Mark as cached
|
|
858
|
+
session.cached_state._is_cached = True
|
|
859
|
+
|
|
860
|
+
# Save cookies if a file is specified
|
|
861
|
+
if self.config.cookies_file:
|
|
862
|
+
asyncio.create_task(self.save_cookies())
|
|
863
|
+
|
|
864
|
+
return session.cached_state
|
|
865
|
+
except Exception as e:
|
|
866
|
+
logger.error(f"Critical error in get_state: {str(e)}")
|
|
867
|
+
# Create minimal valid state as last resort
|
|
868
|
+
minimal_root_node = DOMElementNode(
|
|
869
|
+
tag_name="html",
|
|
870
|
+
is_visible=True,
|
|
871
|
+
parent=None,
|
|
872
|
+
xpath="",
|
|
873
|
+
attributes={},
|
|
874
|
+
children=[]
|
|
875
|
+
)
|
|
876
|
+
return BrowserState(
|
|
877
|
+
element_tree=minimal_root_node,
|
|
878
|
+
selector_map={},
|
|
879
|
+
url="",
|
|
880
|
+
title="Error Page",
|
|
881
|
+
tabs=[],
|
|
882
|
+
screenshot=None
|
|
883
|
+
)
|
|
884
|
+
|
|
885
|
+
async def _update_state(self, focus_element: int = -1, capture_screenshot: bool = True) -> BrowserState:
|
|
886
|
+
"""Update and return state.
|
|
887
|
+
|
|
888
|
+
Args:
|
|
889
|
+
focus_element: Element index to focus on (default -1 = none)
|
|
890
|
+
capture_screenshot: Whether to capture screenshot. Set False for non-vision tasks
|
|
891
|
+
to save ~100-200ms per step.
|
|
892
|
+
|
|
893
|
+
Returns:
|
|
894
|
+
Updated BrowserState
|
|
895
|
+
"""
|
|
896
|
+
session = await self.get_session()
|
|
897
|
+
|
|
898
|
+
# Check if current page is still valid, if not switch to another available page
|
|
899
|
+
try:
|
|
900
|
+
page = await self.get_current_page()
|
|
901
|
+
# Test if page is still accessible
|
|
902
|
+
await page.evaluate('1')
|
|
903
|
+
except Exception as e:
|
|
904
|
+
logger.debug(f'Current page is no longer accessible: {str(e)}')
|
|
905
|
+
# Get all available pages
|
|
906
|
+
pages = session.context.pages
|
|
907
|
+
if pages:
|
|
908
|
+
session.current_page = pages[-1]
|
|
909
|
+
page = session.current_page
|
|
910
|
+
logger.debug(f'Switched to page: {await page.title()}')
|
|
911
|
+
else:
|
|
912
|
+
raise BrowserError('Browser closed: no valid pages available')
|
|
913
|
+
|
|
914
|
+
try:
|
|
915
|
+
await self.remove_highlights()
|
|
916
|
+
dom_service = DomService(page)
|
|
917
|
+
content = await dom_service.get_clickable_elements(
|
|
918
|
+
focus_element=focus_element,
|
|
919
|
+
viewport_expansion=self.config.viewport_expansion,
|
|
920
|
+
highlight_elements=self.config.highlight_elements,
|
|
921
|
+
)
|
|
922
|
+
|
|
923
|
+
# FIX (Dec 2025): Only capture screenshot when vision is needed
|
|
924
|
+
# This saves ~100-200ms per step for non-vision tasks
|
|
925
|
+
screenshot_b64 = None
|
|
926
|
+
if capture_screenshot:
|
|
927
|
+
screenshot_b64 = await self.take_screenshot()
|
|
928
|
+
else:
|
|
929
|
+
logger.debug("Skipping screenshot capture (vision disabled)")
|
|
930
|
+
|
|
931
|
+
pixels_above, pixels_below = await self.get_scroll_info(page)
|
|
932
|
+
|
|
933
|
+
self.current_state = BrowserState(
|
|
934
|
+
element_tree=content.element_tree,
|
|
935
|
+
selector_map=content.selector_map,
|
|
936
|
+
url=page.url,
|
|
937
|
+
title=await page.title(),
|
|
938
|
+
tabs=await self.get_tabs_info(),
|
|
939
|
+
screenshot=screenshot_b64,
|
|
940
|
+
pixels_above=pixels_above,
|
|
941
|
+
pixels_below=pixels_below,
|
|
942
|
+
)
|
|
943
|
+
|
|
944
|
+
return self.current_state
|
|
945
|
+
except Exception as e:
|
|
946
|
+
logger.error(f'Failed to update state: {str(e)}')
|
|
947
|
+
# Return last known good state if available
|
|
948
|
+
if hasattr(self, 'current_state'):
|
|
949
|
+
return self.current_state
|
|
950
|
+
raise
|
|
951
|
+
|
|
952
|
+
# region - Browser Actions
|
|
953
|
+
|
|
954
|
+
async def take_screenshot(self, full_page: bool = False) -> str:
|
|
955
|
+
"""
|
|
956
|
+
Returns a base64 encoded screenshot of the current page.
|
|
957
|
+
Includes error handling and retries for more reliable screenshot capture.
|
|
958
|
+
"""
|
|
959
|
+
try:
|
|
960
|
+
page = await self.get_current_page()
|
|
961
|
+
|
|
962
|
+
# Try a more reliable screenshot approach
|
|
963
|
+
try:
|
|
964
|
+
# First attempt with standard approach
|
|
965
|
+
screenshot = await page.screenshot(
|
|
966
|
+
full_page=full_page,
|
|
967
|
+
animations='disabled',
|
|
968
|
+
timeout=10000 # Longer timeout for screenshot capture
|
|
969
|
+
)
|
|
970
|
+
|
|
971
|
+
# Verify the screenshot has content
|
|
972
|
+
if not screenshot or len(screenshot) < 100:
|
|
973
|
+
logger.warning("Screenshot appears to be empty or too small, retrying with alternative method")
|
|
974
|
+
# Try alternative approach - capture viewport only
|
|
975
|
+
screenshot = await page.screenshot(
|
|
976
|
+
full_page=False,
|
|
977
|
+
animations='disabled',
|
|
978
|
+
timeout=10000
|
|
979
|
+
)
|
|
980
|
+
|
|
981
|
+
except Exception as screenshot_error:
|
|
982
|
+
logger.error(f"Error taking screenshot with standard method: {screenshot_error}")
|
|
983
|
+
# Fallback method
|
|
984
|
+
try:
|
|
985
|
+
screenshot = await page.screenshot(
|
|
986
|
+
full_page=False,
|
|
987
|
+
animations='disabled',
|
|
988
|
+
timeout=10000
|
|
989
|
+
)
|
|
990
|
+
except Exception as fallback_error:
|
|
991
|
+
logger.error(f"Fallback screenshot method also failed: {fallback_error}")
|
|
992
|
+
# Return empty string if all screenshot methods fail
|
|
993
|
+
return ""
|
|
994
|
+
|
|
995
|
+
screenshot_b64 = base64.b64encode(screenshot).decode('utf-8')
|
|
996
|
+
|
|
997
|
+
# Log the screenshot size to help with debugging
|
|
998
|
+
logger.debug(f"Screenshot captured successfully - size: {len(screenshot_b64)} bytes")
|
|
999
|
+
|
|
1000
|
+
# If we have a session ID, save the screenshot to the session directory
|
|
1001
|
+
session = await self.get_session()
|
|
1002
|
+
if hasattr(session, 'session_id') and session.session_id:
|
|
1003
|
+
try:
|
|
1004
|
+
# Try to use PathManager for consistent path handling
|
|
1005
|
+
try:
|
|
1006
|
+
from agents.task.path import pm
|
|
1007
|
+
path_manager = pm()
|
|
1008
|
+
|
|
1009
|
+
# Get screenshots directory for this session
|
|
1010
|
+
screenshots_dir = path_manager.get_subdir(session.session_id, "screenshots")
|
|
1011
|
+
|
|
1012
|
+
# Ensure the directory exists
|
|
1013
|
+
screenshots_dir = str(screenshots_dir)
|
|
1014
|
+
os.makedirs(screenshots_dir, exist_ok=True)
|
|
1015
|
+
|
|
1016
|
+
except (ImportError, ValueError, Exception) as e:
|
|
1017
|
+
logger.warning(f"PathManager not available: {str(e)}")
|
|
1018
|
+
|
|
1019
|
+
# Fallback to direct path construction
|
|
1020
|
+
screenshots_dir = os.path.join("data", "auto", session.session_id, "screenshots")
|
|
1021
|
+
|
|
1022
|
+
# Check if screenshots_dir has duplicated session ID to avoid nesting
|
|
1023
|
+
pattern = f"data{os.path.sep}auto{os.path.sep}{session.session_id}"
|
|
1024
|
+
if screenshots_dir.count(pattern) > 1:
|
|
1025
|
+
# Fix path by removing the duplication
|
|
1026
|
+
parts = screenshots_dir.split(pattern)
|
|
1027
|
+
screenshots_dir = pattern.join([parts[0], parts[-1]])
|
|
1028
|
+
logger.warning(f"Fixed duplicate session paths: {screenshots_dir}")
|
|
1029
|
+
|
|
1030
|
+
# Ensure the directory exists
|
|
1031
|
+
os.makedirs(screenshots_dir, exist_ok=True)
|
|
1032
|
+
|
|
1033
|
+
# Get current page URL and encode it for the filename
|
|
1034
|
+
current_url = page.url
|
|
1035
|
+
# Truncate and encode URL for filename
|
|
1036
|
+
url_for_filename = ""
|
|
1037
|
+
if current_url:
|
|
1038
|
+
# Limit URL length and remove unsafe characters
|
|
1039
|
+
import urllib.parse
|
|
1040
|
+
import re
|
|
1041
|
+
# Keep just the domain and first part of path
|
|
1042
|
+
url_parts = urllib.parse.urlparse(current_url)
|
|
1043
|
+
shorter_url = f"{url_parts.netloc}{url_parts.path[:30]}"
|
|
1044
|
+
# Clean URL for safe filename
|
|
1045
|
+
url_for_filename = re.sub(r'[^\w\-_]', '_', shorter_url)[:50]
|
|
1046
|
+
# Add leading underscore for parsing
|
|
1047
|
+
url_for_filename = f"_{url_for_filename}"
|
|
1048
|
+
|
|
1049
|
+
# Generate filename with timestamp
|
|
1050
|
+
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
|
|
1051
|
+
fullpage_suffix = "_fullpage" if full_page else ""
|
|
1052
|
+
filename = f"screenshot_{timestamp}{fullpage_suffix}{url_for_filename}.png"
|
|
1053
|
+
|
|
1054
|
+
# Create file path
|
|
1055
|
+
if 'path_manager' in locals():
|
|
1056
|
+
file_path = path_manager.create_file_path(
|
|
1057
|
+
session.session_id,
|
|
1058
|
+
"screenshots",
|
|
1059
|
+
filename
|
|
1060
|
+
)
|
|
1061
|
+
else:
|
|
1062
|
+
file_path = os.path.join(screenshots_dir, filename)
|
|
1063
|
+
|
|
1064
|
+
# Save raw screenshot bytes
|
|
1065
|
+
with open(file_path, "wb") as f:
|
|
1066
|
+
f.write(screenshot)
|
|
1067
|
+
|
|
1068
|
+
logger.debug(f"Saved screenshot directly to {file_path}")
|
|
1069
|
+
except Exception as save_error:
|
|
1070
|
+
logger.error(f"Failed to save screenshot to disk: {save_error}")
|
|
1071
|
+
|
|
1072
|
+
return screenshot_b64
|
|
1073
|
+
except Exception as e:
|
|
1074
|
+
logger.error(f"Failed to take screenshot: {e}")
|
|
1075
|
+
return "" # Return empty string on failure
|
|
1076
|
+
|
|
1077
|
+
async def take_and_save_fullpage_screenshot(self) -> Optional[str]:
|
|
1078
|
+
"""
|
|
1079
|
+
Takes a fullpage screenshot and saves it directly to the session directory.
|
|
1080
|
+
Returns the path to the saved file, or None if saving failed.
|
|
1081
|
+
"""
|
|
1082
|
+
try:
|
|
1083
|
+
page = await self.get_current_page()
|
|
1084
|
+
session = await self.get_session()
|
|
1085
|
+
|
|
1086
|
+
if not hasattr(session, 'session_id') or not session.session_id:
|
|
1087
|
+
logger.warning("Cannot save fullpage screenshot: no session ID available")
|
|
1088
|
+
return None
|
|
1089
|
+
|
|
1090
|
+
# Try to use SessionManager for consistent path handling
|
|
1091
|
+
try:
|
|
1092
|
+
from agents.task.path import pm
|
|
1093
|
+
path_manager = pm()
|
|
1094
|
+
|
|
1095
|
+
# Get screenshots directory for this session
|
|
1096
|
+
screenshots_dir = path_manager.get_subdir(session.session_id, "screenshots")
|
|
1097
|
+
|
|
1098
|
+
# Ensure the directory exists
|
|
1099
|
+
screenshots_dir = str(screenshots_dir)
|
|
1100
|
+
os.makedirs(screenshots_dir, exist_ok=True)
|
|
1101
|
+
|
|
1102
|
+
except (ImportError, ValueError, Exception) as e:
|
|
1103
|
+
logger.warning(f"PathManager not available for fullpage screenshot: {str(e)}")
|
|
1104
|
+
|
|
1105
|
+
# Fallback to direct path construction
|
|
1106
|
+
screenshots_dir = os.path.join("data", "auto", session.session_id, "screenshots")
|
|
1107
|
+
|
|
1108
|
+
# Check if screenshots_dir has duplicated session ID to avoid nesting
|
|
1109
|
+
pattern = f"data{os.path.sep}auto{os.path.sep}{session.session_id}"
|
|
1110
|
+
if screenshots_dir.count(pattern) > 1:
|
|
1111
|
+
# Fix path by removing the duplication
|
|
1112
|
+
parts = screenshots_dir.split(pattern)
|
|
1113
|
+
screenshots_dir = pattern.join([parts[0], parts[-1]])
|
|
1114
|
+
logger.warning(f"Fixed duplicate session paths in fullpage: {screenshots_dir}")
|
|
1115
|
+
|
|
1116
|
+
# Ensure the directory exists
|
|
1117
|
+
os.makedirs(screenshots_dir, exist_ok=True)
|
|
1118
|
+
|
|
1119
|
+
# Generate filename with timestamp
|
|
1120
|
+
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
|
|
1121
|
+
filename = f"screenshot_{timestamp}_fullpage.png"
|
|
1122
|
+
|
|
1123
|
+
# Create file path
|
|
1124
|
+
if 'path_manager' in locals():
|
|
1125
|
+
file_path = path_manager.create_file_path(
|
|
1126
|
+
session.session_id,
|
|
1127
|
+
"screenshots",
|
|
1128
|
+
filename
|
|
1129
|
+
)
|
|
1130
|
+
else:
|
|
1131
|
+
file_path = os.path.join(screenshots_dir, filename)
|
|
1132
|
+
|
|
1133
|
+
# Take fullpage screenshot
|
|
1134
|
+
try:
|
|
1135
|
+
# Use a longer timeout for fullpage screenshots
|
|
1136
|
+
screenshot = await page.screenshot(
|
|
1137
|
+
full_page=True,
|
|
1138
|
+
animations='disabled',
|
|
1139
|
+
timeout=15000
|
|
1140
|
+
)
|
|
1141
|
+
|
|
1142
|
+
# Save screenshot directly to file
|
|
1143
|
+
with open(file_path, "wb") as f:
|
|
1144
|
+
f.write(screenshot)
|
|
1145
|
+
|
|
1146
|
+
logger.debug(f"Saved fullpage screenshot to {file_path}")
|
|
1147
|
+
return file_path
|
|
1148
|
+
except Exception as screenshot_error:
|
|
1149
|
+
logger.error(f"Error taking fullpage screenshot: {screenshot_error}")
|
|
1150
|
+
return None
|
|
1151
|
+
except Exception as e:
|
|
1152
|
+
logger.error(f"Failed to take and save fullpage screenshot: {e}")
|
|
1153
|
+
return None
|
|
1154
|
+
|
|
1155
|
+
async def remove_highlights(self):
|
|
1156
|
+
"""
|
|
1157
|
+
Removes all highlight overlays and labels created by the highlightElement function.
|
|
1158
|
+
Handles cases where the page might be closed or inaccessible.
|
|
1159
|
+
"""
|
|
1160
|
+
try:
|
|
1161
|
+
page = await self.get_current_page()
|
|
1162
|
+
await page.evaluate(
|
|
1163
|
+
"""
|
|
1164
|
+
try {
|
|
1165
|
+
// Remove the highlight container and all its contents
|
|
1166
|
+
const container = document.getElementById('playwright-highlight-container');
|
|
1167
|
+
if (container) {
|
|
1168
|
+
container.remove();
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
// Remove highlight attributes from elements
|
|
1172
|
+
const highlightedElements = document.querySelectorAll('[browser-user-highlight-id^="playwright-highlight-"]');
|
|
1173
|
+
highlightedElements.forEach(el => {
|
|
1174
|
+
el.removeAttribute('browser-user-highlight-id');
|
|
1175
|
+
});
|
|
1176
|
+
} catch (e) {
|
|
1177
|
+
console.error('Failed to remove highlights:', e);
|
|
1178
|
+
}
|
|
1179
|
+
"""
|
|
1180
|
+
)
|
|
1181
|
+
except Exception as e:
|
|
1182
|
+
logger.debug(f'Failed to remove highlights (this is usually ok): {str(e)}')
|
|
1183
|
+
# Don't raise the error since this is not critical functionality
|
|
1184
|
+
pass
|
|
1185
|
+
|
|
1186
|
+
# endregion
|
|
1187
|
+
|
|
1188
|
+
# region - User Actions
|
|
1189
|
+
|
|
1190
|
+
@classmethod
|
|
1191
|
+
def _convert_simple_xpath_to_css_selector(cls, xpath: str) -> str:
|
|
1192
|
+
"""Converts simple XPath expressions to CSS selectors."""
|
|
1193
|
+
if not xpath:
|
|
1194
|
+
return ''
|
|
1195
|
+
|
|
1196
|
+
# Remove leading slash if present
|
|
1197
|
+
xpath = xpath.lstrip('/')
|
|
1198
|
+
|
|
1199
|
+
# Split into parts
|
|
1200
|
+
parts = xpath.split('/')
|
|
1201
|
+
css_parts = []
|
|
1202
|
+
|
|
1203
|
+
for part in parts:
|
|
1204
|
+
if not part:
|
|
1205
|
+
continue
|
|
1206
|
+
|
|
1207
|
+
# Handle index notation [n]
|
|
1208
|
+
if '[' in part:
|
|
1209
|
+
base_part = part[: part.find('[')]
|
|
1210
|
+
index_part = part[part.find('[') :]
|
|
1211
|
+
|
|
1212
|
+
# Handle multiple indices
|
|
1213
|
+
indices = [i.strip('[]') for i in index_part.split(']')[:-1]]
|
|
1214
|
+
|
|
1215
|
+
for idx in indices:
|
|
1216
|
+
try:
|
|
1217
|
+
# Handle numeric indices
|
|
1218
|
+
if idx.isdigit():
|
|
1219
|
+
index = int(idx) - 1
|
|
1220
|
+
base_part += f':nth-of-type({index + 1})'
|
|
1221
|
+
# Handle last() function
|
|
1222
|
+
elif idx == 'last()':
|
|
1223
|
+
base_part += ':last-of-type'
|
|
1224
|
+
# Handle position() functions
|
|
1225
|
+
elif 'position()' in idx:
|
|
1226
|
+
if '>1' in idx:
|
|
1227
|
+
base_part += ':nth-of-type(n+2)'
|
|
1228
|
+
except ValueError:
|
|
1229
|
+
continue
|
|
1230
|
+
|
|
1231
|
+
css_parts.append(base_part)
|
|
1232
|
+
else:
|
|
1233
|
+
css_parts.append(part)
|
|
1234
|
+
|
|
1235
|
+
base_selector = ' > '.join(css_parts)
|
|
1236
|
+
return base_selector
|
|
1237
|
+
|
|
1238
|
+
@classmethod
|
|
1239
|
+
def _enhanced_css_selector_for_element(cls, element: DOMElementNode, include_dynamic_attributes: bool = True) -> str:
|
|
1240
|
+
"""
|
|
1241
|
+
Creates a CSS selector for a DOM element, handling various edge cases and special characters.
|
|
1242
|
+
|
|
1243
|
+
Args:
|
|
1244
|
+
element: The DOM element to create a selector for
|
|
1245
|
+
|
|
1246
|
+
Returns:
|
|
1247
|
+
A valid CSS selector string
|
|
1248
|
+
"""
|
|
1249
|
+
try:
|
|
1250
|
+
# Get base selector from XPath
|
|
1251
|
+
css_selector = cls._convert_simple_xpath_to_css_selector(element.xpath)
|
|
1252
|
+
|
|
1253
|
+
# Handle class attributes
|
|
1254
|
+
if 'class' in element.attributes and element.attributes['class'] and include_dynamic_attributes:
|
|
1255
|
+
# Define a regex pattern for valid class names in CSS
|
|
1256
|
+
valid_class_name_pattern = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_-]*$')
|
|
1257
|
+
|
|
1258
|
+
# Iterate through the class attribute values
|
|
1259
|
+
classes = element.attributes['class'].split()
|
|
1260
|
+
for class_name in classes:
|
|
1261
|
+
# Skip empty class names
|
|
1262
|
+
if not class_name.strip():
|
|
1263
|
+
continue
|
|
1264
|
+
|
|
1265
|
+
# Check if the class name is valid
|
|
1266
|
+
if valid_class_name_pattern.match(class_name):
|
|
1267
|
+
# Append the valid class name to the CSS selector
|
|
1268
|
+
css_selector += f'.{class_name}'
|
|
1269
|
+
else:
|
|
1270
|
+
# Skip invalid class names
|
|
1271
|
+
continue
|
|
1272
|
+
|
|
1273
|
+
# Expanded set of safe attributes that are stable and useful for selection
|
|
1274
|
+
SAFE_ATTRIBUTES = {
|
|
1275
|
+
# Data attributes (if they're stable in your application)
|
|
1276
|
+
'id',
|
|
1277
|
+
# Standard HTML attributes
|
|
1278
|
+
'name',
|
|
1279
|
+
'type',
|
|
1280
|
+
'placeholder',
|
|
1281
|
+
# Accessibility attributes
|
|
1282
|
+
'aria-label',
|
|
1283
|
+
'aria-labelledby',
|
|
1284
|
+
'aria-describedby',
|
|
1285
|
+
'role',
|
|
1286
|
+
# Common form attributes
|
|
1287
|
+
'for',
|
|
1288
|
+
'autocomplete',
|
|
1289
|
+
'required',
|
|
1290
|
+
'readonly',
|
|
1291
|
+
# Media attributes
|
|
1292
|
+
'alt',
|
|
1293
|
+
'title',
|
|
1294
|
+
'src',
|
|
1295
|
+
# Custom stable attributes (add any application-specific ones)
|
|
1296
|
+
'href',
|
|
1297
|
+
'target',
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
if include_dynamic_attributes:
|
|
1301
|
+
dynamic_attributes = {
|
|
1302
|
+
'data-id',
|
|
1303
|
+
'data-qa',
|
|
1304
|
+
'data-cy',
|
|
1305
|
+
'data-testid',
|
|
1306
|
+
}
|
|
1307
|
+
SAFE_ATTRIBUTES.update(dynamic_attributes)
|
|
1308
|
+
|
|
1309
|
+
# Handle other attributes
|
|
1310
|
+
for attribute, value in element.attributes.items():
|
|
1311
|
+
if attribute == 'class':
|
|
1312
|
+
continue
|
|
1313
|
+
|
|
1314
|
+
# Skip invalid attribute names
|
|
1315
|
+
if not attribute.strip():
|
|
1316
|
+
continue
|
|
1317
|
+
|
|
1318
|
+
if attribute not in SAFE_ATTRIBUTES:
|
|
1319
|
+
continue
|
|
1320
|
+
|
|
1321
|
+
# Escape special characters in attribute names
|
|
1322
|
+
safe_attribute = attribute.replace(':', r'\:')
|
|
1323
|
+
|
|
1324
|
+
# Handle different value cases
|
|
1325
|
+
if value == '':
|
|
1326
|
+
css_selector += f'[{safe_attribute}]'
|
|
1327
|
+
elif any(char in value for char in '"\'<>`\n\r\t'):
|
|
1328
|
+
# Use contains for values with special characters
|
|
1329
|
+
# Regex-substitute *any* whitespace with a single space, then strip.
|
|
1330
|
+
collapsed_value = re.sub(r'\s+', ' ', value).strip()
|
|
1331
|
+
# Escape embedded double-quotes.
|
|
1332
|
+
safe_value = collapsed_value.replace('"', '\\"')
|
|
1333
|
+
css_selector += f'[{safe_attribute}*="{safe_value}"]'
|
|
1334
|
+
else:
|
|
1335
|
+
css_selector += f'[{safe_attribute}="{value}"]'
|
|
1336
|
+
|
|
1337
|
+
return css_selector
|
|
1338
|
+
|
|
1339
|
+
except Exception:
|
|
1340
|
+
# Fallback to a more basic selector if something goes wrong
|
|
1341
|
+
tag_name = element.tag_name or '*'
|
|
1342
|
+
return f"{tag_name}[highlight_index='{element.highlight_index}']"
|
|
1343
|
+
|
|
1344
|
+
async def get_locate_element(self, element: DOMElementNode) -> Optional[ElementHandle]:
|
|
1345
|
+
current_frame = await self.get_current_page()
|
|
1346
|
+
|
|
1347
|
+
# Start with the target element and collect all parents
|
|
1348
|
+
parents: list[DOMElementNode] = []
|
|
1349
|
+
current = element
|
|
1350
|
+
while current.parent is not None:
|
|
1351
|
+
parent = current.parent
|
|
1352
|
+
parents.append(parent)
|
|
1353
|
+
current = parent
|
|
1354
|
+
|
|
1355
|
+
# Reverse the parents list to process from top to bottom
|
|
1356
|
+
parents.reverse()
|
|
1357
|
+
|
|
1358
|
+
# Process all iframe parents in sequence
|
|
1359
|
+
iframes = [item for item in parents if item.tag_name == 'iframe']
|
|
1360
|
+
for parent in iframes:
|
|
1361
|
+
css_selector = self._enhanced_css_selector_for_element(
|
|
1362
|
+
parent,
|
|
1363
|
+
include_dynamic_attributes=self.config.include_dynamic_attributes,
|
|
1364
|
+
)
|
|
1365
|
+
current_frame = current_frame.frame_locator(css_selector)
|
|
1366
|
+
|
|
1367
|
+
css_selector = self._enhanced_css_selector_for_element(
|
|
1368
|
+
element, include_dynamic_attributes=self.config.include_dynamic_attributes
|
|
1369
|
+
)
|
|
1370
|
+
|
|
1371
|
+
try:
|
|
1372
|
+
if isinstance(current_frame, FrameLocator):
|
|
1373
|
+
element_handle = await current_frame.locator(css_selector).element_handle()
|
|
1374
|
+
return element_handle
|
|
1375
|
+
else:
|
|
1376
|
+
# Try to scroll into view if hidden
|
|
1377
|
+
element_handle = await current_frame.query_selector(css_selector)
|
|
1378
|
+
if element_handle:
|
|
1379
|
+
await element_handle.scroll_into_view_if_needed()
|
|
1380
|
+
return element_handle
|
|
1381
|
+
return None
|
|
1382
|
+
except Exception as e:
|
|
1383
|
+
logger.error(f'Failed to locate element: {str(e)}')
|
|
1384
|
+
return None
|
|
1385
|
+
|
|
1386
|
+
async def _input_text_element_node(self, element_node: DOMElementNode, text: str):
|
|
1387
|
+
"""
|
|
1388
|
+
Input text into an element with proper error handling and state management.
|
|
1389
|
+
Handles different types of input fields and ensures proper element state before input.
|
|
1390
|
+
"""
|
|
1391
|
+
try:
|
|
1392
|
+
# Highlight before typing
|
|
1393
|
+
if element_node.highlight_index is not None:
|
|
1394
|
+
await self._update_state(focus_element=element_node.highlight_index)
|
|
1395
|
+
|
|
1396
|
+
page = await self.get_current_page()
|
|
1397
|
+
element_handle = await self.get_locate_element(element_node)
|
|
1398
|
+
|
|
1399
|
+
if element_handle is None:
|
|
1400
|
+
raise BrowserError(f'Element: {repr(element_node)} not found')
|
|
1401
|
+
|
|
1402
|
+
# Enhanced element readiness check with multiple attempts
|
|
1403
|
+
max_attempts = 3
|
|
1404
|
+
for attempt in range(max_attempts):
|
|
1405
|
+
try:
|
|
1406
|
+
# Wait for element to be stable and visible
|
|
1407
|
+
await element_handle.wait_for_element_state('stable', timeout=3000)
|
|
1408
|
+
await element_handle.wait_for_element_state('visible', timeout=3000)
|
|
1409
|
+
await element_handle.scroll_into_view_if_needed(timeout=3000)
|
|
1410
|
+
|
|
1411
|
+
# Additional wait for potential dynamic enabling
|
|
1412
|
+
await page.wait_for_timeout(200)
|
|
1413
|
+
|
|
1414
|
+
# Check if element is enabled
|
|
1415
|
+
is_enabled = await element_handle.is_enabled()
|
|
1416
|
+
if not is_enabled:
|
|
1417
|
+
# Wait a bit more for element to become enabled
|
|
1418
|
+
await page.wait_for_timeout(500)
|
|
1419
|
+
is_enabled = await element_handle.is_enabled()
|
|
1420
|
+
|
|
1421
|
+
if is_enabled:
|
|
1422
|
+
break
|
|
1423
|
+
elif attempt == max_attempts - 1:
|
|
1424
|
+
logger.warning(f'Element not enabled after {max_attempts} attempts, continuing anyway')
|
|
1425
|
+
except Exception as e:
|
|
1426
|
+
if attempt == max_attempts - 1:
|
|
1427
|
+
logger.warning(f'Element readiness check failed: {str(e)}, continuing anyway')
|
|
1428
|
+
else:
|
|
1429
|
+
await page.wait_for_timeout(500) # Wait before retry
|
|
1430
|
+
|
|
1431
|
+
# Get element properties to determine input method
|
|
1432
|
+
is_contenteditable = await element_handle.get_property('isContentEditable')
|
|
1433
|
+
|
|
1434
|
+
# Multiple strategies for text input with progressively more aggressive approaches
|
|
1435
|
+
strategies = [
|
|
1436
|
+
# Strategy 1: Standard approach
|
|
1437
|
+
lambda: self._input_strategy_standard(element_handle, text, is_contenteditable),
|
|
1438
|
+
# Strategy 2: Click first, then input
|
|
1439
|
+
lambda: self._input_strategy_click_first(element_handle, text, is_contenteditable),
|
|
1440
|
+
# Strategy 3: Force focus and clear before input
|
|
1441
|
+
lambda: self._input_strategy_force_focus(element_handle, text, is_contenteditable),
|
|
1442
|
+
# Strategy 4: JavaScript-based input as last resort
|
|
1443
|
+
lambda: self._input_strategy_javascript(element_handle, text, page)
|
|
1444
|
+
]
|
|
1445
|
+
|
|
1446
|
+
last_error = None
|
|
1447
|
+
for i, strategy in enumerate(strategies):
|
|
1448
|
+
try:
|
|
1449
|
+
await strategy()
|
|
1450
|
+
logger.debug(f'Text input successful using strategy {i + 1}')
|
|
1451
|
+
return
|
|
1452
|
+
except Exception as e:
|
|
1453
|
+
last_error = e
|
|
1454
|
+
logger.debug(f'Input strategy {i + 1} failed: {str(e)}')
|
|
1455
|
+
if i < len(strategies) - 1:
|
|
1456
|
+
# Wait before trying next strategy
|
|
1457
|
+
await page.wait_for_timeout(200)
|
|
1458
|
+
|
|
1459
|
+
# If all strategies failed, raise the last error
|
|
1460
|
+
raise last_error
|
|
1461
|
+
|
|
1462
|
+
except Exception as e:
|
|
1463
|
+
logger.debug(f'Failed to input text into element: {repr(element_node)}. Error: {str(e)}')
|
|
1464
|
+
raise BrowserError(f'Failed to input text into index {element_node.highlight_index}')
|
|
1465
|
+
|
|
1466
|
+
async def _input_strategy_standard(self, element_handle, text, is_contenteditable):
|
|
1467
|
+
"""Standard input strategy"""
|
|
1468
|
+
if await is_contenteditable.json_value():
|
|
1469
|
+
await element_handle.evaluate('el => el.textContent = ""')
|
|
1470
|
+
await element_handle.type(text, delay=5)
|
|
1471
|
+
else:
|
|
1472
|
+
await element_handle.fill(text)
|
|
1473
|
+
|
|
1474
|
+
async def _input_strategy_click_first(self, element_handle, text, is_contenteditable):
|
|
1475
|
+
"""Click element first, then input text"""
|
|
1476
|
+
await element_handle.click(timeout=5000)
|
|
1477
|
+
if await is_contenteditable.json_value():
|
|
1478
|
+
await element_handle.evaluate('el => el.textContent = ""')
|
|
1479
|
+
await element_handle.type(text, delay=5)
|
|
1480
|
+
else:
|
|
1481
|
+
await element_handle.fill(text)
|
|
1482
|
+
|
|
1483
|
+
async def _input_strategy_force_focus(self, element_handle, text, is_contenteditable):
|
|
1484
|
+
"""Force focus and clear before input"""
|
|
1485
|
+
await element_handle.focus()
|
|
1486
|
+
await element_handle.evaluate('el => { el.select(); el.value = ""; }')
|
|
1487
|
+
await element_handle.type(text, delay=5)
|
|
1488
|
+
|
|
1489
|
+
async def _input_strategy_javascript(self, element_handle, text, page):
|
|
1490
|
+
"""JavaScript-based input as last resort"""
|
|
1491
|
+
await element_handle.evaluate(f'''
|
|
1492
|
+
el => {{
|
|
1493
|
+
el.focus();
|
|
1494
|
+
el.value = "{text}";
|
|
1495
|
+
el.dispatchEvent(new Event('input', {{ bubbles: true }}));
|
|
1496
|
+
el.dispatchEvent(new Event('change', {{ bubbles: true }}));
|
|
1497
|
+
}}
|
|
1498
|
+
''')
|
|
1499
|
+
# Small delay to let any change handlers run
|
|
1500
|
+
await page.wait_for_timeout(100)
|
|
1501
|
+
|
|
1502
|
+
async def _click_element_node(self, element_node: DOMElementNode) -> Optional[str]:
|
|
1503
|
+
"""
|
|
1504
|
+
Optimized method to click an element using xpath.
|
|
1505
|
+
"""
|
|
1506
|
+
page = await self.get_current_page()
|
|
1507
|
+
|
|
1508
|
+
try:
|
|
1509
|
+
# Highlight before clicking
|
|
1510
|
+
if element_node.highlight_index is not None:
|
|
1511
|
+
await self._update_state(focus_element=element_node.highlight_index)
|
|
1512
|
+
|
|
1513
|
+
element_handle = await self.get_locate_element(element_node)
|
|
1514
|
+
|
|
1515
|
+
if element_handle is None:
|
|
1516
|
+
raise Exception(f'Element: {repr(element_node)} not found')
|
|
1517
|
+
|
|
1518
|
+
async def perform_click(click_func):
|
|
1519
|
+
"""Performs the actual click, handling both download
|
|
1520
|
+
and navigation scenarios."""
|
|
1521
|
+
if self.config.save_downloads_path:
|
|
1522
|
+
try:
|
|
1523
|
+
# Try short-timeout expect_download to detect a file download has been been triggered
|
|
1524
|
+
async with page.expect_download(timeout=5000) as download_info:
|
|
1525
|
+
await click_func()
|
|
1526
|
+
download = await download_info.value
|
|
1527
|
+
# Determine file path
|
|
1528
|
+
suggested_filename = download.suggested_filename
|
|
1529
|
+
unique_filename = await self._get_unique_filename(self.config.save_downloads_path, suggested_filename)
|
|
1530
|
+
download_path = os.path.join(self.config.save_downloads_path, unique_filename)
|
|
1531
|
+
await download.save_as(download_path)
|
|
1532
|
+
logger.debug(f'Download triggered. Saved file to: {download_path}')
|
|
1533
|
+
return download_path
|
|
1534
|
+
except TimeoutError:
|
|
1535
|
+
# If no download is triggered, treat as normal click
|
|
1536
|
+
logger.debug('No download triggered within timeout. Checking navigation...')
|
|
1537
|
+
await page.wait_for_load_state()
|
|
1538
|
+
await self._check_and_handle_navigation(page)
|
|
1539
|
+
else:
|
|
1540
|
+
# Standard click logic if no download is expected
|
|
1541
|
+
await click_func()
|
|
1542
|
+
await page.wait_for_load_state()
|
|
1543
|
+
await self._check_and_handle_navigation(page)
|
|
1544
|
+
|
|
1545
|
+
try:
|
|
1546
|
+
return await perform_click(lambda: element_handle.click(timeout=1500))
|
|
1547
|
+
except URLNotAllowedError as e:
|
|
1548
|
+
raise e
|
|
1549
|
+
except Exception:
|
|
1550
|
+
try:
|
|
1551
|
+
return await perform_click(lambda: page.evaluate('(el) => el.click()', element_handle))
|
|
1552
|
+
except URLNotAllowedError as e:
|
|
1553
|
+
raise e
|
|
1554
|
+
except Exception as e:
|
|
1555
|
+
raise Exception(f'Failed to click element: {str(e)}')
|
|
1556
|
+
|
|
1557
|
+
except URLNotAllowedError as e:
|
|
1558
|
+
raise e
|
|
1559
|
+
except Exception as e:
|
|
1560
|
+
raise Exception(f'Failed to click element: {repr(element_node)}. Error: {str(e)}')
|
|
1561
|
+
|
|
1562
|
+
async def get_tabs_info(self) -> list[TabInfo]:
|
|
1563
|
+
"""Get information about all tabs"""
|
|
1564
|
+
session = await self.get_session()
|
|
1565
|
+
|
|
1566
|
+
tabs_info = []
|
|
1567
|
+
for page_id, page in enumerate(session.context.pages):
|
|
1568
|
+
tab_info = TabInfo(page_id=page_id, url=page.url, title=await page.title())
|
|
1569
|
+
tabs_info.append(tab_info)
|
|
1570
|
+
|
|
1571
|
+
return tabs_info
|
|
1572
|
+
|
|
1573
|
+
async def switch_to_tab(self, page_id: int) -> None:
|
|
1574
|
+
"""Switch to a specific tab by its page_id
|
|
1575
|
+
|
|
1576
|
+
@You can also use negative indices to switch to tabs from the end (Pure pythonic way)
|
|
1577
|
+
"""
|
|
1578
|
+
session = await self.get_session()
|
|
1579
|
+
pages = session.context.pages
|
|
1580
|
+
tabs_count = len(pages)
|
|
1581
|
+
|
|
1582
|
+
if tabs_count == 0:
|
|
1583
|
+
raise BrowserError('No tabs available to switch to')
|
|
1584
|
+
|
|
1585
|
+
# Handle negative indices properly
|
|
1586
|
+
if page_id < 0:
|
|
1587
|
+
# Convert negative index to positive index
|
|
1588
|
+
positive_index = tabs_count + page_id
|
|
1589
|
+
if positive_index < 0:
|
|
1590
|
+
# Even after conversion, index is still negative (out of range)
|
|
1591
|
+
tabs_info = await self.get_tabs_info()
|
|
1592
|
+
tabs_str = "\n".join([f"Tab {tab.page_id}: {tab.title} ({tab.url})" for tab in tabs_info])
|
|
1593
|
+
raise BrowserError(f'No tab found with page_id: {page_id} (negative index out of range). Available tabs:\n{tabs_str}')
|
|
1594
|
+
page_id = positive_index
|
|
1595
|
+
|
|
1596
|
+
if page_id >= tabs_count:
|
|
1597
|
+
# Index is out of range, show available tabs in error message
|
|
1598
|
+
tabs_info = await self.get_tabs_info()
|
|
1599
|
+
tabs_str = "\n".join([f"Tab {tab.page_id}: {tab.title} ({tab.url})" for tab in tabs_info])
|
|
1600
|
+
raise BrowserError(f'No tab found with page_id: {page_id} (out of range). Available tabs:\n{tabs_str}')
|
|
1601
|
+
|
|
1602
|
+
page = pages[page_id]
|
|
1603
|
+
|
|
1604
|
+
# Check if the tab's URL is allowed before switching
|
|
1605
|
+
if not self._is_url_allowed(page.url):
|
|
1606
|
+
raise BrowserError(f'Cannot switch to tab with non-allowed URL: {page.url}')
|
|
1607
|
+
|
|
1608
|
+
session.current_page = page
|
|
1609
|
+
|
|
1610
|
+
await page.bring_to_front()
|
|
1611
|
+
await page.wait_for_load_state()
|
|
1612
|
+
|
|
1613
|
+
async def create_new_tab(self, url: str | None = None) -> None:
|
|
1614
|
+
"""Create a new tab and optionally navigate to a URL"""
|
|
1615
|
+
if url and not self._is_url_allowed(url):
|
|
1616
|
+
raise BrowserError(f'Cannot create new tab with non-allowed URL: {url}')
|
|
1617
|
+
|
|
1618
|
+
session = await self.get_session()
|
|
1619
|
+
new_page = await session.context.new_page()
|
|
1620
|
+
session.current_page = new_page
|
|
1621
|
+
|
|
1622
|
+
await new_page.wait_for_load_state()
|
|
1623
|
+
|
|
1624
|
+
page = await self.get_current_page()
|
|
1625
|
+
|
|
1626
|
+
if url:
|
|
1627
|
+
await page.goto(url)
|
|
1628
|
+
await self._wait_for_page_and_frames_load(timeout_overwrite=1)
|
|
1629
|
+
|
|
1630
|
+
# endregion
|
|
1631
|
+
|
|
1632
|
+
# region - Helper methods for easier access to the DOM
|
|
1633
|
+
async def get_selector_map(self) -> SelectorMap:
|
|
1634
|
+
session = await self.get_session()
|
|
1635
|
+
return session.cached_state.selector_map
|
|
1636
|
+
|
|
1637
|
+
async def get_element_by_index(self, index: int) -> ElementHandle | None:
|
|
1638
|
+
selector_map = await self.get_selector_map()
|
|
1639
|
+
element_handle = await self.get_locate_element(selector_map[index])
|
|
1640
|
+
return element_handle
|
|
1641
|
+
|
|
1642
|
+
async def get_dom_element_by_index(self, index: int) -> DOMElementNode:
|
|
1643
|
+
selector_map = await self.get_selector_map()
|
|
1644
|
+
return selector_map[index]
|
|
1645
|
+
|
|
1646
|
+
async def save_cookies(self):
|
|
1647
|
+
"""Save current cookies to file"""
|
|
1648
|
+
if self.session and self.session.context and self.config.cookies_file:
|
|
1649
|
+
try:
|
|
1650
|
+
cookies = await self.session.context.cookies()
|
|
1651
|
+
logger.debug(f'Saving {len(cookies)} cookies to {self.config.cookies_file}')
|
|
1652
|
+
|
|
1653
|
+
# Check if the path is a directory and create it if necessary
|
|
1654
|
+
dirname = os.path.dirname(self.config.cookies_file)
|
|
1655
|
+
if dirname:
|
|
1656
|
+
os.makedirs(dirname, exist_ok=True)
|
|
1657
|
+
|
|
1658
|
+
with open(self.config.cookies_file, 'w') as f:
|
|
1659
|
+
json.dump(cookies, f)
|
|
1660
|
+
except Exception as e:
|
|
1661
|
+
logger.warning(f'Failed to save cookies: {str(e)}')
|
|
1662
|
+
|
|
1663
|
+
async def is_file_uploader(self, element_node: DOMElementNode, max_depth: int = 3, current_depth: int = 0) -> bool:
|
|
1664
|
+
"""Check if element or its children are file uploaders"""
|
|
1665
|
+
if current_depth > max_depth:
|
|
1666
|
+
return False
|
|
1667
|
+
|
|
1668
|
+
# Check current element
|
|
1669
|
+
is_uploader = False
|
|
1670
|
+
|
|
1671
|
+
if not isinstance(element_node, DOMElementNode):
|
|
1672
|
+
return False
|
|
1673
|
+
|
|
1674
|
+
# Check for file input attributes
|
|
1675
|
+
if element_node.tag_name == 'input':
|
|
1676
|
+
is_uploader = element_node.attributes.get('type') == 'file' or element_node.attributes.get('accept') is not None
|
|
1677
|
+
|
|
1678
|
+
if is_uploader:
|
|
1679
|
+
return True
|
|
1680
|
+
|
|
1681
|
+
# Recursively check children
|
|
1682
|
+
if element_node.children and current_depth < max_depth:
|
|
1683
|
+
for child in element_node.children:
|
|
1684
|
+
if isinstance(child, DOMElementNode):
|
|
1685
|
+
if await self.is_file_uploader(child, max_depth, current_depth + 1):
|
|
1686
|
+
return True
|
|
1687
|
+
|
|
1688
|
+
return False
|
|
1689
|
+
|
|
1690
|
+
async def get_scroll_info(self, page: Page) -> tuple[int, int]:
|
|
1691
|
+
"""Get scroll position information for the current page."""
|
|
1692
|
+
scroll_y = await page.evaluate('window.scrollY')
|
|
1693
|
+
viewport_height = await page.evaluate('window.innerHeight')
|
|
1694
|
+
total_height = await page.evaluate('document.documentElement.scrollHeight')
|
|
1695
|
+
pixels_above = scroll_y
|
|
1696
|
+
pixels_below = total_height - (scroll_y + viewport_height)
|
|
1697
|
+
return pixels_above, pixels_below
|
|
1698
|
+
|
|
1699
|
+
async def reset_context(self):
|
|
1700
|
+
"""Reset the browser session
|
|
1701
|
+
Call this when you don't want to kill the context but just kill the state
|
|
1702
|
+
"""
|
|
1703
|
+
# close all tabs and clear cached state
|
|
1704
|
+
session = await self.get_session()
|
|
1705
|
+
|
|
1706
|
+
pages = session.context.pages
|
|
1707
|
+
for page in pages:
|
|
1708
|
+
await page.close()
|
|
1709
|
+
|
|
1710
|
+
session.cached_state = self._get_initial_state()
|
|
1711
|
+
session.current_page = await session.context.new_page()
|
|
1712
|
+
|
|
1713
|
+
def _get_initial_state(self, page: Optional[Page] = None) -> BrowserState:
|
|
1714
|
+
"""Get the initial state of the browser
|
|
1715
|
+
|
|
1716
|
+
Note: This creates a minimal state for a new browser session.
|
|
1717
|
+
The state should be updated via get_state() after any navigation.
|
|
1718
|
+
"""
|
|
1719
|
+
# Log if we're creating an initial state with about:blank
|
|
1720
|
+
url = page.url if page else ''
|
|
1721
|
+
if url == 'about:blank' or url == '':
|
|
1722
|
+
self.logger.debug("Creating initial state with blank page - state will be updated after first navigation")
|
|
1723
|
+
|
|
1724
|
+
return BrowserState(
|
|
1725
|
+
element_tree=DOMElementNode(
|
|
1726
|
+
tag_name='root',
|
|
1727
|
+
is_visible=True,
|
|
1728
|
+
parent=None,
|
|
1729
|
+
xpath='',
|
|
1730
|
+
attributes={},
|
|
1731
|
+
children=[],
|
|
1732
|
+
),
|
|
1733
|
+
selector_map={},
|
|
1734
|
+
url=url,
|
|
1735
|
+
title='',
|
|
1736
|
+
screenshot=None,
|
|
1737
|
+
tabs=[],
|
|
1738
|
+
)
|
|
1739
|
+
|
|
1740
|
+
async def _get_unique_filename(self, directory, filename):
|
|
1741
|
+
"""Generate a unique filename by appending (1), (2), etc., if a file already exists."""
|
|
1742
|
+
base, ext = os.path.splitext(filename)
|
|
1743
|
+
counter = 1
|
|
1744
|
+
new_filename = filename
|
|
1745
|
+
while os.path.exists(os.path.join(directory, new_filename)):
|
|
1746
|
+
new_filename = f'{base} ({counter}){ext}'
|
|
1747
|
+
counter += 1
|
|
1748
|
+
return new_filename
|