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/browser.py
ADDED
|
@@ -0,0 +1,1457 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Playwright browser on steroids.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import gc
|
|
7
|
+
import logging
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Optional, Dict, Any, Type, List
|
|
10
|
+
import platform
|
|
11
|
+
import os
|
|
12
|
+
import tempfile
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
# ProxySettings type for proxy configuration
|
|
17
|
+
from playwright.async_api import Browser as PlaywrightBrowser
|
|
18
|
+
from playwright.async_api import (
|
|
19
|
+
Playwright,
|
|
20
|
+
async_playwright,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
from tools.browser.context import BrowserContext, BrowserContextConfig
|
|
24
|
+
from tools.base_tool import BaseTool
|
|
25
|
+
from tools.controller.types import ActionResult
|
|
26
|
+
from tools.browser.actions import (
|
|
27
|
+
SearchGoogleAction, GoToUrlAction, ClickElementAction, InputTextAction,
|
|
28
|
+
SwitchTabAction, OpenTabAction, ScrollAction, SendKeysAction,
|
|
29
|
+
NoParamsAction, ExtractPageContentAction
|
|
30
|
+
)
|
|
31
|
+
from tools.controller.execution_context import ActionExecutionContext
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _check_url_ssrf(url: str) -> Optional[str]:
|
|
35
|
+
"""SSRF guard for agent-supplied navigation URLs.
|
|
36
|
+
|
|
37
|
+
Runs the URL through the existing MCPURLValidator (which resolves the host
|
|
38
|
+
and rejects loopback / RFC1918 / link-local / cloud-metadata IP ranges)
|
|
39
|
+
BEFORE the browser is allowed to navigate. This stops a prompt-injected page
|
|
40
|
+
from steering the agent to http://169.254.169.254/ (instance metadata) or
|
|
41
|
+
internal RFC1918 services and exfiltrating the response back to the model.
|
|
42
|
+
|
|
43
|
+
The browser legitimately uses both http and https, so ``allow_http=True`` is
|
|
44
|
+
passed — we only care about the SSRF IP-range checks here, not the scheme.
|
|
45
|
+
|
|
46
|
+
Gated by ``BROWSER_ALLOW_PRIVATE_URLS`` (default false = guard active). Set it
|
|
47
|
+
to ``true`` for local/dev where hitting localhost is intentional.
|
|
48
|
+
|
|
49
|
+
Residual risk (accepted for this fix): Playwright re-resolves DNS at goto
|
|
50
|
+
time, so a hostname whose A-record flips between this check and the actual
|
|
51
|
+
navigation (DNS rebinding) is a TOCTOU window this does NOT fully close. We
|
|
52
|
+
validate the *currently resolved* IP, which blocks the obvious static
|
|
53
|
+
metadata/RFC1918 SSRF; a separate pin-resolved-IP task covers rebinding.
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
An error message string if the URL is blocked, or ``None`` if allowed.
|
|
57
|
+
"""
|
|
58
|
+
allow_private = os.getenv('BROWSER_ALLOW_PRIVATE_URLS', 'false').strip().lower() in ('1', 'true', 'yes', 'on')
|
|
59
|
+
if allow_private:
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
# WS-4 (compute posture): a NARROW exception for the agent's OWN sandbox server —
|
|
63
|
+
# a loopback URL on a host port the sandbox actually published is allowed, so the
|
|
64
|
+
# agent can HTTP-test what it just started. This never opens RFC1918 or cloud
|
|
65
|
+
# metadata (169.254.169.254 is not loopback); the set is empty unless the sandbox
|
|
66
|
+
# published a port (posture >= 1). Everything else still runs the strict validator.
|
|
67
|
+
try:
|
|
68
|
+
from tools.shell.loopback_allow import is_loopback_allowed
|
|
69
|
+
if is_loopback_allowed(url):
|
|
70
|
+
return None
|
|
71
|
+
except Exception:
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
from tools.mcp.security import MCPURLValidator
|
|
76
|
+
# allow_http=True: the browser uses http+https; we want only the SSRF
|
|
77
|
+
# IP-range checks, not the HTTPS-only restriction MCP applies to servers.
|
|
78
|
+
validator = MCPURLValidator(allow_http=True)
|
|
79
|
+
is_valid, error = validator.validate(url)
|
|
80
|
+
if not is_valid:
|
|
81
|
+
return f"Blocked URL (SSRF protection): {error}. Set BROWSER_ALLOW_PRIVATE_URLS=true to allow private/internal hosts (local/dev only)."
|
|
82
|
+
except Exception as e:
|
|
83
|
+
# Fail closed: if validation itself errors, do not navigate.
|
|
84
|
+
return f"Blocked URL (SSRF validation error): {e}"
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass
|
|
89
|
+
class BrowserConfig:
|
|
90
|
+
r"""
|
|
91
|
+
Configuration for the Browser.
|
|
92
|
+
|
|
93
|
+
Default values:
|
|
94
|
+
headless: True
|
|
95
|
+
Whether to run browser in headless mode (no visible window).
|
|
96
|
+
Set to True by default for server compatibility.
|
|
97
|
+
|
|
98
|
+
disable_security: False
|
|
99
|
+
Disable browser security features (safe default - opt-in relaxations only)
|
|
100
|
+
|
|
101
|
+
use_no_sandbox: False
|
|
102
|
+
Enable --no-sandbox flag (opt-in only, required for some server environments)
|
|
103
|
+
|
|
104
|
+
extra_chromium_args: []
|
|
105
|
+
Extra arguments to pass to the browser
|
|
106
|
+
|
|
107
|
+
wss_url: None
|
|
108
|
+
Connect to a browser instance via WebSocket
|
|
109
|
+
|
|
110
|
+
cdp_url: None
|
|
111
|
+
Connect to a browser instance via CDP
|
|
112
|
+
|
|
113
|
+
chrome_instance_path: None
|
|
114
|
+
Path to a Chrome instance to use to connect to your normal browser
|
|
115
|
+
e.g. '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome'
|
|
116
|
+
|
|
117
|
+
auto_configure_for_server: True
|
|
118
|
+
Automatically configure browser for server environments.
|
|
119
|
+
This includes checking for X server availability and falling back
|
|
120
|
+
to headless mode if no display is available. It also adds necessary
|
|
121
|
+
flags like --no-sandbox and --disable-dev-shm-usage for stability.
|
|
122
|
+
Should be left enabled unless you're managing these settings manually.
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
headless: bool = True # Changed default to True for safety and server compatibility
|
|
126
|
+
disable_security: bool = False
|
|
127
|
+
use_no_sandbox: bool = False # Opt-in --no-sandbox flag for server environments
|
|
128
|
+
extra_chromium_args: list[str] = field(default_factory=list)
|
|
129
|
+
chrome_instance_path: str | None = None
|
|
130
|
+
wss_url: str | None = None
|
|
131
|
+
cdp_url: str | None = None
|
|
132
|
+
auto_configure_for_server: bool = True
|
|
133
|
+
|
|
134
|
+
proxy: Dict[str, Any] | None = field(default=None)
|
|
135
|
+
new_context_config: BrowserContextConfig = field(default_factory=BrowserContextConfig)
|
|
136
|
+
|
|
137
|
+
_force_keep_browser_alive: bool = False
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# @singleton: TODO - think about id singleton makes sense here
|
|
141
|
+
# @dev By default this is a singleton, but you can create multiple instances if you need to.
|
|
142
|
+
class Browser(BaseTool):
|
|
143
|
+
"""
|
|
144
|
+
Playwright browser on steroids.
|
|
145
|
+
|
|
146
|
+
This tool provides browser automation capabilities using Playwright.
|
|
147
|
+
It follows the standard BaseTool pattern with decorated actions.
|
|
148
|
+
|
|
149
|
+
Architecture:
|
|
150
|
+
- Extends BaseTool for lifecycle management
|
|
151
|
+
- Actions defined with @BaseTool.action() decorator
|
|
152
|
+
- Auto-discovered by Controller via get_actions()
|
|
153
|
+
- Registered with namespacing (browser_action_name)
|
|
154
|
+
|
|
155
|
+
Usage:
|
|
156
|
+
# In Controller/Orchestrator initialization
|
|
157
|
+
browser = Browser(name="browser", config=bot_config)
|
|
158
|
+
await browser.initialize()
|
|
159
|
+
controller.add_tool("browser", browser)
|
|
160
|
+
|
|
161
|
+
# Actions are automatically registered and available to LLM
|
|
162
|
+
|
|
163
|
+
Note: It is recommended to use only one instance per application
|
|
164
|
+
as each instance consumes significant RAM.
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
def __init__(
|
|
168
|
+
self,
|
|
169
|
+
name: str = "browser",
|
|
170
|
+
config = None,
|
|
171
|
+
container = None,
|
|
172
|
+
# Browser-specific parameters
|
|
173
|
+
headless: bool = True,
|
|
174
|
+
slow_mo: int = 0,
|
|
175
|
+
proxy: Optional[Dict[str, Any]] = None,
|
|
176
|
+
browser_config: Optional[BrowserConfig] = None,
|
|
177
|
+
timeout: int = 30000,
|
|
178
|
+
server_args: Optional[List[str]] = None,
|
|
179
|
+
browser_path: Optional[str] = None,
|
|
180
|
+
env: Optional[Dict[str, str]] = None,
|
|
181
|
+
):
|
|
182
|
+
"""Initialize Browser with configuration.
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
name: Tool name for registration
|
|
186
|
+
config: Bot configuration (required by BaseTool)
|
|
187
|
+
container: Dependency container (required by BaseTool)
|
|
188
|
+
headless: Whether to run browser in headless mode
|
|
189
|
+
slow_mo: Slow down Playwright operations by specified milliseconds
|
|
190
|
+
proxy: Proxy settings
|
|
191
|
+
browser_config: Custom browser configuration
|
|
192
|
+
timeout: Browser launch timeout in milliseconds
|
|
193
|
+
server_args: Additional arguments for browser launch
|
|
194
|
+
browser_path: Path to browser executable
|
|
195
|
+
env: Environment variables
|
|
196
|
+
"""
|
|
197
|
+
# Initialize BaseTool (this sets up logging, status tracking, etc.)
|
|
198
|
+
if config is None:
|
|
199
|
+
from core.config import BotConfig
|
|
200
|
+
config = BotConfig()
|
|
201
|
+
|
|
202
|
+
super().__init__(name=name, config=config, container=container)
|
|
203
|
+
|
|
204
|
+
# Initialize state variables (will be set in _initialize())
|
|
205
|
+
self._browser = None
|
|
206
|
+
self._playwright = None
|
|
207
|
+
self._xvfb_process = None
|
|
208
|
+
self._started_xvfb = False
|
|
209
|
+
|
|
210
|
+
# Use provided browser config or create default
|
|
211
|
+
self.browser_config = browser_config or BrowserConfig()
|
|
212
|
+
|
|
213
|
+
# Override browser config with provided arguments
|
|
214
|
+
if headless is not None:
|
|
215
|
+
self.browser_config.headless = headless
|
|
216
|
+
|
|
217
|
+
# Store initialization parameters
|
|
218
|
+
self.slow_mo = slow_mo
|
|
219
|
+
self.timeout = timeout
|
|
220
|
+
self.server_args = server_args or []
|
|
221
|
+
self.browser_path = browser_path
|
|
222
|
+
|
|
223
|
+
# Initialize base environment
|
|
224
|
+
base_env = os.environ.copy()
|
|
225
|
+
if env:
|
|
226
|
+
base_env.update(env)
|
|
227
|
+
|
|
228
|
+
# Handle server environment if needed
|
|
229
|
+
if self.browser_config.auto_configure_for_server:
|
|
230
|
+
# Configure environment with display setup
|
|
231
|
+
self.env = self._setup_display_for_server(base_env)
|
|
232
|
+
|
|
233
|
+
# Check if we started Xvfb (for cleanup)
|
|
234
|
+
if hasattr(self, '_xvfb_process') and self._xvfb_process is not None:
|
|
235
|
+
self._started_xvfb = True
|
|
236
|
+
|
|
237
|
+
# Get browser path if possible
|
|
238
|
+
self._detect_browser_on_server()
|
|
239
|
+
else:
|
|
240
|
+
self.env = base_env
|
|
241
|
+
|
|
242
|
+
# Disable security if configured
|
|
243
|
+
self.disable_security_args = []
|
|
244
|
+
if self.browser_config.disable_security:
|
|
245
|
+
self.disable_security_args = ['--disable-web-security', '--disable-site-isolation-trials', '--disable-features=IsolateOrigins,site-per-process']
|
|
246
|
+
|
|
247
|
+
self.logger.info(f"Browser initialized with headless={self.browser_config.headless}, auto_configure={self.browser_config.auto_configure_for_server}")
|
|
248
|
+
|
|
249
|
+
def _setup_display_for_server(self, env=None):
|
|
250
|
+
"""Set up display for server environments, ensuring Xvfb is running if needed."""
|
|
251
|
+
import subprocess
|
|
252
|
+
import shutil
|
|
253
|
+
import time
|
|
254
|
+
|
|
255
|
+
if not env:
|
|
256
|
+
env = os.environ.copy()
|
|
257
|
+
|
|
258
|
+
# If no DISPLAY, try to check if Xvfb is already running
|
|
259
|
+
if "DISPLAY" not in env:
|
|
260
|
+
logging.info("DISPLAY not set, checking for running Xvfb instances")
|
|
261
|
+
|
|
262
|
+
# Check if Xvfb is already running on :99
|
|
263
|
+
try:
|
|
264
|
+
xvfb_check = subprocess.run(
|
|
265
|
+
["pgrep", "-f", "Xvfb :99"],
|
|
266
|
+
stdout=subprocess.PIPE,
|
|
267
|
+
stderr=subprocess.PIPE,
|
|
268
|
+
text=True
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
if xvfb_check.returncode == 0:
|
|
272
|
+
# Xvfb is running, use it
|
|
273
|
+
logging.info("Found running Xvfb on :99, using it")
|
|
274
|
+
env["DISPLAY"] = ":99"
|
|
275
|
+
else:
|
|
276
|
+
# No Xvfb running, check if we can start one
|
|
277
|
+
xvfb_path = shutil.which("Xvfb")
|
|
278
|
+
if xvfb_path and self.browser_config.auto_configure_for_server:
|
|
279
|
+
logging.info("Starting Xvfb on :99")
|
|
280
|
+
try:
|
|
281
|
+
xvfb_process = subprocess.Popen(
|
|
282
|
+
["Xvfb", ":99", "-screen", "0", "1920x1080x24"],
|
|
283
|
+
stdout=subprocess.DEVNULL,
|
|
284
|
+
stderr=subprocess.DEVNULL,
|
|
285
|
+
)
|
|
286
|
+
# Give Xvfb a moment to start
|
|
287
|
+
time.sleep(1)
|
|
288
|
+
|
|
289
|
+
# Check if it's actually running
|
|
290
|
+
if xvfb_process.poll() is None:
|
|
291
|
+
logging.info("Successfully started Xvfb with PID: %d", xvfb_process.pid)
|
|
292
|
+
# Save PID for potential cleanup
|
|
293
|
+
pid_dir = os.path.dirname(os.path.abspath(__file__))
|
|
294
|
+
with open(os.path.join(pid_dir, "xvfb.pid"), "w") as f:
|
|
295
|
+
f.write(str(xvfb_process.pid))
|
|
296
|
+
env["DISPLAY"] = ":99"
|
|
297
|
+
else:
|
|
298
|
+
logging.warning("Failed to start Xvfb, forcing headless mode")
|
|
299
|
+
self.browser_config.headless = True
|
|
300
|
+
except Exception as e:
|
|
301
|
+
logging.warning(f"Error starting Xvfb: {str(e)}, forcing headless mode")
|
|
302
|
+
self.browser_config.headless = True
|
|
303
|
+
else:
|
|
304
|
+
# No Xvfb available, force headless mode
|
|
305
|
+
logging.warning(
|
|
306
|
+
"DISPLAY not set and Xvfb not available, forcing headless mode"
|
|
307
|
+
)
|
|
308
|
+
self.browser_config.headless = True
|
|
309
|
+
except Exception as e:
|
|
310
|
+
logging.warning(f"Error checking for Xvfb: {str(e)}, forcing headless mode")
|
|
311
|
+
self.browser_config.headless = True
|
|
312
|
+
|
|
313
|
+
# Even with a DISPLAY set, test if it's actually working
|
|
314
|
+
if "DISPLAY" in env and not self.browser_config.headless:
|
|
315
|
+
try:
|
|
316
|
+
display_check = subprocess.run(
|
|
317
|
+
["xdpyinfo", "-display", env["DISPLAY"]],
|
|
318
|
+
stdout=subprocess.DEVNULL,
|
|
319
|
+
stderr=subprocess.DEVNULL
|
|
320
|
+
)
|
|
321
|
+
if display_check.returncode != 0:
|
|
322
|
+
logging.warning(f"Display {env['DISPLAY']} not accessible, forcing headless mode")
|
|
323
|
+
self.browser_config.headless = True
|
|
324
|
+
except Exception:
|
|
325
|
+
logging.warning("Failed to verify display, forcing headless mode")
|
|
326
|
+
self.browser_config.headless = True
|
|
327
|
+
|
|
328
|
+
return env
|
|
329
|
+
|
|
330
|
+
def _configure_server_args(self, server_args):
|
|
331
|
+
"""Configure browser launch arguments for server environments."""
|
|
332
|
+
if server_args is None:
|
|
333
|
+
server_args = []
|
|
334
|
+
|
|
335
|
+
# Add --no-sandbox only if explicitly opted-in
|
|
336
|
+
if self.browser_config.use_no_sandbox and "--no-sandbox" not in server_args:
|
|
337
|
+
server_args.append("--no-sandbox")
|
|
338
|
+
|
|
339
|
+
# Configure server-specific flags
|
|
340
|
+
if self.browser_config.auto_configure_for_server:
|
|
341
|
+
|
|
342
|
+
# Handle GPU-related flags for server environments
|
|
343
|
+
if "--disable-gpu" not in server_args:
|
|
344
|
+
server_args.append("--disable-gpu")
|
|
345
|
+
|
|
346
|
+
# Make sure we're handling remote rendering correctly
|
|
347
|
+
if "--disable-dev-shm-usage" not in server_args:
|
|
348
|
+
server_args.append("--disable-dev-shm-usage")
|
|
349
|
+
|
|
350
|
+
# In non-headless mode on a server, we need to adjust some settings
|
|
351
|
+
if not self.browser_config.headless and "DISPLAY" in os.environ:
|
|
352
|
+
# Add browser flags that work better with Xvfb
|
|
353
|
+
if "--disable-features=VizDisplayCompositor" not in server_args:
|
|
354
|
+
server_args.append("--disable-features=VizDisplayCompositor")
|
|
355
|
+
|
|
356
|
+
# Add user-specified args
|
|
357
|
+
if self.browser_config.extra_chromium_args:
|
|
358
|
+
server_args.extend(self.browser_config.extra_chromium_args)
|
|
359
|
+
|
|
360
|
+
return server_args
|
|
361
|
+
|
|
362
|
+
def _detect_browser_on_server(self):
|
|
363
|
+
"""Detect installed browsers on server"""
|
|
364
|
+
common_browser_paths = [
|
|
365
|
+
"/usr/bin/chromium-browser",
|
|
366
|
+
"/usr/bin/chromium",
|
|
367
|
+
"/usr/bin/google-chrome",
|
|
368
|
+
"/usr/bin/google-chrome-stable",
|
|
369
|
+
"/snap/bin/chromium",
|
|
370
|
+
]
|
|
371
|
+
|
|
372
|
+
browser_path = None
|
|
373
|
+
for path in common_browser_paths:
|
|
374
|
+
if os.path.exists(path):
|
|
375
|
+
browser_path = path
|
|
376
|
+
self.logger.info(f"Auto-detected browser at: {browser_path}")
|
|
377
|
+
break
|
|
378
|
+
|
|
379
|
+
if browser_path is None:
|
|
380
|
+
self.logger.warning("No browser executable found. Install chromium-browser or google-chrome.")
|
|
381
|
+
|
|
382
|
+
return browser_path
|
|
383
|
+
|
|
384
|
+
@property
|
|
385
|
+
def required_services(self) -> Dict[str, str]:
|
|
386
|
+
"""Browser has no required services."""
|
|
387
|
+
return {}
|
|
388
|
+
|
|
389
|
+
@property
|
|
390
|
+
def optional_services(self) -> Dict[str, str]:
|
|
391
|
+
"""Browser has no optional services."""
|
|
392
|
+
return {}
|
|
393
|
+
|
|
394
|
+
@property
|
|
395
|
+
def required_config(self) -> Dict[str, str]:
|
|
396
|
+
"""Browser has no required config beyond BotConfig."""
|
|
397
|
+
return {}
|
|
398
|
+
|
|
399
|
+
async def _initialize(self) -> None:
|
|
400
|
+
"""Initialize browser instance.
|
|
401
|
+
|
|
402
|
+
Called automatically by BaseTool.initialize().
|
|
403
|
+
"""
|
|
404
|
+
# Call parent to register decorated actions
|
|
405
|
+
await super()._initialize()
|
|
406
|
+
|
|
407
|
+
# Browser-specific initialization happens lazily when first needed
|
|
408
|
+
self.logger.info("Browser tool initialized (browser instance will start on first use)")
|
|
409
|
+
|
|
410
|
+
async def _cleanup(self) -> None:
|
|
411
|
+
"""Cleanup browser resources.
|
|
412
|
+
|
|
413
|
+
Called automatically by BaseTool.cleanup().
|
|
414
|
+
"""
|
|
415
|
+
try:
|
|
416
|
+
if self._browser:
|
|
417
|
+
await self._browser.close()
|
|
418
|
+
self._browser = None
|
|
419
|
+
self.logger.debug("Browser closed")
|
|
420
|
+
|
|
421
|
+
if self._playwright:
|
|
422
|
+
await self._playwright.stop()
|
|
423
|
+
self._playwright = None
|
|
424
|
+
self.logger.debug("Playwright stopped")
|
|
425
|
+
|
|
426
|
+
# Handle Xvfb cleanup
|
|
427
|
+
if self._started_xvfb and self._xvfb_process:
|
|
428
|
+
try:
|
|
429
|
+
if self._xvfb_process.poll() is None:
|
|
430
|
+
self._xvfb_process.terminate()
|
|
431
|
+
self.logger.info(f"Terminated Xvfb process (PID: {self._xvfb_process.pid})")
|
|
432
|
+
except Exception as e:
|
|
433
|
+
self.logger.warning(f"Error cleaning up Xvfb: {e}")
|
|
434
|
+
|
|
435
|
+
self.logger.info("Browser cleanup completed")
|
|
436
|
+
except Exception as e:
|
|
437
|
+
self.logger.error(f"Error during browser cleanup: {e}")
|
|
438
|
+
raise
|
|
439
|
+
|
|
440
|
+
@BaseTool.action(
|
|
441
|
+
'Search the query in Google in the current tab, the query should be a search query like humans search in Google, concrete and not vague or super long.',
|
|
442
|
+
param_model=SearchGoogleAction
|
|
443
|
+
)
|
|
444
|
+
async def search_google(self, params: SearchGoogleAction, execution_context: Optional[ActionExecutionContext]):
|
|
445
|
+
"""Search Google in the current tab."""
|
|
446
|
+
import time
|
|
447
|
+
start_time = time.time()
|
|
448
|
+
|
|
449
|
+
if not isinstance(params, SearchGoogleAction):
|
|
450
|
+
from pydantic import TypeAdapter
|
|
451
|
+
params = TypeAdapter(SearchGoogleAction).validate_python(params)
|
|
452
|
+
|
|
453
|
+
browser_context = execution_context.browser_context
|
|
454
|
+
if not browser_context:
|
|
455
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
456
|
+
|
|
457
|
+
try:
|
|
458
|
+
page = await browser_context.get_current_page()
|
|
459
|
+
search_url = f'https://www.google.com/search?q={params.query}&udm=14'
|
|
460
|
+
self.logger.info(f"🔍 Starting Google search for: {params.query}")
|
|
461
|
+
|
|
462
|
+
response = await page.goto(search_url, timeout=30000, wait_until='domcontentloaded')
|
|
463
|
+
|
|
464
|
+
if not response or not response.ok:
|
|
465
|
+
status = response.status if response else 'No response'
|
|
466
|
+
duration = time.time() - start_time
|
|
467
|
+
self.logger.error(f"❌ Google search failed after {duration:.2f}s: HTTP {status}")
|
|
468
|
+
return ActionResult(
|
|
469
|
+
error=f"Google search failed: HTTP {status}",
|
|
470
|
+
include_in_memory=True
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
# Wait for page to be ready with proper error handling
|
|
474
|
+
await self._wait_for_page_load(page)
|
|
475
|
+
|
|
476
|
+
# Update the cached state after search
|
|
477
|
+
await browser_context._update_state()
|
|
478
|
+
|
|
479
|
+
duration = time.time() - start_time
|
|
480
|
+
self.logger.info(f"✅ Google search completed successfully in {duration:.2f}s")
|
|
481
|
+
|
|
482
|
+
return ActionResult(
|
|
483
|
+
extracted_content=f'🔍 Searched for "{params.query}" in Google',
|
|
484
|
+
include_in_memory=True
|
|
485
|
+
)
|
|
486
|
+
except asyncio.TimeoutError as e:
|
|
487
|
+
duration = time.time() - start_time
|
|
488
|
+
self.logger.error(f"⏱️ Google search timed out after {duration:.2f}s: {str(e)}")
|
|
489
|
+
return ActionResult(error=f"Search timed out after {duration:.2f}s", include_in_memory=True)
|
|
490
|
+
except Exception as e:
|
|
491
|
+
duration = time.time() - start_time
|
|
492
|
+
self.logger.error(f"❌ Google search failed after {duration:.2f}s: {str(e)}")
|
|
493
|
+
return ActionResult(error=f"Search failed: {str(e)}", include_in_memory=True)
|
|
494
|
+
|
|
495
|
+
@BaseTool.action(
|
|
496
|
+
'Navigate to a URL and get page snapshot.',
|
|
497
|
+
param_model=GoToUrlAction
|
|
498
|
+
)
|
|
499
|
+
async def go_to_url(self, params: GoToUrlAction, execution_context: Optional[ActionExecutionContext]):
|
|
500
|
+
"""Navigate to URL and return accessibility snapshot automatically."""
|
|
501
|
+
if not isinstance(params, GoToUrlAction):
|
|
502
|
+
from pydantic import TypeAdapter
|
|
503
|
+
params = TypeAdapter(GoToUrlAction).validate_python(params)
|
|
504
|
+
|
|
505
|
+
browser_context = execution_context.browser_context
|
|
506
|
+
if not browser_context:
|
|
507
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
508
|
+
|
|
509
|
+
# GUARD: Prevent file:// URLs (local files not supported)
|
|
510
|
+
# BUT allow data: URLs for rendering images
|
|
511
|
+
if (params.url.startswith('file://') or 'file:///' in params.url) and not params.url.startswith('data:'):
|
|
512
|
+
return ActionResult(
|
|
513
|
+
error="Cannot open file:// URLs in browser. If you're trying to view an image, you already have vision capabilities - just analyze the image content that was passed to you in the message. Alternatively, you can use filesystem_read_file to get the image content and create an HTML page with a data URL.",
|
|
514
|
+
include_in_memory=True
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
# GUARD: SSRF — reject loopback / RFC1918 / link-local / cloud-metadata
|
|
518
|
+
# hosts before navigating (gated by BROWSER_ALLOW_PRIVATE_URLS). Offload the
|
|
519
|
+
# blocking DNS resolution to a thread so a slow resolver can't freeze the loop.
|
|
520
|
+
ssrf_error = await asyncio.get_running_loop().run_in_executor(
|
|
521
|
+
None, _check_url_ssrf, params.url)
|
|
522
|
+
if ssrf_error:
|
|
523
|
+
self.logger.warning(f"Blocked navigation to {params.url}: {ssrf_error}")
|
|
524
|
+
return ActionResult(error=ssrf_error, include_in_memory=True)
|
|
525
|
+
|
|
526
|
+
# GUARD: respect the user-configured allowed_domains allowlist that
|
|
527
|
+
# context.navigate_to() enforces — go_to_url uses page.goto() directly
|
|
528
|
+
# and would otherwise bypass it.
|
|
529
|
+
if not browser_context._is_url_allowed(params.url):
|
|
530
|
+
self.logger.warning(f"Blocked navigation to disallowed domain: {params.url}")
|
|
531
|
+
return ActionResult(
|
|
532
|
+
error=f"Navigation blocked: {params.url} is not in the allowed domains list",
|
|
533
|
+
include_in_memory=True,
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
try:
|
|
537
|
+
page = await browser_context.get_current_page()
|
|
538
|
+
self.logger.info(f"Navigating to {params.url}")
|
|
539
|
+
|
|
540
|
+
# Navigate with timeout
|
|
541
|
+
response = await page.goto(params.url, timeout=30000, wait_until='domcontentloaded')
|
|
542
|
+
|
|
543
|
+
if not response or not response.ok:
|
|
544
|
+
status = response.status if response else 'No response'
|
|
545
|
+
return ActionResult(
|
|
546
|
+
error=f"Navigation failed: HTTP {status}",
|
|
547
|
+
include_in_memory=True
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
# Wait for page to be ready with proper error handling
|
|
551
|
+
await self._wait_for_page_load(page)
|
|
552
|
+
|
|
553
|
+
# Update the cached state after navigation
|
|
554
|
+
await browser_context._update_state()
|
|
555
|
+
|
|
556
|
+
self.logger.info(f"Successfully navigated to {page.url}")
|
|
557
|
+
|
|
558
|
+
# FIX (Context Optimization): Return success confirmation only
|
|
559
|
+
# Agent sees full page structure in next prompt via BrowserState.element_tree
|
|
560
|
+
# No need to duplicate page content in tool result (saves 50k+ chars per navigation)
|
|
561
|
+
try:
|
|
562
|
+
page_title = await page.title()
|
|
563
|
+
page_url = str(page.url)
|
|
564
|
+
|
|
565
|
+
# Count interactive elements from browser state if available
|
|
566
|
+
element_count = 0
|
|
567
|
+
if browser_context and hasattr(browser_context, 'session'):
|
|
568
|
+
session = await browser_context.get_session()
|
|
569
|
+
if session and hasattr(session, 'cached_state'):
|
|
570
|
+
element_count = len(session.cached_state.selector_map)
|
|
571
|
+
|
|
572
|
+
# Return concise confirmation
|
|
573
|
+
result_text = f"✅ Navigated to {page_url}\nTitle: {page_title}"
|
|
574
|
+
if element_count > 0:
|
|
575
|
+
result_text += f"\nInteractive elements: {element_count}"
|
|
576
|
+
|
|
577
|
+
self.logger.info(f"Navigated to {page_url} - {element_count} elements")
|
|
578
|
+
|
|
579
|
+
return ActionResult(
|
|
580
|
+
extracted_content=result_text,
|
|
581
|
+
include_in_memory=True,
|
|
582
|
+
metadata={
|
|
583
|
+
'url': page_url,
|
|
584
|
+
'title': page_title,
|
|
585
|
+
'method': 'navigation_confirmation'
|
|
586
|
+
}
|
|
587
|
+
)
|
|
588
|
+
except Exception as e:
|
|
589
|
+
self.logger.warning(f"Error getting page metadata: {e}")
|
|
590
|
+
return ActionResult(
|
|
591
|
+
extracted_content=f'✅ Navigated to {page.url}',
|
|
592
|
+
include_in_memory=True
|
|
593
|
+
)
|
|
594
|
+
|
|
595
|
+
except Exception as e:
|
|
596
|
+
self.logger.error(f"Navigation to {params.url} failed: {str(e)}")
|
|
597
|
+
return ActionResult(error=f"Navigation failed: {str(e)}", include_in_memory=True)
|
|
598
|
+
|
|
599
|
+
@BaseTool.action(
|
|
600
|
+
'Go back to the previous page.',
|
|
601
|
+
param_model=NoParamsAction
|
|
602
|
+
)
|
|
603
|
+
async def go_back_action(self, params: NoParamsAction, execution_context: Optional[ActionExecutionContext]):
|
|
604
|
+
"""Navigate back to the previous page."""
|
|
605
|
+
browser_context = execution_context.browser_context
|
|
606
|
+
if not browser_context:
|
|
607
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
608
|
+
|
|
609
|
+
try:
|
|
610
|
+
page = await browser_context.get_current_page()
|
|
611
|
+
await page.go_back()
|
|
612
|
+
await self._wait_for_page_load(page)
|
|
613
|
+
return ActionResult(
|
|
614
|
+
extracted_content='🔙 Navigated back',
|
|
615
|
+
include_in_memory=True
|
|
616
|
+
)
|
|
617
|
+
except Exception as e:
|
|
618
|
+
return ActionResult(error=f"Go back failed: {str(e)}", include_in_memory=True)
|
|
619
|
+
|
|
620
|
+
@BaseTool.action(
|
|
621
|
+
'Click on an element by its index from the previous observation.',
|
|
622
|
+
param_model=ClickElementAction
|
|
623
|
+
)
|
|
624
|
+
async def click_element(self, params: ClickElementAction, execution_context: Optional[ActionExecutionContext]):
|
|
625
|
+
"""Click an element by its index."""
|
|
626
|
+
if not isinstance(params, ClickElementAction):
|
|
627
|
+
from pydantic import TypeAdapter
|
|
628
|
+
params = TypeAdapter(ClickElementAction).validate_python(params)
|
|
629
|
+
|
|
630
|
+
browser_context = execution_context.browser_context
|
|
631
|
+
if not browser_context:
|
|
632
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
633
|
+
|
|
634
|
+
try:
|
|
635
|
+
context = browser_context
|
|
636
|
+
session = await context.get_session()
|
|
637
|
+
state = session.cached_state
|
|
638
|
+
|
|
639
|
+
if params.index not in state.selector_map:
|
|
640
|
+
return ActionResult(
|
|
641
|
+
error=f'Element with index {params.index} does not exist - retry or use alternative actions',
|
|
642
|
+
include_in_memory=True
|
|
643
|
+
)
|
|
644
|
+
|
|
645
|
+
element_node = state.selector_map[params.index]
|
|
646
|
+
initial_pages = len(session.context.pages)
|
|
647
|
+
|
|
648
|
+
# Check if element has file uploader
|
|
649
|
+
if hasattr(self, 'is_file_uploader') and await self.is_file_uploader(element_node):
|
|
650
|
+
return ActionResult(
|
|
651
|
+
extracted_content=f'Index {params.index} - has an element which opens file upload dialog. To upload files please use a specific function to upload files',
|
|
652
|
+
include_in_memory=True
|
|
653
|
+
)
|
|
654
|
+
|
|
655
|
+
download_path = await context._click_element_node(element_node)
|
|
656
|
+
if download_path:
|
|
657
|
+
msg = f'💾 Downloaded file to {download_path}'
|
|
658
|
+
else:
|
|
659
|
+
msg = f'🖱️ Clicked element with index {params.index}: {element_node.get_all_text_till_next_clickable_element(max_depth=2) if hasattr(element_node, "get_all_text_till_next_clickable_element") else ""}'
|
|
660
|
+
|
|
661
|
+
if len(session.context.pages) > initial_pages:
|
|
662
|
+
new_tab_msg = 'New tab opened - switching to it'
|
|
663
|
+
msg += f' - {new_tab_msg}'
|
|
664
|
+
await browser_context.switch_to_tab(-1)
|
|
665
|
+
|
|
666
|
+
return ActionResult(extracted_content=msg, include_in_memory=True)
|
|
667
|
+
except Exception as e:
|
|
668
|
+
return ActionResult(error=f"Click failed: {str(e)}", include_in_memory=True)
|
|
669
|
+
|
|
670
|
+
@BaseTool.action(
|
|
671
|
+
'Input text into an element by its index.',
|
|
672
|
+
param_model=InputTextAction
|
|
673
|
+
)
|
|
674
|
+
async def input_text(self, params: InputTextAction, execution_context: Optional[ActionExecutionContext]):
|
|
675
|
+
"""Input text into an element."""
|
|
676
|
+
if not isinstance(params, InputTextAction):
|
|
677
|
+
from pydantic import TypeAdapter
|
|
678
|
+
params = TypeAdapter(InputTextAction).validate_python(params)
|
|
679
|
+
|
|
680
|
+
browser_context = execution_context.browser_context
|
|
681
|
+
if not browser_context:
|
|
682
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
683
|
+
|
|
684
|
+
try:
|
|
685
|
+
context = browser_context
|
|
686
|
+
session = await context.get_session()
|
|
687
|
+
state = session.cached_state
|
|
688
|
+
|
|
689
|
+
if params.index not in state.selector_map:
|
|
690
|
+
return ActionResult(
|
|
691
|
+
error=f'Element index {params.index} does not exist - retry or use alternative actions',
|
|
692
|
+
include_in_memory=True
|
|
693
|
+
)
|
|
694
|
+
|
|
695
|
+
element_node = state.selector_map[params.index]
|
|
696
|
+
await context._input_text_element_node(element_node, params.text)
|
|
697
|
+
|
|
698
|
+
return ActionResult(
|
|
699
|
+
extracted_content=f'⌨️ Input {params.text} into index {params.index}',
|
|
700
|
+
include_in_memory=True
|
|
701
|
+
)
|
|
702
|
+
except Exception as e:
|
|
703
|
+
return ActionResult(error=f"Input text failed: {str(e)}", include_in_memory=True)
|
|
704
|
+
|
|
705
|
+
@BaseTool.action(
|
|
706
|
+
'Open a new browser tab with the specified URL.',
|
|
707
|
+
param_model=OpenTabAction
|
|
708
|
+
)
|
|
709
|
+
async def open_tab(self, params: OpenTabAction, execution_context: Optional[ActionExecutionContext]):
|
|
710
|
+
"""Open new tab with URL."""
|
|
711
|
+
if not isinstance(params, OpenTabAction):
|
|
712
|
+
from pydantic import TypeAdapter
|
|
713
|
+
params = TypeAdapter(OpenTabAction).validate_python(params)
|
|
714
|
+
|
|
715
|
+
browser_context = execution_context.browser_context
|
|
716
|
+
if not browser_context:
|
|
717
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
718
|
+
|
|
719
|
+
# GUARD: SSRF — same protection as go_to_url for the new-tab nav path.
|
|
720
|
+
# Offload the blocking DNS resolution to a thread (see go_to_url).
|
|
721
|
+
ssrf_error = await asyncio.get_running_loop().run_in_executor(
|
|
722
|
+
None, _check_url_ssrf, params.url)
|
|
723
|
+
if ssrf_error:
|
|
724
|
+
self.logger.warning(f"Blocked open_tab to {params.url}: {ssrf_error}")
|
|
725
|
+
return ActionResult(error=ssrf_error, include_in_memory=True)
|
|
726
|
+
|
|
727
|
+
try:
|
|
728
|
+
context = browser_context
|
|
729
|
+
self.logger.info(f"Opening new tab with {params.url}")
|
|
730
|
+
|
|
731
|
+
# Create new page
|
|
732
|
+
page = await context.session.context.new_page()
|
|
733
|
+
|
|
734
|
+
# Navigate to URL with timeout
|
|
735
|
+
response = await page.goto(params.url, timeout=30000, wait_until='domcontentloaded')
|
|
736
|
+
|
|
737
|
+
if not response or not response.ok:
|
|
738
|
+
status = response.status if response else 'No response'
|
|
739
|
+
await page.close() # Close the failed tab
|
|
740
|
+
return ActionResult(
|
|
741
|
+
error=f"Failed to load page: HTTP {status}",
|
|
742
|
+
include_in_memory=True
|
|
743
|
+
)
|
|
744
|
+
|
|
745
|
+
# Wait for page to be ready with proper error handling
|
|
746
|
+
await self._wait_for_page_load(page)
|
|
747
|
+
|
|
748
|
+
# Switch to the new tab
|
|
749
|
+
context.session.current_page = page
|
|
750
|
+
await page.bring_to_front()
|
|
751
|
+
|
|
752
|
+
# Update the cached state
|
|
753
|
+
await context._update_state()
|
|
754
|
+
|
|
755
|
+
self.logger.info(f"Successfully opened new tab with {page.url}")
|
|
756
|
+
return ActionResult(
|
|
757
|
+
extracted_content=f'📑 Opened new tab with {page.url}',
|
|
758
|
+
include_in_memory=True
|
|
759
|
+
)
|
|
760
|
+
except Exception as e:
|
|
761
|
+
self.logger.error(f"Open tab failed: {str(e)}")
|
|
762
|
+
return ActionResult(error=f"Open tab failed: {str(e)}", include_in_memory=True)
|
|
763
|
+
|
|
764
|
+
@BaseTool.action(
|
|
765
|
+
'Switch to a different browser tab by index.',
|
|
766
|
+
param_model=SwitchTabAction
|
|
767
|
+
)
|
|
768
|
+
async def switch_tab(self, params: SwitchTabAction, execution_context: Optional[ActionExecutionContext]):
|
|
769
|
+
"""Switch to a browser tab by index."""
|
|
770
|
+
if not isinstance(params, SwitchTabAction):
|
|
771
|
+
from pydantic import TypeAdapter
|
|
772
|
+
params = TypeAdapter(SwitchTabAction).validate_python(params)
|
|
773
|
+
|
|
774
|
+
browser_context = execution_context.browser_context
|
|
775
|
+
if not browser_context:
|
|
776
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
777
|
+
|
|
778
|
+
try:
|
|
779
|
+
context = browser_context
|
|
780
|
+
pages = context.session.context.pages if context.session else []
|
|
781
|
+
if 0 <= params.page_id < len(pages):
|
|
782
|
+
page = pages[params.page_id]
|
|
783
|
+
context.session.current_page = page
|
|
784
|
+
await page.bring_to_front()
|
|
785
|
+
|
|
786
|
+
# Update the cached state after switching tabs
|
|
787
|
+
await context._update_state()
|
|
788
|
+
|
|
789
|
+
self.logger.info(f"Switched to tab {params.page_id}: {page.url}")
|
|
790
|
+
msg = f'🔄 Switched to tab {params.page_id}: {page.url}'
|
|
791
|
+
else:
|
|
792
|
+
return ActionResult(
|
|
793
|
+
error=f'Tab index {params.page_id} out of range (0-{len(pages)-1})',
|
|
794
|
+
include_in_memory=True
|
|
795
|
+
)
|
|
796
|
+
return ActionResult(extracted_content=msg, include_in_memory=True)
|
|
797
|
+
except Exception as e:
|
|
798
|
+
self.logger.error(f"Switch tab failed: {str(e)}")
|
|
799
|
+
return ActionResult(error=str(e), include_in_memory=True)
|
|
800
|
+
|
|
801
|
+
@BaseTool.action(
|
|
802
|
+
'Scroll the page in the specified direction (up, down, left, right).',
|
|
803
|
+
param_model=ScrollAction
|
|
804
|
+
)
|
|
805
|
+
async def scroll(self, params: ScrollAction, execution_context: Optional[ActionExecutionContext]):
|
|
806
|
+
"""Scroll the page."""
|
|
807
|
+
if not isinstance(params, ScrollAction):
|
|
808
|
+
from pydantic import TypeAdapter
|
|
809
|
+
params = TypeAdapter(ScrollAction).validate_python(params)
|
|
810
|
+
|
|
811
|
+
browser_context = execution_context.browser_context
|
|
812
|
+
if not browser_context:
|
|
813
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
814
|
+
|
|
815
|
+
try:
|
|
816
|
+
page = await browser_context.get_current_page()
|
|
817
|
+
direction = params.direction
|
|
818
|
+
amount = params.amount or 500 # Default scroll amount
|
|
819
|
+
|
|
820
|
+
if direction == "up":
|
|
821
|
+
await page.evaluate(f"window.scrollBy(0, -{amount})")
|
|
822
|
+
msg = f'⬆️ Scrolled up {amount}px'
|
|
823
|
+
elif direction == "down":
|
|
824
|
+
await page.evaluate(f"window.scrollBy(0, {amount})")
|
|
825
|
+
msg = f'⬇️ Scrolled down {amount}px'
|
|
826
|
+
elif direction == "left":
|
|
827
|
+
await page.evaluate(f"window.scrollBy(-{amount}, 0)")
|
|
828
|
+
msg = f'⬅️ Scrolled left {amount}px'
|
|
829
|
+
elif direction == "right":
|
|
830
|
+
await page.evaluate(f"window.scrollBy({amount}, 0)")
|
|
831
|
+
msg = f'➡️ Scrolled right {amount}px'
|
|
832
|
+
else:
|
|
833
|
+
msg = f'❌ Invalid scroll direction: {direction}'
|
|
834
|
+
|
|
835
|
+
return ActionResult(extracted_content=msg, include_in_memory=True)
|
|
836
|
+
except Exception as e:
|
|
837
|
+
return ActionResult(error=f"Scroll failed: {str(e)}", include_in_memory=True)
|
|
838
|
+
|
|
839
|
+
@BaseTool.action(
|
|
840
|
+
'Send keyboard keys/shortcuts (e.g., "Enter", "Escape", "Control+A").',
|
|
841
|
+
param_model=SendKeysAction
|
|
842
|
+
)
|
|
843
|
+
async def send_keys(self, params: SendKeysAction, execution_context: Optional[ActionExecutionContext]):
|
|
844
|
+
"""Send keyboard keys."""
|
|
845
|
+
if not isinstance(params, SendKeysAction):
|
|
846
|
+
from pydantic import TypeAdapter
|
|
847
|
+
params = TypeAdapter(SendKeysAction).validate_python(params)
|
|
848
|
+
|
|
849
|
+
browser_context = execution_context.browser_context
|
|
850
|
+
if not browser_context:
|
|
851
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
852
|
+
|
|
853
|
+
try:
|
|
854
|
+
page = await browser_context.get_current_page()
|
|
855
|
+
await page.keyboard.press(params.keys)
|
|
856
|
+
return ActionResult(
|
|
857
|
+
extracted_content=f'⌨️ Sent keys: {params.keys}',
|
|
858
|
+
include_in_memory=True
|
|
859
|
+
)
|
|
860
|
+
except Exception as e:
|
|
861
|
+
return ActionResult(error=f"Send keys failed: {str(e)}", include_in_memory=True)
|
|
862
|
+
|
|
863
|
+
@BaseTool.action(
|
|
864
|
+
'Extract the current page content as text.',
|
|
865
|
+
param_model=ExtractPageContentAction
|
|
866
|
+
)
|
|
867
|
+
async def extract_page_content(self, params: ExtractPageContentAction, execution_context: Optional[ActionExecutionContext]):
|
|
868
|
+
"""Extract page content using accessibility snapshot for clean semantic content."""
|
|
869
|
+
|
|
870
|
+
browser_context = execution_context.browser_context
|
|
871
|
+
if not browser_context:
|
|
872
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
873
|
+
|
|
874
|
+
try:
|
|
875
|
+
page = await browser_context.get_current_page()
|
|
876
|
+
|
|
877
|
+
# FIX (Nov 6, 2025): Use accessibility API for clean semantic content
|
|
878
|
+
# Previously returned raw HTML (1-2M chars, 99% noise)
|
|
879
|
+
# Now returns accessibility snapshot (30-80K chars, 100% signal)
|
|
880
|
+
|
|
881
|
+
# FIX (Context Optimization v2): Adaptive truncation - balance data vs context
|
|
882
|
+
# Previous 3k limit was too aggressive - agent couldn't complete tasks (see logs: repeated extractions, task loops)
|
|
883
|
+
# New strategy: Provide useful data while preventing context bloat
|
|
884
|
+
# - Small/Medium content (<25k): Keep all - agent needs data to work
|
|
885
|
+
# - Large content (>25k): Truncate to 25k - still substantial, prevents overflow
|
|
886
|
+
# - Compaction at 65% handles overflow if needed
|
|
887
|
+
MAX_EXTRACT_CHARS = 25000 # 8x increase from 3k - reasonable for 128k+ models
|
|
888
|
+
|
|
889
|
+
try:
|
|
890
|
+
snapshot = await page.accessibility.snapshot()
|
|
891
|
+
|
|
892
|
+
if snapshot:
|
|
893
|
+
# Format snapshot as readable text
|
|
894
|
+
formatted_content = self._format_accessibility_snapshot(snapshot)
|
|
895
|
+
|
|
896
|
+
# Add page metadata
|
|
897
|
+
page_title = await page.title()
|
|
898
|
+
page_url = str(page.url)
|
|
899
|
+
|
|
900
|
+
# Combine into result
|
|
901
|
+
full_content = f"# {page_title}\n\nURL: {page_url}\n\n{formatted_content}"
|
|
902
|
+
|
|
903
|
+
# Adaptive truncation
|
|
904
|
+
if len(full_content) > MAX_EXTRACT_CHARS:
|
|
905
|
+
truncated_content = full_content[:MAX_EXTRACT_CHARS]
|
|
906
|
+
removed_chars = len(full_content) - MAX_EXTRACT_CHARS
|
|
907
|
+
result_text = f"{truncated_content}\n\n[... {removed_chars:,} more chars truncated. Use scroll + extract to see more, or navigate to sub-sections.]"
|
|
908
|
+
|
|
909
|
+
self.logger.info(
|
|
910
|
+
f"Extracted page content - {len(full_content):,} chars truncated to {len(result_text):,} chars"
|
|
911
|
+
)
|
|
912
|
+
else:
|
|
913
|
+
result_text = full_content
|
|
914
|
+
self.logger.info(
|
|
915
|
+
f"Extracted page content - {len(result_text):,} chars (accessibility API)"
|
|
916
|
+
)
|
|
917
|
+
|
|
918
|
+
return ActionResult(
|
|
919
|
+
extracted_content=result_text,
|
|
920
|
+
include_in_memory=True,
|
|
921
|
+
metadata={
|
|
922
|
+
'url': page_url,
|
|
923
|
+
'title': page_title,
|
|
924
|
+
'method': 'accessibility_snapshot',
|
|
925
|
+
'size': len(result_text),
|
|
926
|
+
'truncated': len(full_content) > MAX_EXTRACT_CHARS
|
|
927
|
+
}
|
|
928
|
+
)
|
|
929
|
+
except Exception as snapshot_error:
|
|
930
|
+
self.logger.warning(f"Accessibility snapshot failed: {snapshot_error}, falling back to HTML extraction")
|
|
931
|
+
|
|
932
|
+
# Fallback: If accessibility snapshot fails, use raw HTML with truncation
|
|
933
|
+
content = await page.content()
|
|
934
|
+
|
|
935
|
+
# Truncate to reasonable size with guidance
|
|
936
|
+
if len(content) > 50000:
|
|
937
|
+
self.logger.info(f"Large page ({len(content):,} chars), truncating to 50K with guidance")
|
|
938
|
+
content = content[:50000] + "\n\n[Content truncated - page has more content. Use CSS selectors to extract specific sections, or navigate to sub-pages for detailed content.]"
|
|
939
|
+
|
|
940
|
+
return ActionResult(
|
|
941
|
+
extracted_content=content,
|
|
942
|
+
include_in_memory=True,
|
|
943
|
+
metadata={
|
|
944
|
+
'method': 'html_fallback',
|
|
945
|
+
'truncated': len(content) > 50000
|
|
946
|
+
}
|
|
947
|
+
)
|
|
948
|
+
|
|
949
|
+
except Exception as e:
|
|
950
|
+
self.logger.error(f"Extract failed: {str(e)}")
|
|
951
|
+
return ActionResult(error=f"Extract failed: {str(e)}", include_in_memory=True)
|
|
952
|
+
|
|
953
|
+
@BaseTool.action(
|
|
954
|
+
'Refresh the current page.',
|
|
955
|
+
param_model=NoParamsAction
|
|
956
|
+
)
|
|
957
|
+
async def refresh_page(self, params: NoParamsAction, execution_context: Optional[ActionExecutionContext]):
|
|
958
|
+
"""Refresh the page."""
|
|
959
|
+
|
|
960
|
+
browser_context = execution_context.browser_context
|
|
961
|
+
if not browser_context:
|
|
962
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
963
|
+
|
|
964
|
+
try:
|
|
965
|
+
page = await browser_context.get_current_page()
|
|
966
|
+
self.logger.info(f"Refreshing page: {page.url}")
|
|
967
|
+
|
|
968
|
+
await page.reload(timeout=30000, wait_until='domcontentloaded')
|
|
969
|
+
|
|
970
|
+
# Wait for page to be ready with proper error handling
|
|
971
|
+
await self._wait_for_page_load(page)
|
|
972
|
+
|
|
973
|
+
# Update the cached state after refresh
|
|
974
|
+
await browser_context._update_state()
|
|
975
|
+
|
|
976
|
+
return ActionResult(
|
|
977
|
+
extracted_content='🔄 Page refreshed',
|
|
978
|
+
include_in_memory=True
|
|
979
|
+
)
|
|
980
|
+
except Exception as e:
|
|
981
|
+
self.logger.error(f"Refresh failed: {str(e)}")
|
|
982
|
+
return ActionResult(error=f"Refresh failed: {str(e)}", include_in_memory=True)
|
|
983
|
+
|
|
984
|
+
@BaseTool.action(
|
|
985
|
+
'Scroll down the page.',
|
|
986
|
+
param_model=NoParamsAction
|
|
987
|
+
)
|
|
988
|
+
async def scroll_down(self, params: NoParamsAction, execution_context: Optional[ActionExecutionContext]):
|
|
989
|
+
"""Scroll down."""
|
|
990
|
+
browser_context = execution_context.browser_context
|
|
991
|
+
if not browser_context:
|
|
992
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
993
|
+
|
|
994
|
+
try:
|
|
995
|
+
page = await browser_context.get_current_page()
|
|
996
|
+
await page.evaluate("window.scrollBy(0, 500)")
|
|
997
|
+
return ActionResult(
|
|
998
|
+
extracted_content='⬇️ Scrolled down',
|
|
999
|
+
include_in_memory=True
|
|
1000
|
+
)
|
|
1001
|
+
except Exception as e:
|
|
1002
|
+
return ActionResult(error=f"Scroll down failed: {str(e)}", include_in_memory=True)
|
|
1003
|
+
|
|
1004
|
+
@BaseTool.action(
|
|
1005
|
+
'Scroll up the page.',
|
|
1006
|
+
param_model=NoParamsAction
|
|
1007
|
+
)
|
|
1008
|
+
async def scroll_up(self, params: NoParamsAction, execution_context: Optional[ActionExecutionContext]):
|
|
1009
|
+
"""Scroll up."""
|
|
1010
|
+
browser_context = execution_context.browser_context
|
|
1011
|
+
if not browser_context:
|
|
1012
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
1013
|
+
|
|
1014
|
+
try:
|
|
1015
|
+
page = await browser_context.get_current_page()
|
|
1016
|
+
await page.evaluate("window.scrollBy(0, -500)")
|
|
1017
|
+
return ActionResult(
|
|
1018
|
+
extracted_content='⬆️ Scrolled up',
|
|
1019
|
+
include_in_memory=True
|
|
1020
|
+
)
|
|
1021
|
+
except Exception as e:
|
|
1022
|
+
return ActionResult(error=f"Scroll up failed: {str(e)}", include_in_memory=True)
|
|
1023
|
+
|
|
1024
|
+
@BaseTool.action(
|
|
1025
|
+
'Scroll to specific text on the page.',
|
|
1026
|
+
param_model=SendKeysAction
|
|
1027
|
+
)
|
|
1028
|
+
async def scroll_to_text(self, params: SendKeysAction, execution_context: Optional[ActionExecutionContext]):
|
|
1029
|
+
"""Scroll to text."""
|
|
1030
|
+
if not isinstance(params, SendKeysAction):
|
|
1031
|
+
from pydantic import TypeAdapter
|
|
1032
|
+
params = TypeAdapter(SendKeysAction).validate_python(params)
|
|
1033
|
+
|
|
1034
|
+
browser_context = execution_context.browser_context
|
|
1035
|
+
if not browser_context:
|
|
1036
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
1037
|
+
|
|
1038
|
+
try:
|
|
1039
|
+
page = await browser_context.get_current_page()
|
|
1040
|
+
# Use text locator to find and scroll to element
|
|
1041
|
+
locator = page.get_by_text(params.keys, exact=False).first
|
|
1042
|
+
if await locator.count() > 0:
|
|
1043
|
+
await locator.scroll_into_view_if_needed()
|
|
1044
|
+
return ActionResult(
|
|
1045
|
+
extracted_content=f'📜 Scrolled to text: {params.keys}',
|
|
1046
|
+
include_in_memory=True
|
|
1047
|
+
)
|
|
1048
|
+
else:
|
|
1049
|
+
return ActionResult(
|
|
1050
|
+
error=f'Text "{params.keys}" not found on page',
|
|
1051
|
+
include_in_memory=True
|
|
1052
|
+
)
|
|
1053
|
+
except Exception as e:
|
|
1054
|
+
return ActionResult(error=f"Scroll to text failed: {str(e)}", include_in_memory=True)
|
|
1055
|
+
|
|
1056
|
+
@BaseTool.action(
|
|
1057
|
+
'Get available options from a dropdown element by its index.',
|
|
1058
|
+
param_model=ClickElementAction
|
|
1059
|
+
)
|
|
1060
|
+
async def get_dropdown_options(self, params: ClickElementAction, execution_context: Optional[ActionExecutionContext]):
|
|
1061
|
+
"""Get dropdown options."""
|
|
1062
|
+
if not isinstance(params, ClickElementAction):
|
|
1063
|
+
from pydantic import TypeAdapter
|
|
1064
|
+
params = TypeAdapter(ClickElementAction).validate_python(params)
|
|
1065
|
+
|
|
1066
|
+
browser_context = execution_context.browser_context
|
|
1067
|
+
if not browser_context:
|
|
1068
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
1069
|
+
|
|
1070
|
+
try:
|
|
1071
|
+
context = browser_context
|
|
1072
|
+
session = await context.get_session()
|
|
1073
|
+
state = session.cached_state
|
|
1074
|
+
|
|
1075
|
+
if params.index not in state.selector_map:
|
|
1076
|
+
return ActionResult(
|
|
1077
|
+
error=f'Element index {params.index} does not exist',
|
|
1078
|
+
include_in_memory=True
|
|
1079
|
+
)
|
|
1080
|
+
|
|
1081
|
+
element_node = state.selector_map[params.index]
|
|
1082
|
+
locate_result = await context.get_locate_element(element_node)
|
|
1083
|
+
locator = locate_result.locator
|
|
1084
|
+
|
|
1085
|
+
# Get all option elements
|
|
1086
|
+
options = await locator.locator('option').all_text_contents()
|
|
1087
|
+
return ActionResult(
|
|
1088
|
+
extracted_content=f'📋 Dropdown options: {", ".join(options)}',
|
|
1089
|
+
include_in_memory=True
|
|
1090
|
+
)
|
|
1091
|
+
except Exception as e:
|
|
1092
|
+
return ActionResult(error=f"Get dropdown options failed: {str(e)}", include_in_memory=True)
|
|
1093
|
+
|
|
1094
|
+
@BaseTool.action(
|
|
1095
|
+
'Select a dropdown option by its text value.',
|
|
1096
|
+
param_model=InputTextAction
|
|
1097
|
+
)
|
|
1098
|
+
async def select_dropdown_option(self, params: InputTextAction, execution_context: Optional[ActionExecutionContext]):
|
|
1099
|
+
"""Select dropdown option."""
|
|
1100
|
+
if not isinstance(params, InputTextAction):
|
|
1101
|
+
from pydantic import TypeAdapter
|
|
1102
|
+
params = TypeAdapter(InputTextAction).validate_python(params)
|
|
1103
|
+
|
|
1104
|
+
browser_context = execution_context.browser_context
|
|
1105
|
+
if not browser_context:
|
|
1106
|
+
return ActionResult(error="Browser context not available", include_in_memory=True)
|
|
1107
|
+
|
|
1108
|
+
try:
|
|
1109
|
+
context = browser_context
|
|
1110
|
+
session = await context.get_session()
|
|
1111
|
+
state = session.cached_state
|
|
1112
|
+
|
|
1113
|
+
if params.index not in state.selector_map:
|
|
1114
|
+
return ActionResult(
|
|
1115
|
+
error=f'Element index {params.index} does not exist',
|
|
1116
|
+
include_in_memory=True
|
|
1117
|
+
)
|
|
1118
|
+
|
|
1119
|
+
element_node = state.selector_map[params.index]
|
|
1120
|
+
locate_result = await context.get_locate_element(element_node)
|
|
1121
|
+
locator = locate_result.locator
|
|
1122
|
+
|
|
1123
|
+
# Select by label/text
|
|
1124
|
+
await locator.select_option(label=params.text)
|
|
1125
|
+
return ActionResult(
|
|
1126
|
+
extracted_content=f'✅ Selected "{params.text}" from dropdown at index {params.index}',
|
|
1127
|
+
include_in_memory=True
|
|
1128
|
+
)
|
|
1129
|
+
except Exception as e:
|
|
1130
|
+
return ActionResult(error=f"Select dropdown option failed: {str(e)}", include_in_memory=True)
|
|
1131
|
+
|
|
1132
|
+
async def is_file_uploader(self, element_node):
|
|
1133
|
+
"""Check if element opens file uploader (placeholder)."""
|
|
1134
|
+
# This is a placeholder - actual implementation would check element type
|
|
1135
|
+
return False
|
|
1136
|
+
|
|
1137
|
+
async def _wait_for_page_load(self, page, timeout: int = 5000):
|
|
1138
|
+
"""Helper to wait for page load with proper timeout handling.
|
|
1139
|
+
|
|
1140
|
+
Args:
|
|
1141
|
+
page: The Playwright page object
|
|
1142
|
+
timeout: Timeout in milliseconds for networkidle (default 5s)
|
|
1143
|
+
"""
|
|
1144
|
+
try:
|
|
1145
|
+
# Try to wait for networkidle, but don't fail if it times out
|
|
1146
|
+
await page.wait_for_load_state('networkidle', timeout=timeout)
|
|
1147
|
+
except Exception as e:
|
|
1148
|
+
# If networkidle times out, page might still be usable
|
|
1149
|
+
# Just log a debug message and continue
|
|
1150
|
+
self.logger.debug(f"Network idle timeout (this is normal for pages with long-polling): {str(e)}")
|
|
1151
|
+
# Ensure DOM is at least loaded
|
|
1152
|
+
try:
|
|
1153
|
+
await page.wait_for_load_state('domcontentloaded', timeout=2000)
|
|
1154
|
+
except Exception:
|
|
1155
|
+
pass # Even domcontentloaded might fail on some pages
|
|
1156
|
+
|
|
1157
|
+
async def new_context(self, config: BrowserContextConfig = BrowserContextConfig(), session_id: Optional[str] = None) -> BrowserContext:
|
|
1158
|
+
"""Create a browser context"""
|
|
1159
|
+
return BrowserContext(config=config, browser=self, session_id=session_id)
|
|
1160
|
+
|
|
1161
|
+
async def get_playwright_browser(self) -> PlaywrightBrowser:
|
|
1162
|
+
"""Get a browser context"""
|
|
1163
|
+
if self._browser is None:
|
|
1164
|
+
return await self._init()
|
|
1165
|
+
|
|
1166
|
+
return self._browser
|
|
1167
|
+
|
|
1168
|
+
async def _init(self):
|
|
1169
|
+
"""Initialize the browser session"""
|
|
1170
|
+
self._playwright = await async_playwright().start()
|
|
1171
|
+
self._browser = await self._setup_browser(self._playwright)
|
|
1172
|
+
|
|
1173
|
+
return self._browser
|
|
1174
|
+
|
|
1175
|
+
async def _setup_cdp(self, playwright: Playwright) -> PlaywrightBrowser:
|
|
1176
|
+
"""Sets up and returns a Playwright Browser instance with anti-detection measures."""
|
|
1177
|
+
if not self.browser_config.cdp_url:
|
|
1178
|
+
raise ValueError('CDP URL is required')
|
|
1179
|
+
self.logger.info(f'Connecting to remote browser via CDP {self.browser_config.cdp_url}')
|
|
1180
|
+
browser = await playwright.chromium.connect_over_cdp(self.browser_config.cdp_url)
|
|
1181
|
+
return browser
|
|
1182
|
+
|
|
1183
|
+
async def _setup_wss(self, playwright: Playwright) -> PlaywrightBrowser:
|
|
1184
|
+
"""Sets up and returns a Playwright Browser instance with anti-detection measures."""
|
|
1185
|
+
if not self.browser_config.wss_url:
|
|
1186
|
+
raise ValueError('WSS URL is required')
|
|
1187
|
+
self.logger.info(f'Connecting to remote browser via WSS {self.browser_config.wss_url}')
|
|
1188
|
+
browser = await playwright.chromium.connect(self.browser_config.wss_url)
|
|
1189
|
+
return browser
|
|
1190
|
+
|
|
1191
|
+
async def _setup_browser_with_instance(self, playwright: Playwright) -> PlaywrightBrowser:
|
|
1192
|
+
"""Sets up and returns a Playwright Browser instance with anti-detection measures."""
|
|
1193
|
+
if not self.browser_config.chrome_instance_path:
|
|
1194
|
+
raise ValueError('Chrome instance path is required')
|
|
1195
|
+
import subprocess
|
|
1196
|
+
|
|
1197
|
+
import requests
|
|
1198
|
+
|
|
1199
|
+
try:
|
|
1200
|
+
# Check if browser is already running
|
|
1201
|
+
response = requests.get('http://localhost:9222/json/version', timeout=2)
|
|
1202
|
+
if response.status_code == 200:
|
|
1203
|
+
self.logger.info('Reusing existing Chrome instance')
|
|
1204
|
+
browser = await playwright.chromium.connect_over_cdp(
|
|
1205
|
+
endpoint_url='http://localhost:9222',
|
|
1206
|
+
timeout=20000, # 20 second timeout for connection
|
|
1207
|
+
)
|
|
1208
|
+
return browser
|
|
1209
|
+
except requests.ConnectionError:
|
|
1210
|
+
self.logger.debug('No existing Chrome instance found, starting a new one')
|
|
1211
|
+
|
|
1212
|
+
# Start a new Chrome instance
|
|
1213
|
+
subprocess.Popen(
|
|
1214
|
+
[
|
|
1215
|
+
self.browser_config.chrome_instance_path,
|
|
1216
|
+
'--remote-debugging-port=9222',
|
|
1217
|
+
]
|
|
1218
|
+
+ self.browser_config.extra_chromium_args,
|
|
1219
|
+
stdout=subprocess.DEVNULL,
|
|
1220
|
+
stderr=subprocess.DEVNULL,
|
|
1221
|
+
)
|
|
1222
|
+
|
|
1223
|
+
# Attempt to connect again after starting a new instance
|
|
1224
|
+
for _ in range(10):
|
|
1225
|
+
try:
|
|
1226
|
+
response = requests.get('http://localhost:9222/json/version', timeout=2)
|
|
1227
|
+
if response.status_code == 200:
|
|
1228
|
+
break
|
|
1229
|
+
except requests.ConnectionError:
|
|
1230
|
+
pass
|
|
1231
|
+
await asyncio.sleep(1)
|
|
1232
|
+
|
|
1233
|
+
# Attempt to connect again after starting a new instance
|
|
1234
|
+
try:
|
|
1235
|
+
browser = await playwright.chromium.connect_over_cdp(
|
|
1236
|
+
endpoint_url='http://localhost:9222',
|
|
1237
|
+
timeout=20000, # 20 second timeout for connection
|
|
1238
|
+
)
|
|
1239
|
+
return browser
|
|
1240
|
+
except Exception as e:
|
|
1241
|
+
self.logger.error(f'Failed to start a new Chrome instance.: {str(e)}')
|
|
1242
|
+
raise RuntimeError(
|
|
1243
|
+
' To start chrome in Debug mode, you need to close all existing Chrome instances and try again otherwise we can not connect to the instance.'
|
|
1244
|
+
)
|
|
1245
|
+
|
|
1246
|
+
async def _setup_standard_browser(self, playwright: Playwright) -> PlaywrightBrowser:
|
|
1247
|
+
"""Standard browser setup with proper server environment handling."""
|
|
1248
|
+
browser_args = self._configure_server_args(self.server_args)
|
|
1249
|
+
|
|
1250
|
+
# If in server environment, double-check headless mode
|
|
1251
|
+
if self.browser_config.auto_configure_for_server:
|
|
1252
|
+
# Check for server environment indicators
|
|
1253
|
+
is_server_env = (
|
|
1254
|
+
"SSH_CONNECTION" in os.environ or
|
|
1255
|
+
"SSH_CLIENT" in os.environ or
|
|
1256
|
+
not os.environ.get("DISPLAY") or
|
|
1257
|
+
os.environ.get("XDG_SESSION_TYPE") == "tty"
|
|
1258
|
+
)
|
|
1259
|
+
|
|
1260
|
+
# Final headless check for server environments
|
|
1261
|
+
if is_server_env and not self.browser_config.headless:
|
|
1262
|
+
logging.info("Server environment detected, overriding to headless mode")
|
|
1263
|
+
self.browser_config.headless = True
|
|
1264
|
+
|
|
1265
|
+
try:
|
|
1266
|
+
browser = await playwright.chromium.launch(
|
|
1267
|
+
headless=self.browser_config.headless,
|
|
1268
|
+
slow_mo=self.slow_mo,
|
|
1269
|
+
args=browser_args,
|
|
1270
|
+
timeout=self.timeout,
|
|
1271
|
+
executable_path=self.browser_path,
|
|
1272
|
+
env=self.env,
|
|
1273
|
+
)
|
|
1274
|
+
return browser
|
|
1275
|
+
except Exception as e:
|
|
1276
|
+
if not self.browser_config.headless:
|
|
1277
|
+
# If browser launch fails in headed mode, try again in headless mode
|
|
1278
|
+
logging.warning(f"Browser launch failed in headed mode: {str(e)}")
|
|
1279
|
+
logging.info("Retrying with headless=True")
|
|
1280
|
+
self.browser_config.headless = True
|
|
1281
|
+
browser = await playwright.chromium.launch(
|
|
1282
|
+
headless=True,
|
|
1283
|
+
slow_mo=self.slow_mo,
|
|
1284
|
+
args=browser_args,
|
|
1285
|
+
timeout=self.timeout,
|
|
1286
|
+
executable_path=self.browser_path,
|
|
1287
|
+
env=self.env,
|
|
1288
|
+
)
|
|
1289
|
+
return browser
|
|
1290
|
+
else:
|
|
1291
|
+
# If already in headless mode, re-raise the exception
|
|
1292
|
+
raise
|
|
1293
|
+
|
|
1294
|
+
async def _setup_browser(self, playwright: Playwright) -> PlaywrightBrowser:
|
|
1295
|
+
"""Sets up and returns a Playwright Browser instance with anti-detection measures."""
|
|
1296
|
+
try:
|
|
1297
|
+
if self.browser_config.cdp_url:
|
|
1298
|
+
return await self._setup_cdp(playwright)
|
|
1299
|
+
if self.browser_config.wss_url:
|
|
1300
|
+
return await self._setup_wss(playwright)
|
|
1301
|
+
elif self.browser_config.chrome_instance_path:
|
|
1302
|
+
return await self._setup_browser_with_instance(playwright)
|
|
1303
|
+
else:
|
|
1304
|
+
return await self._setup_standard_browser(playwright)
|
|
1305
|
+
except Exception as e:
|
|
1306
|
+
self.logger.error(f'Failed to initialize Playwright browser: {str(e)}')
|
|
1307
|
+
raise
|
|
1308
|
+
|
|
1309
|
+
async def close(self):
|
|
1310
|
+
"""Close browser and clean up resources."""
|
|
1311
|
+
await self._cleanup()
|
|
1312
|
+
|
|
1313
|
+
# Handle Xvfb cleanup
|
|
1314
|
+
if self._started_xvfb and self._xvfb_process:
|
|
1315
|
+
try:
|
|
1316
|
+
# Check if process is still running
|
|
1317
|
+
if self._xvfb_process.poll() is None:
|
|
1318
|
+
self._xvfb_process.terminate()
|
|
1319
|
+
self.logger.info(f"Terminated Xvfb process (PID: {self._xvfb_process.pid})")
|
|
1320
|
+
except Exception as e:
|
|
1321
|
+
self.logger.warning(f"Error cleaning up Xvfb: {e}")
|
|
1322
|
+
|
|
1323
|
+
self.logger.info("Browser closed and resources cleaned up")
|
|
1324
|
+
|
|
1325
|
+
def _format_accessibility_snapshot(self, node, indent=0):
|
|
1326
|
+
"""
|
|
1327
|
+
Format accessibility tree as readable text.
|
|
1328
|
+
|
|
1329
|
+
Args:
|
|
1330
|
+
node: Accessibility tree node from Playwright
|
|
1331
|
+
indent: Current indentation level
|
|
1332
|
+
|
|
1333
|
+
Returns:
|
|
1334
|
+
List of formatted text lines
|
|
1335
|
+
"""
|
|
1336
|
+
lines = []
|
|
1337
|
+
role = node.get('role', '')
|
|
1338
|
+
name = node.get('name', '')
|
|
1339
|
+
|
|
1340
|
+
# Skip empty or decorative elements
|
|
1341
|
+
if not name or role in ['none', 'presentation']:
|
|
1342
|
+
# Still process children of empty containers
|
|
1343
|
+
for child in node.get('children', []):
|
|
1344
|
+
lines.extend(self._format_accessibility_snapshot(child, indent))
|
|
1345
|
+
return lines
|
|
1346
|
+
|
|
1347
|
+
# Format based on role type
|
|
1348
|
+
prefix = ' ' * indent
|
|
1349
|
+
|
|
1350
|
+
if role == 'heading':
|
|
1351
|
+
# Format headings with markdown
|
|
1352
|
+
level = node.get('level', 1)
|
|
1353
|
+
lines.append(f"\n{'#' * level} {name}")
|
|
1354
|
+
elif role == 'link':
|
|
1355
|
+
# Format links with arrow
|
|
1356
|
+
lines.append(f"{prefix}→ {name}")
|
|
1357
|
+
elif role == 'button':
|
|
1358
|
+
# Format buttons with brackets
|
|
1359
|
+
lines.append(f"{prefix}[{name}]")
|
|
1360
|
+
elif role == 'listitem':
|
|
1361
|
+
# Format list items with bullets
|
|
1362
|
+
lines.append(f"{prefix}• {name}")
|
|
1363
|
+
elif role in ['paragraph', 'article', 'main', 'text']:
|
|
1364
|
+
# Format text content
|
|
1365
|
+
lines.append(f"{prefix}{name}")
|
|
1366
|
+
elif role == 'code':
|
|
1367
|
+
# Format code blocks
|
|
1368
|
+
lines.append(f"\n```\n{name}\n```")
|
|
1369
|
+
else:
|
|
1370
|
+
# Generic content - include if has meaningful text
|
|
1371
|
+
if name.strip():
|
|
1372
|
+
lines.append(f"{prefix}{name}")
|
|
1373
|
+
|
|
1374
|
+
# Recursively process children
|
|
1375
|
+
for child in node.get('children', []):
|
|
1376
|
+
lines.extend(self._format_accessibility_snapshot(child, indent + 1))
|
|
1377
|
+
|
|
1378
|
+
return '\n'.join(lines)
|
|
1379
|
+
|
|
1380
|
+
async def __aenter__(self):
|
|
1381
|
+
"""Async context manager entry - allows `async with Browser() as browser:`"""
|
|
1382
|
+
await self.initialize()
|
|
1383
|
+
return self
|
|
1384
|
+
|
|
1385
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
1386
|
+
"""Async context manager exit - ensures proper cleanup."""
|
|
1387
|
+
await self.close()
|
|
1388
|
+
return False # Don't suppress exceptions
|
|
1389
|
+
|
|
1390
|
+
def __del__(self):
|
|
1391
|
+
"""Cleanup resources when object is garbage collected.
|
|
1392
|
+
|
|
1393
|
+
WARNING: This is a last resort cleanup. Always prefer using:
|
|
1394
|
+
- `async with Browser() as browser:` (context manager)
|
|
1395
|
+
- Explicit `await browser.close()` call
|
|
1396
|
+
|
|
1397
|
+
Async cleanup in __del__ is unreliable and can cause issues.
|
|
1398
|
+
This method only handles synchronous cleanup (like Xvfb processes).
|
|
1399
|
+
"""
|
|
1400
|
+
# Log warning if browser wasn't properly closed
|
|
1401
|
+
if hasattr(self, '_browser') and self._browser:
|
|
1402
|
+
if hasattr(self, 'logger'):
|
|
1403
|
+
self.logger.warning(
|
|
1404
|
+
"Browser was not properly closed before garbage collection. "
|
|
1405
|
+
"Use 'async with Browser()' or call 'await browser.close()' explicitly."
|
|
1406
|
+
)
|
|
1407
|
+
else:
|
|
1408
|
+
logging.warning("Browser not properly closed before GC")
|
|
1409
|
+
|
|
1410
|
+
# Force nullify Python references (doesn't close actual browser process)
|
|
1411
|
+
self._browser = None
|
|
1412
|
+
self._playwright = None
|
|
1413
|
+
|
|
1414
|
+
# Synchronous cleanup of Xvfb process (this is safe in __del__)
|
|
1415
|
+
if hasattr(self, '_started_xvfb') and self._started_xvfb:
|
|
1416
|
+
if hasattr(self, '_xvfb_process') and self._xvfb_process:
|
|
1417
|
+
try:
|
|
1418
|
+
if self._xvfb_process.poll() is None:
|
|
1419
|
+
self._xvfb_process.terminate()
|
|
1420
|
+
# Give it a moment to terminate
|
|
1421
|
+
try:
|
|
1422
|
+
self._xvfb_process.wait(timeout=2)
|
|
1423
|
+
except Exception:
|
|
1424
|
+
# Force kill if termination times out
|
|
1425
|
+
self._xvfb_process.kill()
|
|
1426
|
+
except Exception as e:
|
|
1427
|
+
if hasattr(self, 'logger'):
|
|
1428
|
+
self.logger.debug(f"Error cleaning up Xvfb in __del__: {e}")
|
|
1429
|
+
# Swallow exceptions in __del__ to prevent crashes
|
|
1430
|
+
|
|
1431
|
+
async def _cleanup(self):
|
|
1432
|
+
"""Async cleanup of browser resources with timeout protection."""
|
|
1433
|
+
import asyncio
|
|
1434
|
+
|
|
1435
|
+
async def cleanup_with_timeout():
|
|
1436
|
+
try:
|
|
1437
|
+
if self._browser:
|
|
1438
|
+
await self._browser.close()
|
|
1439
|
+
self._browser = None
|
|
1440
|
+
|
|
1441
|
+
if self._playwright:
|
|
1442
|
+
await self._playwright.stop()
|
|
1443
|
+
self._playwright = None
|
|
1444
|
+
except Exception as e:
|
|
1445
|
+
self.logger.warning(f"Error in browser async cleanup: {e}")
|
|
1446
|
+
|
|
1447
|
+
try:
|
|
1448
|
+
# Give cleanup 5 seconds max before force killing
|
|
1449
|
+
await asyncio.wait_for(cleanup_with_timeout(), timeout=5.0)
|
|
1450
|
+
except asyncio.TimeoutError:
|
|
1451
|
+
self.logger.warning("Browser cleanup timed out after 5 seconds - forcing cleanup")
|
|
1452
|
+
# Force cleanup
|
|
1453
|
+
self._browser = None
|
|
1454
|
+
self._playwright = None
|
|
1455
|
+
except Exception as e:
|
|
1456
|
+
self.logger.warning(f"Error in browser cleanup: {e}")
|
|
1457
|
+
|